instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAVC::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAVC::setConfig(
OMX_INDEXTYPE index, const OMX_PTR _params) {
switch (index) {
case OMX_IndexConfigVideoIntraVOPRefresh:
{
OMX_CONFIG_INTRAREFRESHVOPTYPE *params =
(OMX_CONFIG_INTRAREFRESHVOPTYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
mKeyFrameRequested = params->IntraRefreshVOP;
return OMX_ErrorNone;
}
case OMX_IndexConfigVideoBitrate:
{
OMX_VIDEO_CONFIG_BITRATETYPE *params =
(OMX_VIDEO_CONFIG_BITRATETYPE *)_params;
if (!isValidOMXParam(params)) {
return OMX_ErrorBadParameter;
}
if (params->nPortIndex != kOutputPortIndex) {
return OMX_ErrorBadPortIndex;
}
if (mBitrate != params->nEncodeBitrate) {
mBitrate = params->nEncodeBitrate;
mBitrateUpdated = true;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::setConfig(index, _params);
}
}
| 174,202 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: http_splitline(struct worker *w, int fd, struct http *hp,
const struct http_conn *htc, int h1, int h2, int h3)
{
char *p, *q;
CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC);
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
/* XXX: Assert a NUL at rx.e ? */
Tcheck(htc->rxbuf);
/* Skip leading LWS */
for (p = htc->rxbuf.b ; vct_islws(*p); p++)
continue;
/* First field cannot contain SP, CRLF or CTL */
q = p;
for (; !vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h1].b = q;
hp->hd[h1].e = p;
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Second field cannot contain LWS or CTL */
q = p;
for (; !vct_islws(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h2].b = q;
hp->hd[h2].e = p;
if (!Tlen(hp->hd[h2]))
return (400);
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Third field is optional and cannot contain CTL */
q = p;
if (!vct_iscrlf(*p)) {
for (; !vct_iscrlf(*p); p++)
if (!vct_issep(*p) && vct_isctl(*p))
return (400);
}
hp->hd[h3].b = q;
hp->hd[h3].e = p;
/* Skip CRLF */
p += vct_skipcrlf(p);
*hp->hd[h1].e = '\0';
WSLH(w, fd, hp, h1);
*hp->hd[h2].e = '\0';
WSLH(w, fd, hp, h2);
if (hp->hd[h3].e != NULL) {
*hp->hd[h3].e = '\0';
WSLH(w, fd, hp, h3);
}
return (http_dissect_hdrs(w, hp, fd, p, htc));
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID: | http_splitline(struct worker *w, int fd, struct http *hp,
const struct http_conn *htc, int h1, int h2, int h3)
{
char *p, *q;
CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC);
CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC);
/* XXX: Assert a NUL at rx.e ? */
Tcheck(htc->rxbuf);
/* Skip leading LWS */
for (p = htc->rxbuf.b ; vct_islws(*p); p++)
continue;
/* First field cannot contain SP, CRLF or CTL */
q = p;
for (; !vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h1].b = q;
hp->hd[h1].e = p;
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Second field cannot contain LWS or CTL */
q = p;
for (; !vct_islws(*p); p++) {
if (vct_isctl(*p))
return (400);
}
hp->hd[h2].b = q;
hp->hd[h2].e = p;
if (!Tlen(hp->hd[h2]))
return (400);
/* Skip SP */
for (; vct_issp(*p); p++) {
if (vct_isctl(*p))
return (400);
}
/* Third field is optional and cannot contain CTL */
q = p;
if (!vct_iscrlf(p)) {
for (; !vct_iscrlf(p); p++)
if (!vct_issep(*p) && vct_isctl(*p))
return (400);
}
hp->hd[h3].b = q;
hp->hd[h3].e = p;
/* Skip CRLF */
p += vct_skipcrlf(p);
*hp->hd[h1].e = '\0';
WSLH(w, fd, hp, h1);
*hp->hd[h2].e = '\0';
WSLH(w, fd, hp, h2);
if (hp->hd[h3].e != NULL) {
*hp->hd[h3].e = '\0';
WSLH(w, fd, hp, h3);
}
return (http_dissect_hdrs(w, hp, fd, p, htc));
}
| 169,998 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_ofb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_ofb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
| 167,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: asmlinkage void do_ade(struct pt_regs *regs)
{
unsigned int __user *pc;
mm_segment_t seg;
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS,
1, 0, regs, regs->cp0_badvaddr);
/*
* Did we catch a fault trying to load an instruction?
* Or are we running in MIPS16 mode?
*/
if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1))
goto sigbus;
pc = (unsigned int __user *) exception_epc(regs);
if (user_mode(regs) && !test_thread_flag(TIF_FIXADE))
goto sigbus;
if (unaligned_action == UNALIGNED_ACTION_SIGNAL)
goto sigbus;
else if (unaligned_action == UNALIGNED_ACTION_SHOW)
show_registers(regs);
/*
* Do branch emulation only if we didn't forward the exception.
* This is all so but ugly ...
*/
seg = get_fs();
if (!user_mode(regs))
set_fs(KERNEL_DS);
emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc);
set_fs(seg);
return;
sigbus:
die_if_kernel("Kernel unaligned instruction access", regs);
force_sig(SIGBUS, current);
/*
* XXX On return from the signal handler we should advance the epc
*/
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | asmlinkage void do_ade(struct pt_regs *regs)
{
unsigned int __user *pc;
mm_segment_t seg;
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS,
1, regs, regs->cp0_badvaddr);
/*
* Did we catch a fault trying to load an instruction?
* Or are we running in MIPS16 mode?
*/
if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1))
goto sigbus;
pc = (unsigned int __user *) exception_epc(regs);
if (user_mode(regs) && !test_thread_flag(TIF_FIXADE))
goto sigbus;
if (unaligned_action == UNALIGNED_ACTION_SIGNAL)
goto sigbus;
else if (unaligned_action == UNALIGNED_ACTION_SHOW)
show_registers(regs);
/*
* Do branch emulation only if we didn't forward the exception.
* This is all so but ugly ...
*/
seg = get_fs();
if (!user_mode(regs))
set_fs(KERNEL_DS);
emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc);
set_fs(seg);
return;
sigbus:
die_if_kernel("Kernel unaligned instruction access", regs);
force_sig(SIGBUS, current);
/*
* XXX On return from the signal handler we should advance the epc
*/
}
| 165,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
case 0x2f8:
return true;
}
return false;
}
Commit Message: KVM: MTRR: remove MSR 0x2f8
MSR 0x2f8 accessed the 124th Variable Range MTRR ever since MTRR support
was introduced by 9ba075a664df ("KVM: MTRR support").
0x2f8 became harmful when 910a6aae4e2e ("KVM: MTRR: exactly define the
size of variable MTRRs") shrinked the array of VR MTRRs from 256 to 8,
which made access to index 124 out of bounds. The surrounding code only
WARNs in this situation, thus the guest gained a limited read/write
access to struct kvm_arch_vcpu.
0x2f8 is not a valid VR MTRR MSR, because KVM has/advertises only 16 VR
MTRR MSRs, 0x200-0x20f. Every VR MTRR is set up using two MSRs, 0x2f8
was treated as a PHYSBASE and 0x2f9 would be its PHYSMASK, but 0x2f9 was
not implemented in KVM, therefore 0x2f8 could never do anything useful
and getting rid of it is safe.
This fixes CVE-2016-3713.
Fixes: 910a6aae4e2e ("KVM: MTRR: exactly define the size of variable MTRRs")
Cc: [email protected]
Reported-by: David Matlack <[email protected]>
Signed-off-by: Andy Honig <[email protected]>
Signed-off-by: Radim Krčmář <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-284 | static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
}
return false;
}
| 167,345 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
s->method = ssl23_get_server_method(s->version);
if (s->method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
Commit Message:
CWE ID: | int ssl23_get_client_hello(SSL *s)
{
char buf_space[11]; /* Request this many bytes in initial read.
* We can detect SSL 3.0/TLS 1.0 Client Hellos
* ('type == 3') correctly only when the following
* is in a single record, which is not guaranteed by
* the protocol specification:
* Byte Content
* 0 type \
* 1/2 version > record header
* 3/4 length /
* 5 msg_type \
* 6-8 length > Client Hello message
* 9/10 client_version /
*/
char *buf= &(buf_space[0]);
unsigned char *p,*d,*d_len,*dd;
unsigned int i;
unsigned int csl,sil,cl;
int n=0,j;
int type=0;
int v[2];
if (s->state == SSL23_ST_SR_CLNT_HELLO_A)
{
/* read the initial header */
v[0]=v[1]=0;
if (!ssl3_setup_buffers(s)) goto err;
n=ssl23_read_bytes(s, sizeof buf_space);
if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */
p=s->packet;
memcpy(buf,p,n);
if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO))
{
/*
* SSLv2 header
*/
if ((p[3] == 0x00) && (p[4] == 0x02))
{
v[0]=p[3]; v[1]=p[4];
/* SSLv2 */
if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
else if (p[3] == SSL3_VERSION_MAJOR)
{
v[0]=p[3]; v[1]=p[4];
/* SSLv3/TLSv1 */
if (p[4] >= TLS1_VERSION_MINOR)
{
if (p[4] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (p[4] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
/* type=2; */ /* done later to survive restarts */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
{
type=1;
}
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
/* type=2; */
s->state=SSL23_ST_SR_CLNT_HELLO_B;
}
else if (!(s->options & SSL_OP_NO_SSLv2))
type=1;
}
}
else if ((p[0] == SSL3_RT_HANDSHAKE) &&
(p[1] == SSL3_VERSION_MAJOR) &&
(p[5] == SSL3_MT_CLIENT_HELLO) &&
((p[3] == 0 && p[4] < 5 /* silly record length? */)
|| (p[9] >= p[1])))
{
/*
* SSLv3 or tls1 header
*/
v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */
/* We must look at client_version inside the Client Hello message
* to get the correct minor version.
* However if we have only a pathologically small fragment of the
* Client Hello message, this would be difficult, and we'd have
* to read more records to find out.
* No known SSL 3.0 client fragments ClientHello like this,
* so we simply reject such connections to avoid
* protocol version downgrade attacks. */
if (p[3] == 0 && p[4] < 6)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL);
goto err;
}
/* if major version number > 3 set minor to a value
* which will use the highest version 3 we support.
* If TLS 2.0 ever appears we will need to revise
* this....
*/
if (p[9] > SSL3_VERSION_MAJOR)
v[1]=0xff;
else
v[1]=p[10]; /* minor version according to client_version */
if (v[1] >= TLS1_VERSION_MINOR)
{
if (v[1] >= TLS1_2_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_2))
{
s->version=TLS1_2_VERSION;
type=3;
}
else if (v[1] >= TLS1_1_VERSION_MINOR &&
!(s->options & SSL_OP_NO_TLSv1_1))
{
s->version=TLS1_1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
s->version=TLS1_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
}
else
{
/* client requests SSL 3.0 */
if (!(s->options & SSL_OP_NO_SSLv3))
{
s->version=SSL3_VERSION;
type=3;
}
else if (!(s->options & SSL_OP_NO_TLSv1))
{
/* we won't be able to use TLS of course,
* but this will send an appropriate alert */
s->version=TLS1_VERSION;
type=3;
}
}
}
else if ((strncmp("GET ", (char *)p,4) == 0) ||
(strncmp("POST ",(char *)p,5) == 0) ||
(strncmp("HEAD ",(char *)p,5) == 0) ||
(strncmp("PUT ", (char *)p,4) == 0))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST);
goto err;
}
else if (strncmp("CONNECT",(char *)p,7) == 0)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
}
/* ensure that TLS_MAX_VERSION is up-to-date */
OPENSSL_assert(s->version <= TLS_MAX_VERSION);
#ifdef OPENSSL_FIPS
if (FIPS_mode() && (s->version < TLS1_VERSION))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,
SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE);
goto err;
}
#endif
if (s->state == SSL23_ST_SR_CLNT_HELLO_B)
{
/* we have SSLv3/TLSv1 in an SSLv2 header
* (other cases skip this state) */
type=2;
p=s->packet;
v[0] = p[3]; /* == SSL3_VERSION_MAJOR */
v[1] = p[4];
/* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
* header is sent directly on the wire, not wrapped as a TLS
* record. It's format is:
* Byte Content
* 0-1 msg_length
* 2 msg_type
* 3-4 version
* 5-6 cipher_spec_length
* 7-8 session_id_length
* 9-10 challenge_length
* ... ...
*/
n=((p[0]&0x7f)<<8)|p[1];
if (n > (1024*4))
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE);
goto err;
}
if (n < 9)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
j=ssl23_read_bytes(s,n+2);
/* We previously read 11 bytes, so if j > 0, we must have
* j == n+2 == s->packet_length. We have at least 11 valid
* packet bytes. */
if (j <= 0) return(j);
ssl3_finish_mac(s, s->packet+2, s->packet_length-2);
if (s->msg_callback)
s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */
p=s->packet;
p+=5;
n2s(p,csl);
n2s(p,sil);
n2s(p,cl);
d=(unsigned char *)s->init_buf->data;
if ((csl+sil+cl+11) != s->packet_length) /* We can't have TLS extensions in SSL 2.0 format
* Client Hello, can we? Error condition should be
* '>' otherweise */
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH);
goto err;
}
/* record header: msg_type ... */
*(d++) = SSL3_MT_CLIENT_HELLO;
/* ... and length (actual value will be written later) */
d_len = d;
d += 3;
/* client_version */
*(d++) = SSL3_VERSION_MAJOR; /* == v[0] */
*(d++) = v[1];
/* lets populate the random area */
/* get the challenge_length */
i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl;
memset(d,0,SSL3_RANDOM_SIZE);
memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i);
d+=SSL3_RANDOM_SIZE;
/* no session-id reuse */
*(d++)=0;
/* ciphers */
j=0;
dd=d;
d+=2;
for (i=0; i<csl; i+=3)
{
if (p[i] != 0) continue;
*(d++)=p[i+1];
*(d++)=p[i+2];
j+=2;
}
s2n(j,dd);
/* COMPRESSION */
*(d++)=1;
*(d++)=0;
#if 0
/* copy any remaining data with may be extensions */
p = p+csl+sil+cl;
while (p < s->packet+s->packet_length)
{
*(d++)=*(p++);
}
#endif
i = (d-(unsigned char *)s->init_buf->data) - 4;
l2n3((long)i, d_len);
/* get the data reused from the init_buf */
s->s3->tmp.reuse_message=1;
s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO;
s->s3->tmp.message_size=i;
}
/* imaginary new state (for program structure): */
/* s->state = SSL23_SR_CLNT_HELLO_C */
if (type == 1)
{
#ifdef OPENSSL_NO_SSL2
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
#else
/* we are talking sslv2 */
/* we need to clean up the SSLv3/TLSv1 setup and put in the
* sslv2 stuff. */
if (s->s2 == NULL)
{
if (!ssl2_new(s))
goto err;
}
else
ssl2_clear(s);
if (s->s3 != NULL) ssl3_free(s);
if (!BUF_MEM_grow_clean(s->init_buf,
SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER))
{
goto err;
}
s->state=SSL2_ST_GET_CLIENT_HELLO_A;
if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3)
s->s2->ssl2_rollback=0;
else
/* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0
* (SSL 3.0 draft/RFC 2246, App. E.2) */
s->s2->ssl2_rollback=1;
/* setup the n bytes we have read so we get them from
* the sslv2 buffer */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
s->packet= &(s->s2->rbuf[0]);
memcpy(s->packet,buf,n);
s->s2->rbuf_left=n;
s->s2->rbuf_offs=0;
s->method=SSLv2_server_method();
s->handshake_func=s->method->ssl_accept;
#endif
}
if ((type == 2) || (type == 3))
{
/* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */
const SSL_METHOD *new_method;
new_method = ssl23_get_server_method(s->version);
if (new_method == NULL)
{
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL);
goto err;
}
s->method = new_method;
if (!ssl_init_wbio_buffer(s,1)) goto err;
if (type == 3)
{
/* put the 'n' bytes we have read into the input buffer
* for SSLv3 */
s->rstate=SSL_ST_READ_HEADER;
s->packet_length=n;
if (s->s3->rbuf.buf == NULL)
if (!ssl3_setup_read_buffer(s))
goto err;
s->packet= &(s->s3->rbuf.buf[0]);
memcpy(s->packet,buf,n);
s->s3->rbuf.left=n;
s->s3->rbuf.offset=0;
}
else
{
s->packet_length=0;
s->s3->rbuf.left=0;
s->s3->rbuf.offset=0;
}
#if 0 /* ssl3_get_client_hello does this */
s->client_version=(v[0]<<8)|v[1];
#endif
s->handshake_func=s->method->ssl_accept;
}
if ((type < 1) || (type > 3))
{
/* bad, very bad */
SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL);
goto err;
}
s->init_num=0;
if (buf != buf_space) OPENSSL_free(buf);
return(SSL_accept(s));
err:
if (buf != buf_space) OPENSSL_free(buf);
return(-1);
}
| 165,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void registerStreamURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static void registerStreamURLTask(void* context)
{
OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
if (WebBlobRegistry* registry = blobRegistry())
registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
}
| 170,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _client_protocol_timeout (GsmXSMPClient *client)
{
g_debug ("GsmXSMPClient: client_protocol_timeout for client '%s' in ICE status %d",
client->priv->description,
IceConnectionStatus (client->priv->ice_connection));
gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED);
gsm_client_disconnected (GSM_CLIENT (client));
return FALSE;
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
CWE ID: CWE-835 | _client_protocol_timeout (GsmXSMPClient *client)
| 168,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
Commit Message: Fixed possibility of Unsolicited Dialback Attacks
CWE ID: CWE-20 | static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0 && xhash_get(out->states, rkey) == (void*) conn_INPROGRESS) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
| 165,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::Rect ShellWindowFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
return gfx::Rect(client_bounds.x(),
std::max(0, client_bounds.y() - kCaptionHeight),
std::max(header_width, client_bounds.width()),
client_bounds.height() + kCaptionHeight);
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | gfx::Rect ShellWindowFrameView::GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
if (is_frameless_)
return client_bounds;
int closeButtonOffsetX =
(kCaptionHeight - close_button_->height()) / 2;
int header_width = close_button_->width() + closeButtonOffsetX * 2;
return gfx::Rect(client_bounds.x(),
std::max(0, client_bounds.y() - kCaptionHeight),
std::max(header_width, client_bounds.width()),
client_bounds.height() + kCaptionHeight);
}
| 170,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
mpeg4_decode_profile_level(s, gb);
if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(s->avctx->level > 0 && s->avctx->level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
}
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
Commit Message: avcodec/mpeg4videodec: Check read profile before setting it
Fixes: null pointer dereference
Fixes: ffmpeg_crash_7.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476 | int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
av_assert0(s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO);
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
| 169,160 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OpenSession() {
const int render_process_id = 1;
const int render_frame_id = 1;
const int page_request_id = 1;
const url::Origin security_origin =
url::Origin::Create(GURL("http://test.com"));
ASSERT_TRUE(opened_device_label_.empty());
MediaDeviceInfoArray video_devices;
{
base::RunLoop run_loop;
MediaDevicesManager::BoolDeviceTypes devices_to_enumerate;
devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true;
media_stream_manager_->media_devices_manager()->EnumerateDevices(
devices_to_enumerate,
base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(),
browser_context_.GetMediaDeviceIDSalt(),
security_origin, &video_devices));
run_loop.Run();
}
ASSERT_FALSE(video_devices.empty());
{
base::RunLoop run_loop;
media_stream_manager_->OpenDevice(
render_process_id, render_frame_id, page_request_id,
video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE,
MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(),
browser_context_.GetMediaDeviceIDSalt(),
security_origin},
base::BindOnce(&VideoCaptureTest::OnDeviceOpened,
base::Unretained(this), run_loop.QuitClosure()),
MediaStreamManager::DeviceStoppedCallback());
run_loop.Run();
}
ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_);
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | void OpenSession() {
const int render_process_id = 1;
const int render_frame_id = 1;
const int requester_id = 1;
const int page_request_id = 1;
const url::Origin security_origin =
url::Origin::Create(GURL("http://test.com"));
ASSERT_TRUE(opened_device_label_.empty());
MediaDeviceInfoArray video_devices;
{
base::RunLoop run_loop;
MediaDevicesManager::BoolDeviceTypes devices_to_enumerate;
devices_to_enumerate[MEDIA_DEVICE_TYPE_VIDEO_INPUT] = true;
media_stream_manager_->media_devices_manager()->EnumerateDevices(
devices_to_enumerate,
base::BindOnce(&VideoInputDevicesEnumerated, run_loop.QuitClosure(),
browser_context_.GetMediaDeviceIDSalt(),
security_origin, &video_devices));
run_loop.Run();
}
ASSERT_FALSE(video_devices.empty());
{
base::RunLoop run_loop;
media_stream_manager_->OpenDevice(
render_process_id, render_frame_id, requester_id, page_request_id,
video_devices[0].device_id, MEDIA_DEVICE_VIDEO_CAPTURE,
MediaDeviceSaltAndOrigin{browser_context_.GetMediaDeviceIDSalt(),
browser_context_.GetMediaDeviceIDSalt(),
security_origin},
base::BindOnce(&VideoCaptureTest::OnDeviceOpened,
base::Unretained(this), run_loop.QuitClosure()),
MediaStreamManager::DeviceStoppedCallback());
run_loop.Run();
}
ASSERT_NE(MediaStreamDevice::kNoId, opened_session_id_);
}
| 173,109 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
*/
if (ns_capable(ns->parent, cap_setid))
return true;
return false;
}
Commit Message: userns: Don't let unprivileged users trick privileged users into setting the id_map
When we require privilege for setting /proc/<pid>/uid_map or
/proc/<pid>/gid_map no longer allow an unprivileged user to
open the file and pass it to a privileged program to write
to the file.
Instead when privilege is required require both the opener and the
writer to have the necessary capabilities.
I have tested this code and verified that setting /proc/<pid>/uid_map
fails when an unprivileged user opens the file and a privielged user
attempts to set the mapping, that unprivileged users can still map
their own id, and that a privileged users can still setup an arbitrary
mapping.
Reported-by: Andy Lutomirski <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Andy Lutomirski <[email protected]>
CWE ID: CWE-264 | static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid,
static bool new_idmap_permitted(const struct file *file,
struct user_namespace *ns, int cap_setid,
struct uid_gid_map *new_map)
{
/* Allow mapping to your own filesystem ids */
if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) {
u32 id = new_map->extent[0].lower_first;
if (cap_setid == CAP_SETUID) {
kuid_t uid = make_kuid(ns->parent, id);
if (uid_eq(uid, current_fsuid()))
return true;
}
else if (cap_setid == CAP_SETGID) {
kgid_t gid = make_kgid(ns->parent, id);
if (gid_eq(gid, current_fsgid()))
return true;
}
}
/* Allow anyone to set a mapping that doesn't require privilege */
if (!cap_valid(cap_setid))
return true;
/* Allow the specified ids if we have the appropriate capability
* (CAP_SETUID or CAP_SETGID) over the parent user namespace.
* And the opener of the id file also had the approprpiate capability.
*/
if (ns_capable(ns->parent, cap_setid) &&
file_ns_capable(file, ns->parent, cap_setid))
return true;
return false;
}
| 166,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
Commit Message: Sanity check eapol_len in AirPDcapDecryptWPABroadcastKey
Bug: 12175
Change-Id: Iaf977ba48f8668bf8095800a115ff9a3472dd893
Reviewed-on: https://code.wireshark.org/review/15326
Petri-Dish: Michael Mann <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Alexis La Goutte <[email protected]>
Reviewed-by: Peter Wu <[email protected]>
Tested-by: Peter Wu <[email protected]>
CWE ID: CWE-125 | AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if ((key_bytes_len < GROUP_KEY_MIN_LEN) ||
(eapol_len < sizeof(EAPOL_RSN_KEY)) ||
(key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
| 167,157 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int X509_verify_cert(X509_STORE_CTX *ctx)
{
X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
int bad_chain = 0;
X509_VERIFY_PARAM *param = ctx->param;
int depth, i, ok = 0;
int num, j, retry;
int (*cb) (int xok, X509_STORE_CTX *xctx);
STACK_OF(X509) *sktmp = NULL;
if (ctx->cert == NULL) {
X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return -1;
}
cb = ctx->verify_cb;
/*
* first we make sure the chain we are going to build is present and that
* the first entry is in place
*/
if (ctx->chain == NULL) {
if (((ctx->chain = sk_X509_new_null()) == NULL) ||
(!sk_X509_push(ctx->chain, ctx->cert))) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
ctx->last_untrusted = 1;
}
/* We use a temporary STACK so we can chop and hack at it */
if (ctx->untrusted != NULL
&& (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
num = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, num - 1);
depth = param->depth;
for (;;) {
/* If we have enough, we break */
if (depth < num)
break; /* FIXME: If this happens, we should take
* note of it and, if appropriate, use the
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
/* If we were passed a cert chain, use it first */
if (ctx->untrusted != NULL) {
xtmp = find_issuer(ctx, sktmp, x);
if (xtmp != NULL) {
if (!sk_X509_push(ctx->chain, xtmp)) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
(void)sk_X509_delete_ptr(sktmp, xtmp);
ctx->last_untrusted++;
x = xtmp;
num++;
/*
* reparse the full chain for the next one
*/
continue;
}
}
break;
}
/* Remember how many untrusted certs we have */
j = num;
/*
* at this point, chain should contain a list of untrusted certificates.
* We now need to add at least one trusted one, if possible, otherwise we
* complain.
*/
do {
/*
* Examine last certificate in chain and see if it is self signed.
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (ctx->check_issued(ctx, x, x)) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
* We have a single self signed certificate: see if we can
* find it in the store. We must have an exact match to avoid
* possible impersonation.
*/
ok = ctx->get_issuer(&xtmp, ctx, x);
if ((ok <= 0) || X509_cmp(x, xtmp)) {
ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
ctx->current_cert = x;
ctx->error_depth = i - 1;
if (ok == 1)
X509_free(xtmp);
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
} else {
/*
* We have a match: replace certificate with store
* version so we get any trust settings.
*/
X509_free(x);
x = xtmp;
(void)sk_X509_set(ctx->chain, i - 1, x);
ctx->last_untrusted = 0;
}
} else {
/*
* extract and save self signed certificate for later use
*/
chain_ss = sk_X509_pop(ctx->chain);
ctx->last_untrusted--;
num--;
j--;
x = sk_X509_value(ctx->chain, num - 1);
}
}
/* We now lookup certs from the certificate store */
for (;;) {
/* If we have enough, we break */
if (depth < num)
break;
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
if (ok == 0)
break;
x = xtmp;
if (!sk_X509_push(ctx->chain, x)) {
X509_free(xtmp);
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
return 0;
}
num++;
}
/*
* If we haven't got a least one certificate from our store then check
* if there is an alternative chain that could be used. We only do this
* if the user hasn't switched off alternate chain checking
*/
retry = 0;
if (j == ctx->last_untrusted &&
!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
while (j-- > 1) {
xtmp2 = sk_X509_value(ctx->chain, j - 1);
ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
if (ok < 0)
goto end;
/* Check if we found an alternate chain */
if (ok > 0) {
/*
* Free up the found cert we'll add it again later
*/
X509_free(xtmp);
/*
* Dump all the certs above this point - we've found an
* alternate chain
*/
while (num > j) {
xtmp = sk_X509_pop(ctx->chain);
X509_free(xtmp);
num--;
ctx->last_untrusted--;
}
retry = 1;
break;
}
}
}
} while (retry);
/* Is last certificate looked up self signed? */
if (!ctx->check_issued(ctx, x, x)) {
if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
if (ctx->last_untrusted >= num)
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
else
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
ctx->current_cert = x;
} else {
sk_X509_push(ctx->chain, chain_ss);
num++;
ctx->last_untrusted = num;
ctx->current_cert = chain_ss;
ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
chain_ss = NULL;
}
ctx->error_depth = num - 1;
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* We have the chain complete: now we need to check its purpose */
ok = check_chain_extensions(ctx);
if (!ok)
goto end;
/* Check name constraints */
ok = check_name_constraints(ctx);
if (!ok)
goto end;
/* The chain extensions are OK: check trust */
if (param->trust > 0)
ok = check_trust(ctx);
if (!ok)
goto end;
/* We may as well copy down any DSA parameters that are required */
X509_get_pubkey_parameters(NULL, ctx->chain);
/*
* Check revocation status: we do this after copying parameters because
* they may be needed for CRL signature verification.
*/
ok = ctx->check_revocation(ctx);
if (!ok)
goto end;
/* At this point, we have a chain and need to verify it */
if (ctx->verify != NULL)
ok = ctx->verify(ctx);
else
ok = internal_verify(ctx);
if (!ok)
goto end;
#ifndef OPENSSL_NO_RFC3779
/* RFC 3779 path validation, now that CRL check has been done */
ok = v3_asid_validate_path(ctx);
if (!ok)
goto end;
ok = v3_addr_validate_path(ctx);
if (!ok)
goto end;
#endif
/* If we get this far evaluate policies */
if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
ok = ctx->check_policy(ctx);
if (!ok)
goto end;
if (0) {
end:
X509_get_pubkey_parameters(NULL, ctx->chain);
}
if (sktmp != NULL)
sk_X509_free(sktmp);
if (chain_ss != NULL)
X509_free(chain_ss);
return ok;
}
Commit Message:
CWE ID: CWE-254 | int X509_verify_cert(X509_STORE_CTX *ctx)
{
X509 *x, *xtmp, *xtmp2, *chain_ss = NULL;
int bad_chain = 0;
X509_VERIFY_PARAM *param = ctx->param;
int depth, i, ok = 0;
int num, j, retry;
int (*cb) (int xok, X509_STORE_CTX *xctx);
STACK_OF(X509) *sktmp = NULL;
if (ctx->cert == NULL) {
X509err(X509_F_X509_VERIFY_CERT, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY);
return -1;
}
cb = ctx->verify_cb;
/*
* first we make sure the chain we are going to build is present and that
* the first entry is in place
*/
if (ctx->chain == NULL) {
if (((ctx->chain = sk_X509_new_null()) == NULL) ||
(!sk_X509_push(ctx->chain, ctx->cert))) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&ctx->cert->references, 1, CRYPTO_LOCK_X509);
ctx->last_untrusted = 1;
}
/* We use a temporary STACK so we can chop and hack at it */
if (ctx->untrusted != NULL
&& (sktmp = sk_X509_dup(ctx->untrusted)) == NULL) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
num = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, num - 1);
depth = param->depth;
for (;;) {
/* If we have enough, we break */
if (depth < num)
break; /* FIXME: If this happens, we should take
* note of it and, if appropriate, use the
* X509_V_ERR_CERT_CHAIN_TOO_LONG error code
* later. */
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
/* If we were passed a cert chain, use it first */
if (ctx->untrusted != NULL) {
xtmp = find_issuer(ctx, sktmp, x);
if (xtmp != NULL) {
if (!sk_X509_push(ctx->chain, xtmp)) {
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
goto end;
}
CRYPTO_add(&xtmp->references, 1, CRYPTO_LOCK_X509);
(void)sk_X509_delete_ptr(sktmp, xtmp);
ctx->last_untrusted++;
x = xtmp;
num++;
/*
* reparse the full chain for the next one
*/
continue;
}
}
break;
}
/* Remember how many untrusted certs we have */
j = num;
/*
* at this point, chain should contain a list of untrusted certificates.
* We now need to add at least one trusted one, if possible, otherwise we
* complain.
*/
do {
/*
* Examine last certificate in chain and see if it is self signed.
*/
i = sk_X509_num(ctx->chain);
x = sk_X509_value(ctx->chain, i - 1);
if (ctx->check_issued(ctx, x, x)) {
/* we have a self signed certificate */
if (sk_X509_num(ctx->chain) == 1) {
/*
* We have a single self signed certificate: see if we can
* find it in the store. We must have an exact match to avoid
* possible impersonation.
*/
ok = ctx->get_issuer(&xtmp, ctx, x);
if ((ok <= 0) || X509_cmp(x, xtmp)) {
ctx->error = X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
ctx->current_cert = x;
ctx->error_depth = i - 1;
if (ok == 1)
X509_free(xtmp);
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
} else {
/*
* We have a match: replace certificate with store
* version so we get any trust settings.
*/
X509_free(x);
x = xtmp;
(void)sk_X509_set(ctx->chain, i - 1, x);
ctx->last_untrusted = 0;
}
} else {
/*
* extract and save self signed certificate for later use
*/
chain_ss = sk_X509_pop(ctx->chain);
ctx->last_untrusted--;
num--;
j--;
x = sk_X509_value(ctx->chain, num - 1);
}
}
/* We now lookup certs from the certificate store */
for (;;) {
/* If we have enough, we break */
if (depth < num)
break;
/* If we are self signed, we break */
if (ctx->check_issued(ctx, x, x))
break;
ok = ctx->get_issuer(&xtmp, ctx, x);
if (ok < 0)
return ok;
if (ok == 0)
break;
x = xtmp;
if (!sk_X509_push(ctx->chain, x)) {
X509_free(xtmp);
X509err(X509_F_X509_VERIFY_CERT, ERR_R_MALLOC_FAILURE);
return 0;
}
num++;
}
/*
* If we haven't got a least one certificate from our store then check
* if there is an alternative chain that could be used. We only do this
* if the user hasn't switched off alternate chain checking
*/
retry = 0;
if (j == ctx->last_untrusted &&
!(ctx->param->flags & X509_V_FLAG_NO_ALT_CHAINS)) {
while (j-- > 1) {
xtmp2 = sk_X509_value(ctx->chain, j - 1);
ok = ctx->get_issuer(&xtmp, ctx, xtmp2);
if (ok < 0)
goto end;
/* Check if we found an alternate chain */
if (ok > 0) {
/*
* Free up the found cert we'll add it again later
*/
X509_free(xtmp);
/*
* Dump all the certs above this point - we've found an
* alternate chain
*/
while (num > j) {
xtmp = sk_X509_pop(ctx->chain);
X509_free(xtmp);
num--;
}
ctx->last_untrusted = sk_X509_num(ctx->chain);
retry = 1;
break;
}
}
}
} while (retry);
/* Is last certificate looked up self signed? */
if (!ctx->check_issued(ctx, x, x)) {
if ((chain_ss == NULL) || !ctx->check_issued(ctx, x, chain_ss)) {
if (ctx->last_untrusted >= num)
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
else
ctx->error = X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
ctx->current_cert = x;
} else {
sk_X509_push(ctx->chain, chain_ss);
num++;
ctx->last_untrusted = num;
ctx->current_cert = chain_ss;
ctx->error = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
chain_ss = NULL;
}
ctx->error_depth = num - 1;
bad_chain = 1;
ok = cb(0, ctx);
if (!ok)
goto end;
}
/* We have the chain complete: now we need to check its purpose */
ok = check_chain_extensions(ctx);
if (!ok)
goto end;
/* Check name constraints */
ok = check_name_constraints(ctx);
if (!ok)
goto end;
/* The chain extensions are OK: check trust */
if (param->trust > 0)
ok = check_trust(ctx);
if (!ok)
goto end;
/* We may as well copy down any DSA parameters that are required */
X509_get_pubkey_parameters(NULL, ctx->chain);
/*
* Check revocation status: we do this after copying parameters because
* they may be needed for CRL signature verification.
*/
ok = ctx->check_revocation(ctx);
if (!ok)
goto end;
/* At this point, we have a chain and need to verify it */
if (ctx->verify != NULL)
ok = ctx->verify(ctx);
else
ok = internal_verify(ctx);
if (!ok)
goto end;
#ifndef OPENSSL_NO_RFC3779
/* RFC 3779 path validation, now that CRL check has been done */
ok = v3_asid_validate_path(ctx);
if (!ok)
goto end;
ok = v3_addr_validate_path(ctx);
if (!ok)
goto end;
#endif
/* If we get this far evaluate policies */
if (!bad_chain && (ctx->param->flags & X509_V_FLAG_POLICY_CHECK))
ok = ctx->check_policy(ctx);
if (!ok)
goto end;
if (0) {
end:
X509_get_pubkey_parameters(NULL, ctx->chain);
}
if (sktmp != NULL)
sk_X509_free(sktmp);
if (chain_ss != NULL)
X509_free(chain_ss);
return ok;
}
| 164,767 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
goto err_size;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, usize);
if (ret)
return -EFAULT;
out:
return ret;
err_size:
ret = -E2BIG;
goto out;
}
Commit Message: sched: Fix information leak in sys_sched_getattr()
We're copying the on-stack structure to userspace, but forgot to give
the right number of bytes to copy. This allows the calling process to
obtain up to PAGE_SIZE bytes from the stack (and possibly adjacent
kernel memory).
This fix copies only as much as we actually have on the stack
(attr->size defaults to the size of the struct) and leaves the rest of
the userspace-provided buffer untouched.
Found using kmemcheck + trinity.
Fixes: d50dde5a10f30 ("sched: Add new scheduler syscalls to support an extended scheduling parameters ABI")
Cc: Dario Faggioli <[email protected]>
Cc: Juri Lelli <[email protected]>
Cc: Ingo Molnar <[email protected]>
Signed-off-by: Vegard Nossum <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Thomas Gleixner <[email protected]>
CWE ID: CWE-200 | static int sched_read_attr(struct sched_attr __user *uattr,
struct sched_attr *attr,
unsigned int usize)
{
int ret;
if (!access_ok(VERIFY_WRITE, uattr, usize))
return -EFAULT;
/*
* If we're handed a smaller struct than we know of,
* ensure all the unknown bits are 0 - i.e. old
* user-space does not get uncomplete information.
*/
if (usize < sizeof(*attr)) {
unsigned char *addr;
unsigned char *end;
addr = (void *)attr + usize;
end = (void *)attr + sizeof(*attr);
for (; addr < end; addr++) {
if (*addr)
goto err_size;
}
attr->size = usize;
}
ret = copy_to_user(uattr, attr, attr->size);
if (ret)
return -EFAULT;
out:
return ret;
err_size:
ret = -E2BIG;
goto out;
}
| 167,575 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HostPortAllocatorSession::OnSessionRequestDone(
UrlFetcher* url_fetcher,
const net::URLRequestStatus& status,
int response_code,
const std::string& response) {
url_fetchers_.erase(url_fetcher);
delete url_fetcher;
if (response_code != net::HTTP_OK) {
LOG(WARNING) << "Received error when allocating relay session: "
<< response_code;
TryCreateRelaySession();
return;
}
ReceiveSessionResponse(response);
}
Commit Message: Remove UrlFetcher from remoting and use the one in net instead.
BUG=133790
TEST=Stop and restart the Me2Me host. It should still work.
Review URL: https://chromiumcodereview.appspot.com/10637008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void HostPortAllocatorSession::OnSessionRequestDone(
void HostPortAllocatorSession::OnURLFetchComplete(
const net::URLFetcher* source) {
url_fetchers_.erase(source);
delete source;
if (source->GetResponseCode() != net::HTTP_OK) {
LOG(WARNING) << "Received error when allocating relay session: "
<< source->GetResponseCode();
TryCreateRelaySession();
return;
}
std::string response;
source->GetResponseAsString(&response);
ReceiveSessionResponse(response);
}
| 170,810 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)
{
int extdatalen=0;
unsigned char *orig = buf;
unsigned char *ret = buf;
/* don't add extensions for SSLv3 unless doing secure renegotiation */
if (s->client_version == SSL3_VERSION
&& !s->s3->send_connection_binding)
return orig;
ret+=2;
if (ret>=limit) return NULL; /* this really never occurs, but ... */
if (s->tlsext_hostname != NULL)
{
/* Add TLS extension servername to the Client Hello message */
unsigned long size_str;
long lenmax;
/* check for enough space.
4 for the servername type and entension length
2 for servernamelist length
1 for the hostname type
2 for hostname length
+ hostname length
*/
if ((lenmax = limit - ret - 9) < 0
|| (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
return NULL;
/* extension type and length */
s2n(TLSEXT_TYPE_server_name,ret);
s2n(size_str+5,ret);
/* length of servername list */
s2n(size_str+3,ret);
/* hostname type, length and hostname */
*(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
s2n(size_str,ret);
memcpy(ret, s->tlsext_hostname, size_str);
ret+=size_str;
}
/* Add RI if renegotiating */
if (s->renegotiate)
{
int el;
if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_renegotiate,ret);
s2n(el,ret);
if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#ifndef OPENSSL_NO_SRP
/* Add SRP username if there is one */
if (s->srp_ctx.login != NULL)
{ /* Add TLS extension SRP username to the Client Hello message */
int login_len = strlen(s->srp_ctx.login);
if (login_len > 255 || login_len == 0)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/* check for enough space.
4 for the srp type type and entension length
1 for the srp user identity
+ srp user identity length
*/
if ((limit - ret - 5 - login_len) < 0) return NULL;
/* fill in the extension */
s2n(TLSEXT_TYPE_srp,ret);
s2n(login_len+1,ret);
(*ret++) = (unsigned char) login_len;
memcpy(ret, s->srp_ctx.login, login_len);
ret+=login_len;
}
#endif
#ifndef OPENSSL_NO_EC
if (s->tlsext_ecpointformatlist != NULL)
{
/* Add TLS extension ECPointFormats to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 5) < 0) return NULL;
if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ecpointformatlist_length > 255)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_ec_point_formats,ret);
s2n(s->tlsext_ecpointformatlist_length + 1,ret);
*(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
ret+=s->tlsext_ecpointformatlist_length;
}
if (s->tlsext_ellipticcurvelist != NULL)
{
/* Add TLS extension EllipticCurves to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 6) < 0) return NULL;
if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ellipticcurvelist_length > 65532)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_elliptic_curves,ret);
s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
/* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
* elliptic_curve_list, but the examples use two bytes.
* http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
* resolves this to two bytes.
*/
s2n(s->tlsext_ellipticcurvelist_length, ret);
memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
ret+=s->tlsext_ellipticcurvelist_length;
}
#endif /* OPENSSL_NO_EC */
if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
{
int ticklen;
if (!s->new_session && s->session && s->session->tlsext_tick)
ticklen = s->session->tlsext_ticklen;
else if (s->session && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data)
{
ticklen = s->tlsext_session_ticket->length;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick)
return NULL;
memcpy(s->session->tlsext_tick,
s->tlsext_session_ticket->data,
ticklen);
s->session->tlsext_ticklen = ticklen;
}
else
ticklen = 0;
if (ticklen == 0 && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data == NULL)
goto skip_ext;
/* Check for enough room 2 for extension type, 2 for len
* rest for ticket
*/
if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
s2n(TLSEXT_TYPE_session_ticket,ret);
s2n(ticklen,ret);
if (ticklen)
{
memcpy(ret, s->session->tlsext_tick, ticklen);
ret += ticklen;
}
}
skip_ext:
if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
{
if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)
return NULL;
s2n(TLSEXT_TYPE_signature_algorithms,ret);
s2n(sizeof(tls12_sigalgs) + 2, ret);
s2n(sizeof(tls12_sigalgs), ret);
memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));
ret += sizeof(tls12_sigalgs);
}
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL &&
s->version != DTLS1_VERSION)
{
size_t col = s->s3->client_opaque_prf_input_len;
if ((long)(limit - ret - 6 - col < 0))
return NULL;
if (col > 0xFFFD) /* can't happen */
return NULL;
s2n(TLSEXT_TYPE_opaque_prf_input, ret);
s2n(col + 2, ret);
s2n(col, ret);
memcpy(ret, s->s3->client_opaque_prf_input, col);
ret += col;
}
#endif
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
s->version != DTLS1_VERSION)
{
int i;
long extlen, idlen, itmp;
OCSP_RESPID *id;
idlen = 0;
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
itmp = i2d_OCSP_RESPID(id, NULL);
if (itmp <= 0)
return NULL;
idlen += itmp + 2;
}
if (s->tlsext_ocsp_exts)
{
extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
if (extlen < 0)
return NULL;
}
else
extlen = 0;
if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
if (extlen + idlen > 0xFFF0)
return NULL;
s2n(extlen + idlen + 5, ret);
*(ret++) = TLSEXT_STATUSTYPE_ocsp;
s2n(idlen, ret);
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
/* save position of id len */
unsigned char *q = ret;
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
/* skip over id len */
ret += 2;
itmp = i2d_OCSP_RESPID(id, &ret);
/* write id len */
s2n(itmp, q);
}
s2n(extlen, ret);
if (extlen > 0)
i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension */
if ((limit - ret - 4 - 1) < 0)
return NULL;
s2n(TLSEXT_TYPE_heartbeat,ret);
s2n(1,ret);
/* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_TLSEXT_HB_ENABLED;
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
{
/* The client advertises an emtpy extension to indicate its
* support for Next Protocol Negotiation */
if (limit - ret - 4 < 0)
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg,ret);
s2n(0,ret);
}
#endif
#ifndef OPENSSL_NO_SRTP
if(SSL_get_srtp_profiles(s))
{
int el;
ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_use_srtp,ret);
s2n(el,ret);
if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#endif
/* Add padding to workaround bugs in F5 terminators.
* See https://tools.ietf.org/html/draft-agl-tls-padding-03
*
* NB: because this code works out the length of all existing
* extensions it MUST always appear last.
*/
if (s->options & SSL_OP_TLSEXT_PADDING)
{
int hlen = ret - (unsigned char *)s->init_buf->data;
/* The code in s23_clnt.c to build ClientHello messages
* includes the 5-byte record header in the buffer, while
* the code in s3_clnt.c does not.
*/
if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
hlen -= 5;
if (hlen > 0xff && hlen < 0x200)
{
hlen = 0x200 - hlen;
if (hlen >= 4)
hlen -= 4;
else
hlen = 0;
s2n(TLSEXT_TYPE_padding, ret);
s2n(hlen, ret);
memset(ret, 0, hlen);
ret += hlen;
}
}
if ((extdatalen = ret-orig-2)== 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
Commit Message:
CWE ID: CWE-20 | unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, unsigned char *limit)
{
int extdatalen=0;
unsigned char *orig = buf;
unsigned char *ret = buf;
/* don't add extensions for SSLv3 unless doing secure renegotiation */
if (s->client_version == SSL3_VERSION
&& !s->s3->send_connection_binding)
return orig;
ret+=2;
if (ret>=limit) return NULL; /* this really never occurs, but ... */
if (s->tlsext_hostname != NULL)
{
/* Add TLS extension servername to the Client Hello message */
unsigned long size_str;
long lenmax;
/* check for enough space.
4 for the servername type and entension length
2 for servernamelist length
1 for the hostname type
2 for hostname length
+ hostname length
*/
if ((lenmax = limit - ret - 9) < 0
|| (size_str = strlen(s->tlsext_hostname)) > (unsigned long)lenmax)
return NULL;
/* extension type and length */
s2n(TLSEXT_TYPE_server_name,ret);
s2n(size_str+5,ret);
/* length of servername list */
s2n(size_str+3,ret);
/* hostname type, length and hostname */
*(ret++) = (unsigned char) TLSEXT_NAMETYPE_host_name;
s2n(size_str,ret);
memcpy(ret, s->tlsext_hostname, size_str);
ret+=size_str;
}
/* Add RI if renegotiating */
if (s->renegotiate)
{
int el;
if(!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_renegotiate,ret);
s2n(el,ret);
if(!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#ifndef OPENSSL_NO_SRP
/* Add SRP username if there is one */
if (s->srp_ctx.login != NULL)
{ /* Add TLS extension SRP username to the Client Hello message */
int login_len = strlen(s->srp_ctx.login);
if (login_len > 255 || login_len == 0)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
/* check for enough space.
4 for the srp type type and entension length
1 for the srp user identity
+ srp user identity length
*/
if ((limit - ret - 5 - login_len) < 0) return NULL;
/* fill in the extension */
s2n(TLSEXT_TYPE_srp,ret);
s2n(login_len+1,ret);
(*ret++) = (unsigned char) login_len;
memcpy(ret, s->srp_ctx.login, login_len);
ret+=login_len;
}
#endif
#ifndef OPENSSL_NO_EC
if (s->tlsext_ecpointformatlist != NULL)
{
/* Add TLS extension ECPointFormats to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 5) < 0) return NULL;
if (s->tlsext_ecpointformatlist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ecpointformatlist_length > 255)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_ec_point_formats,ret);
s2n(s->tlsext_ecpointformatlist_length + 1,ret);
*(ret++) = (unsigned char) s->tlsext_ecpointformatlist_length;
memcpy(ret, s->tlsext_ecpointformatlist, s->tlsext_ecpointformatlist_length);
ret+=s->tlsext_ecpointformatlist_length;
}
if (s->tlsext_ellipticcurvelist != NULL)
{
/* Add TLS extension EllipticCurves to the ClientHello message */
long lenmax;
if ((lenmax = limit - ret - 6) < 0) return NULL;
if (s->tlsext_ellipticcurvelist_length > (unsigned long)lenmax) return NULL;
if (s->tlsext_ellipticcurvelist_length > 65532)
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
s2n(TLSEXT_TYPE_elliptic_curves,ret);
s2n(s->tlsext_ellipticcurvelist_length + 2, ret);
/* NB: draft-ietf-tls-ecc-12.txt uses a one-byte prefix for
* elliptic_curve_list, but the examples use two bytes.
* http://www1.ietf.org/mail-archive/web/tls/current/msg00538.html
* resolves this to two bytes.
*/
s2n(s->tlsext_ellipticcurvelist_length, ret);
memcpy(ret, s->tlsext_ellipticcurvelist, s->tlsext_ellipticcurvelist_length);
ret+=s->tlsext_ellipticcurvelist_length;
}
#endif /* OPENSSL_NO_EC */
if (!(SSL_get_options(s) & SSL_OP_NO_TICKET))
{
int ticklen;
if (!s->new_session && s->session && s->session->tlsext_tick)
ticklen = s->session->tlsext_ticklen;
else if (s->session && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data)
{
ticklen = s->tlsext_session_ticket->length;
s->session->tlsext_tick = OPENSSL_malloc(ticklen);
if (!s->session->tlsext_tick)
return NULL;
memcpy(s->session->tlsext_tick,
s->tlsext_session_ticket->data,
ticklen);
s->session->tlsext_ticklen = ticklen;
}
else
ticklen = 0;
if (ticklen == 0 && s->tlsext_session_ticket &&
s->tlsext_session_ticket->data == NULL)
goto skip_ext;
/* Check for enough room 2 for extension type, 2 for len
* rest for ticket
*/
if ((long)(limit - ret - 4 - ticklen) < 0) return NULL;
s2n(TLSEXT_TYPE_session_ticket,ret);
s2n(ticklen,ret);
if (ticklen)
{
memcpy(ret, s->session->tlsext_tick, ticklen);
ret += ticklen;
}
}
skip_ext:
if (TLS1_get_client_version(s) >= TLS1_2_VERSION)
{
if ((size_t)(limit - ret) < sizeof(tls12_sigalgs) + 6)
return NULL;
s2n(TLSEXT_TYPE_signature_algorithms,ret);
s2n(sizeof(tls12_sigalgs) + 2, ret);
s2n(sizeof(tls12_sigalgs), ret);
memcpy(ret, tls12_sigalgs, sizeof(tls12_sigalgs));
ret += sizeof(tls12_sigalgs);
}
#ifdef TLSEXT_TYPE_opaque_prf_input
if (s->s3->client_opaque_prf_input != NULL &&
s->version != DTLS1_VERSION)
{
size_t col = s->s3->client_opaque_prf_input_len;
if ((long)(limit - ret - 6 - col < 0))
return NULL;
if (col > 0xFFFD) /* can't happen */
return NULL;
s2n(TLSEXT_TYPE_opaque_prf_input, ret);
s2n(col + 2, ret);
s2n(col, ret);
memcpy(ret, s->s3->client_opaque_prf_input, col);
ret += col;
}
#endif
if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp &&
s->version != DTLS1_VERSION)
{
int i;
long extlen, idlen, itmp;
OCSP_RESPID *id;
idlen = 0;
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
itmp = i2d_OCSP_RESPID(id, NULL);
if (itmp <= 0)
return NULL;
idlen += itmp + 2;
}
if (s->tlsext_ocsp_exts)
{
extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL);
if (extlen < 0)
return NULL;
}
else
extlen = 0;
if ((long)(limit - ret - 7 - extlen - idlen) < 0) return NULL;
s2n(TLSEXT_TYPE_status_request, ret);
if (extlen + idlen > 0xFFF0)
return NULL;
s2n(extlen + idlen + 5, ret);
*(ret++) = TLSEXT_STATUSTYPE_ocsp;
s2n(idlen, ret);
for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++)
{
/* save position of id len */
unsigned char *q = ret;
id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i);
/* skip over id len */
ret += 2;
itmp = i2d_OCSP_RESPID(id, &ret);
/* write id len */
s2n(itmp, q);
}
s2n(extlen, ret);
if (extlen > 0)
i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* Add Heartbeat extension */
if ((limit - ret - 4 - 1) < 0)
return NULL;
s2n(TLSEXT_TYPE_heartbeat,ret);
s2n(1,ret);
/* Set mode:
* 1: peer may send requests
* 2: peer not allowed to send requests
*/
if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS)
*(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS;
else
*(ret++) = SSL_TLSEXT_HB_ENABLED;
#endif
#ifndef OPENSSL_NO_NEXTPROTONEG
if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len)
{
/* The client advertises an emtpy extension to indicate its
* support for Next Protocol Negotiation */
if (limit - ret - 4 < 0)
return NULL;
s2n(TLSEXT_TYPE_next_proto_neg,ret);
s2n(0,ret);
}
#endif
#ifndef OPENSSL_NO_SRTP
if(SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s))
{
int el;
ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0);
if((limit - ret - 4 - el) < 0) return NULL;
s2n(TLSEXT_TYPE_use_srtp,ret);
s2n(el,ret);
if(ssl_add_clienthello_use_srtp_ext(s, ret, &el, el))
{
SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR);
return NULL;
}
ret += el;
}
#endif
/* Add padding to workaround bugs in F5 terminators.
* See https://tools.ietf.org/html/draft-agl-tls-padding-03
*
* NB: because this code works out the length of all existing
* extensions it MUST always appear last.
*/
if (s->options & SSL_OP_TLSEXT_PADDING)
{
int hlen = ret - (unsigned char *)s->init_buf->data;
/* The code in s23_clnt.c to build ClientHello messages
* includes the 5-byte record header in the buffer, while
* the code in s3_clnt.c does not.
*/
if (s->state == SSL23_ST_CW_CLNT_HELLO_A)
hlen -= 5;
if (hlen > 0xff && hlen < 0x200)
{
hlen = 0x200 - hlen;
if (hlen >= 4)
hlen -= 4;
else
hlen = 0;
s2n(TLSEXT_TYPE_padding, ret);
s2n(hlen, ret);
memset(ret, 0, hlen);
ret += hlen;
}
}
if ((extdatalen = ret-orig-2)== 0)
return orig;
s2n(extdatalen, orig);
return ret;
}
| 165,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xfs_attr_calc_size(
struct xfs_inode *ip,
int namelen,
int valuelen,
int *local)
{
struct xfs_mount *mp = ip->i_mount;
int size;
int nblks;
/*
* Determine space new attribute will use, and if it would be
* "local" or "remote" (note: local != inline).
*/
size = xfs_attr_leaf_newentsize(namelen, valuelen,
mp->m_sb.sb_blocksize, local);
nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);
if (*local) {
if (size > (mp->m_sb.sb_blocksize >> 1)) {
/* Double split possible */
nblks *= 2;
}
} else {
/*
* Out of line attribute, cannot double split, but
* make room for the attribute value itself.
*/
uint dblocks = XFS_B_TO_FSB(mp, valuelen);
nblks += dblocks;
nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK);
}
return nblks;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr_calc_size(
struct xfs_inode *ip,
int namelen,
int valuelen,
int *local)
{
struct xfs_mount *mp = ip->i_mount;
int size;
int nblks;
/*
* Determine space new attribute will use, and if it would be
* "local" or "remote" (note: local != inline).
*/
size = xfs_attr_leaf_newentsize(namelen, valuelen,
mp->m_sb.sb_blocksize, local);
nblks = XFS_DAENTER_SPACE_RES(mp, XFS_ATTR_FORK);
if (*local) {
if (size > (mp->m_sb.sb_blocksize >> 1)) {
/* Double split possible */
nblks *= 2;
}
} else {
/*
* Out of line attribute, cannot double split, but
* make room for the attribute value itself.
*/
uint dblocks = xfs_attr3_rmt_blocks(mp, valuelen);
nblks += dblocks;
nblks += XFS_NEXTENTADD_SPACE_RES(mp, dblocks, XFS_ATTR_FORK);
}
return nblks;
}
| 166,730 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (!n2size) {
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
Commit Message: Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated)
Thanks to Mick Ayzenberg <[email protected]> for finding this!
CWE ID: CWE-119 | bool initiate_stratum(struct pool *pool)
{
bool ret = false, recvd = false, noresume = false, sockd = false;
char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
json_t *val = NULL, *res_val, *err_val;
json_error_t err;
int n2size;
resend:
if (!setup_stratum_socket(pool)) {
/* FIXME: change to LOG_DEBUG when issue #88 resolved */
applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool));
sockd = false;
goto out;
}
sockd = true;
if (recvd) {
/* Get rid of any crap lying around if we're resending */
clear_sock(pool);
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
} else {
if (pool->sessionid)
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
else
sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
}
if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
goto out;
}
if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
goto out;
}
sret = recv_line(pool);
if (!sret)
goto out;
recvd = true;
val = JSON_LOADS(sret, &err);
free(sret);
if (!val) {
applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
goto out;
}
res_val = json_object_get(val, "result");
err_val = json_object_get(val, "error");
if (!res_val || json_is_null(res_val) ||
(err_val && !json_is_null(err_val))) {
char *ss;
if (err_val)
ss = json_dumps(err_val, JSON_INDENT(3));
else
ss = strdup("(unknown reason)");
applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
free(ss);
goto out;
}
sessionid = get_sessionid(res_val);
if (!sessionid)
applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
nonce1 = json_array_string(res_val, 1);
if (!nonce1) {
applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
free(sessionid);
goto out;
}
n2size = json_integer_value(json_array_get(res_val, 2));
if (n2size < 1)
{
applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
free(sessionid);
free(nonce1);
goto out;
}
cg_wlock(&pool->data_lock);
pool->sessionid = sessionid;
pool->nonce1 = nonce1;
pool->n1_len = strlen(nonce1) / 2;
free(pool->nonce1bin);
pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1);
if (unlikely(!pool->nonce1bin))
quithere(1, "Failed to calloc pool->nonce1bin");
hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
pool->n2size = n2size;
cg_wunlock(&pool->data_lock);
if (sessionid)
applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid);
ret = true;
out:
if (ret) {
if (!pool->stratum_url)
pool->stratum_url = pool->sockaddr_url;
pool->stratum_active = true;
pool->swork.diff = 1;
if (opt_protocol) {
applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d",
get_pool_name(pool), pool->nonce1, pool->n2size);
}
} else {
if (recvd && !noresume) {
/* Reset the sessionid used for stratum resuming in case the pool
* does not support it, or does not know how to respond to the
* presence of the sessionid parameter. */
cg_wlock(&pool->data_lock);
free(pool->sessionid);
free(pool->nonce1);
pool->sessionid = pool->nonce1 = NULL;
cg_wunlock(&pool->data_lock);
applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
noresume = true;
json_decref(val);
goto resend;
}
applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool));
if (sockd) {
applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool));
suspend_stratum(pool);
}
}
json_decref(val);
return ret;
}
| 169,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range *range;
struct evbuffer *evb = NULL;
size_t content_length;
int code = 500, fd = -1, i, nranges, ret;
uint32_t boundary;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((range = parse_range(range_str, st->st_size, &nranges)) == NULL) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
if ((evb = evbuffer_new()) == NULL) {
errstr = "failed to allocate file buffer";
goto abort;
}
if (nranges == 1) {
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
content_length = range->end - range->start + 1;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
} else {
content_length = 0;
boundary = arc4random();
/* Generate a multipart payload of byteranges */
while (nranges--) {
if ((i = evbuffer_add_printf(evb, "\r\n--%ud\r\n",
boundary)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Type: %s/%s\r\n",
media->media_type, media->media_subtype)) == -1)
goto abort;
content_length += i;
if ((i = evbuffer_add_printf(evb,
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
range->start, range->end, st->st_size)) == -1)
goto abort;
content_length += i;
if (buffer_add_range(fd, evb, range) == 0)
goto abort;
content_length += range->end - range->start + 1;
range++;
}
if ((i = evbuffer_add_printf(evb, "\r\n--%ud--\r\n",
boundary)) == -1)
goto abort;
content_length += i;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%ud", boundary);
media = &multipart_media;
}
close(fd);
fd = -1;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
goto done;
default:
break;
}
if (server_bufferevent_write_buffer(clt, evb) == -1)
goto fail;
bufferevent_enable(clt->clt_bev, EV_READ|EV_WRITE);
if (clt->clt_persist)
clt->clt_toread = TOREAD_HTTP_HEADER;
else
clt->clt_toread = TOREAD_HTTP_NONE;
clt->clt_done = 0;
done:
evbuffer_free(evb);
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (evb != NULL)
evbuffer_free(evb);
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
Commit Message: Reimplement httpd's support for byte ranges.
The previous implementation loaded all the output into a single output
buffer and used its size to determine the Content-Length of the body.
The new implementation calculates the body length first and writes the
individual ranges in an async way using the bufferevent mechanism.
This prevents httpd from using too much memory and applies the
watermark and throttling mechanisms to range requests.
Problem reported by Pierre Kim (pierre.kim.sec at gmail.com)
OK benno@ sunil@
CWE ID: CWE-770 | server_partial_file_request(struct httpd *env, struct client *clt, char *path,
struct stat *st, char *range_str)
{
struct server_config *srv_conf = clt->clt_srv_conf;
struct http_descriptor *resp = clt->clt_descresp;
struct http_descriptor *desc = clt->clt_descreq;
struct media_type *media, multipart_media;
struct range_data *r = &clt->clt_ranges;
struct range *range;
size_t content_length = 0;
int code = 500, fd = -1, i, nranges, ret;
char content_range[64];
const char *errstr = NULL;
/* Ignore range request for methods other than GET */
if (desc->http_method != HTTP_METHOD_GET)
return server_file_request(env, clt, path, st);
if ((nranges = parse_ranges(clt, range_str, st->st_size)) < 1) {
code = 416;
(void)snprintf(content_range, sizeof(content_range),
"bytes */%lld", st->st_size);
errstr = content_range;
goto abort;
}
/* Now open the file, should be readable or we have another problem */
if ((fd = open(path, O_RDONLY)) == -1)
goto abort;
media = media_find_config(env, srv_conf, path);
r->range_media = media;
if (nranges == 1) {
range = &r->range[0];
(void)snprintf(content_range, sizeof(content_range),
"bytes %lld-%lld/%lld", range->start, range->end,
st->st_size);
if (kv_add(&resp->http_headers, "Content-Range",
content_range) == NULL)
goto abort;
range = &r->range[0];
content_length += range->end - range->start + 1;
} else {
/* Add boundary, all parts will be handled by the callback */
arc4random_buf(&clt->clt_boundary, sizeof(clt->clt_boundary));
/* Calculate Content-Length of the complete multipart body */
for (i = 0; i < nranges; i++) {
range = &r->range[i];
/* calculate Content-Length of the complete body */
if ((ret = snprintf(NULL, 0,
"\r\n--%llu\r\n"
"Content-Type: %s/%s\r\n"
"Content-Range: bytes %lld-%lld/%lld\r\n\r\n",
clt->clt_boundary,
media->media_type, media->media_subtype,
range->start, range->end, st->st_size)) < 0)
goto abort;
/* Add data length */
content_length += ret + range->end - range->start + 1;
}
if ((ret = snprintf(NULL, 0, "\r\n--%llu--\r\n",
clt->clt_boundary)) < 0)
goto abort;
content_length += ret;
/* prepare multipart/byteranges media type */
(void)strlcpy(multipart_media.media_type, "multipart",
sizeof(multipart_media.media_type));
(void)snprintf(multipart_media.media_subtype,
sizeof(multipart_media.media_subtype),
"byteranges; boundary=%llu", clt->clt_boundary);
media = &multipart_media;
}
/* Start with first range */
r->range_toread = TOREAD_HTTP_RANGE;
ret = server_response_http(clt, 206, media, content_length,
MINIMUM(time(NULL), st->st_mtim.tv_sec));
switch (ret) {
case -1:
goto fail;
case 0:
/* Connection is already finished */
close(fd);
goto done;
default:
break;
}
clt->clt_fd = fd;
if (clt->clt_srvbev != NULL)
bufferevent_free(clt->clt_srvbev);
clt->clt_srvbev_throttled = 0;
clt->clt_srvbev = bufferevent_new(clt->clt_fd, server_read_httprange,
server_write, server_file_error, clt);
if (clt->clt_srvbev == NULL) {
errstr = "failed to allocate file buffer event";
goto fail;
}
/* Adjust read watermark to the socket output buffer size */
bufferevent_setwatermark(clt->clt_srvbev, EV_READ, 0,
clt->clt_sndbufsiz);
bufferevent_settimeout(clt->clt_srvbev,
srv_conf->timeout.tv_sec, srv_conf->timeout.tv_sec);
bufferevent_enable(clt->clt_srvbev, EV_READ);
bufferevent_disable(clt->clt_bev, EV_READ);
done:
server_reset_http(clt);
return (0);
fail:
bufferevent_disable(clt->clt_bev, EV_READ|EV_WRITE);
bufferevent_free(clt->clt_bev);
clt->clt_bev = NULL;
abort:
if (fd != -1)
close(fd);
if (errstr == NULL)
errstr = strerror(errno);
server_abort_http(clt, code, errstr);
return (-1);
}
| 168,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<size_t> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | bool dstBufferSizeHasOverflow(ParsedOptions options) {
CheckedNumeric<unsigned> totalBytes = options.cropRect.width();
totalBytes *= options.cropRect.height();
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
if (!options.shouldScaleInput)
return false;
totalBytes = options.resizeWidth;
totalBytes *= options.resizeHeight;
totalBytes *= options.bytesPerPixel;
if (!totalBytes.IsValid())
return true;
return false;
}
| 172,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
Commit Message: Merge some file writing extension checks from OpenJK.
Thanks Ensiform.
https://github.com/JACoders/OpenJK/commit/05928a57f9e4aae15a3bd0
https://github.com/JACoders/OpenJK/commit/ef124fd0fc48af164581176
CWE ID: CWE-269 | void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv(1), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
| 170,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
size_t dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, iter, iteriter, regexiter;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg, dir, dir_len);
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
zval_ptr_dtor(&arg);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, &iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
if (SUCCESS != object_init_ex(®exiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(®exiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg2, regex, regex_len);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
zval_ptr_dtor(&arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
return;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? ®exiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->archive->ufp = pass.fp;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, buildFromDirectory)
{
char *dir, *error, *regex = NULL;
size_t dir_len, regex_len = 0;
zend_bool apply_reg = 0;
zval arg, arg2, iter, iteriter, regexiter;
struct _phar_t pass;
PHAR_ARCHIVE_OBJECT();
if (PHAR_G(readonly) && !phar_obj->archive->is_data) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0,
"Cannot write to archive - write operations restricted by INI setting");
return;
}
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s", &dir, &dir_len, ®ex, ®ex_len) == FAILURE) {
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iter, spl_ce_RecursiveDirectoryIterator)) {
zval_ptr_dtor(&iter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg, dir, dir_len);
ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS);
zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator,
&spl_ce_RecursiveDirectoryIterator->constructor, "__construct", NULL, &arg, &arg2);
zval_ptr_dtor(&arg);
if (EG(exception)) {
zval_ptr_dtor(&iter);
RETURN_FALSE;
}
if (SUCCESS != object_init_ex(&iteriter, spl_ce_RecursiveIteratorIterator)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate directory iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator,
&spl_ce_RecursiveIteratorIterator->constructor, "__construct", NULL, &iter);
if (EG(exception)) {
zval_ptr_dtor(&iter);
zval_ptr_dtor(&iteriter);
RETURN_FALSE;
}
zval_ptr_dtor(&iter);
if (regex_len > 0) {
apply_reg = 1;
if (SUCCESS != object_init_ex(®exiter, spl_ce_RegexIterator)) {
zval_ptr_dtor(&iteriter);
zval_dtor(®exiter);
zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Unable to instantiate regex iterator for %s", phar_obj->archive->fname);
RETURN_FALSE;
}
ZVAL_STRINGL(&arg2, regex, regex_len);
zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator,
&spl_ce_RegexIterator->constructor, "__construct", NULL, &iteriter, &arg2);
zval_ptr_dtor(&arg2);
}
array_init(return_value);
pass.c = apply_reg ? Z_OBJCE(regexiter) : Z_OBJCE(iteriter);
pass.p = phar_obj;
pass.b = dir;
pass.l = dir_len;
pass.count = 0;
pass.ret = return_value;
pass.fp = php_stream_fopen_tmpfile();
if (pass.fp == NULL) {
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" unable to create temporary file", phar_obj->archive->fname);
return;
}
if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname);
return;
}
if (SUCCESS == spl_iterator_apply((apply_reg ? ®exiter : &iteriter), (spl_iterator_apply_func_t) phar_build, (void *) &pass)) {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
phar_obj->archive->ufp = pass.fp;
phar_flush(phar_obj->archive, 0, 0, 0, &error);
if (error) {
zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error);
efree(error);
}
} else {
zval_ptr_dtor(&iteriter);
if (apply_reg) {
zval_ptr_dtor(®exiter);
}
php_stream_close(pass.fp);
}
}
| 165,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
unsigned long flags;
int ret;
spin_lock_irqsave(&dev->lock, flags);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
spin_unlock_irqrestore(&dev->lock, flags);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
spin_unlock_irqrestore(&dev->lock, flags);
return ret < 0 ? ret : -EIO;
}
Commit Message: HID: cp2112: fix sleep-while-atomic
A recent commit fixing DMA-buffers on stack added a shared transfer
buffer protected by a spinlock. This is broken as the USB HID request
callbacks can sleep. Fix this up by replacing the spinlock with a mutex.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-404 | static int cp2112_gpio_direction_output(struct gpio_chip *chip,
unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_GET_REPORT);
if (ret != CP2112_GPIO_CONFIG_LENGTH) {
hid_err(hdev, "error requesting GPIO config: %d\n", ret);
goto fail;
}
buf[1] |= 1 << offset;
buf[2] = gpio_push_pull;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0) {
hid_err(hdev, "error setting GPIO config: %d\n", ret);
goto fail;
}
mutex_unlock(&dev->lock);
/*
* Set gpio value when output direction is already set,
* as specified in AN495, Rev. 0.2, cpt. 4.4
*/
cp2112_gpio_set(chip, offset, value);
return 0;
fail:
mutex_unlock(&dev->lock);
return ret < 0 ? ret : -EIO;
}
| 168,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ImageBitmap::ImageBitmap(ImageData* data,
Optional<IntRect> cropRect,
const ImageBitmapOptions& options) {
IntRect dataSrcRect = IntRect(IntPoint(), data->size());
ParsedOptions parsedOptions =
parseOptions(options, cropRect, data->bitmapSourceSize());
if (dstBufferSizeHasOverflow(parsedOptions))
return;
IntRect srcRect = cropRect ? intersection(parsedOptions.cropRect, dataSrcRect)
: dataSrcRect;
if (!parsedOptions.premultiplyAlpha) {
unsigned char* srcAddr = data->data()->data();
SkImageInfo info = SkImageInfo::Make(
parsedOptions.cropRect.width(), parsedOptions.cropRect.height(),
kN32_SkColorType, kUnpremul_SkAlphaType);
size_t bytesPerPixel = static_cast<size_t>(info.bytesPerPixel());
size_t srcPixelBytesPerRow = bytesPerPixel * data->size().width();
size_t dstPixelBytesPerRow = bytesPerPixel * parsedOptions.cropRect.width();
sk_sp<SkImage> skImage;
if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) {
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
skImage =
SkImage::MakeRasterCopy(SkPixmap(info, srcAddr, dstPixelBytesPerRow));
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
} else {
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
static_cast<size_t>(parsedOptions.cropRect.height()) *
parsedOptions.cropRect.width(),
bytesPerPixel);
if (!dstBuffer)
return;
RefPtr<Uint8Array> copiedDataBuffer =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
if (!srcRect.isEmpty()) {
IntPoint srcPoint = IntPoint(
(parsedOptions.cropRect.x() > 0) ? parsedOptions.cropRect.x() : 0,
(parsedOptions.cropRect.y() > 0) ? parsedOptions.cropRect.y() : 0);
IntPoint dstPoint = IntPoint(
(parsedOptions.cropRect.x() >= 0) ? 0 : -parsedOptions.cropRect.x(),
(parsedOptions.cropRect.y() >= 0) ? 0
: -parsedOptions.cropRect.y());
int copyHeight = data->size().height() - srcPoint.y();
if (parsedOptions.cropRect.height() < copyHeight)
copyHeight = parsedOptions.cropRect.height();
int copyWidth = data->size().width() - srcPoint.x();
if (parsedOptions.cropRect.width() < copyWidth)
copyWidth = parsedOptions.cropRect.width();
for (int i = 0; i < copyHeight; i++) {
size_t srcStartCopyPosition =
(i + srcPoint.y()) * srcPixelBytesPerRow +
srcPoint.x() * bytesPerPixel;
size_t srcEndCopyPosition =
srcStartCopyPosition + copyWidth * bytesPerPixel;
size_t dstStartCopyPosition;
if (parsedOptions.flipY)
dstStartCopyPosition =
(parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) *
dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
else
dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
for (size_t j = 0; j < srcEndCopyPosition - srcStartCopyPosition;
j++) {
if (kN32_SkColorType == kBGRA_8888_SkColorType) {
if (j % 4 == 0)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j + 2];
else if (j % 4 == 2)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j - 2];
else
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
} else {
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
}
}
}
}
skImage = newSkImageFromRaster(info, std::move(copiedDataBuffer),
dstPixelBytesPerRow);
}
if (!skImage)
return;
if (parsedOptions.shouldScaleInput)
m_image = StaticBitmapImage::create(scaleSkImage(
skImage, parsedOptions.resizeWidth, parsedOptions.resizeHeight,
parsedOptions.resizeQuality));
else
m_image = StaticBitmapImage::create(skImage);
if (!m_image)
return;
m_image->setPremultiplied(parsedOptions.premultiplyAlpha);
return;
}
std::unique_ptr<ImageBuffer> buffer = ImageBuffer::create(
parsedOptions.cropRect.size(), NonOpaque, DoNotInitializeImagePixels);
if (!buffer)
return;
if (srcRect.isEmpty()) {
m_image = StaticBitmapImage::create(buffer->newSkImageSnapshot(
PreferNoAcceleration, SnapshotReasonUnknown));
return;
}
IntPoint dstPoint = IntPoint(std::min(0, -parsedOptions.cropRect.x()),
std::min(0, -parsedOptions.cropRect.y()));
if (parsedOptions.cropRect.x() < 0)
dstPoint.setX(-parsedOptions.cropRect.x());
if (parsedOptions.cropRect.y() < 0)
dstPoint.setY(-parsedOptions.cropRect.y());
buffer->putByteArray(Unmultiplied, data->data()->data(), data->size(),
srcRect, dstPoint);
sk_sp<SkImage> skImage =
buffer->newSkImageSnapshot(PreferNoAcceleration, SnapshotReasonUnknown);
if (parsedOptions.flipY)
skImage = flipSkImageVertically(skImage.get(), PremultiplyAlpha);
if (!skImage)
return;
if (parsedOptions.shouldScaleInput) {
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(
parsedOptions.resizeWidth, parsedOptions.resizeHeight);
if (!surface)
return;
SkPaint paint;
paint.setFilterQuality(parsedOptions.resizeQuality);
SkRect dstDrawRect =
SkRect::MakeWH(parsedOptions.resizeWidth, parsedOptions.resizeHeight);
surface->getCanvas()->drawImageRect(skImage, dstDrawRect, &paint);
skImage = surface->makeImageSnapshot();
}
m_image = StaticBitmapImage::create(std::move(skImage));
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | ImageBitmap::ImageBitmap(ImageData* data,
Optional<IntRect> cropRect,
const ImageBitmapOptions& options) {
IntRect dataSrcRect = IntRect(IntPoint(), data->size());
ParsedOptions parsedOptions =
parseOptions(options, cropRect, data->bitmapSourceSize());
if (dstBufferSizeHasOverflow(parsedOptions))
return;
IntRect srcRect = cropRect ? intersection(parsedOptions.cropRect, dataSrcRect)
: dataSrcRect;
if (!parsedOptions.premultiplyAlpha) {
unsigned char* srcAddr = data->data()->data();
SkImageInfo info = SkImageInfo::Make(
parsedOptions.cropRect.width(), parsedOptions.cropRect.height(),
kN32_SkColorType, kUnpremul_SkAlphaType);
unsigned bytesPerPixel = static_cast<unsigned>(info.bytesPerPixel());
unsigned srcPixelBytesPerRow = bytesPerPixel * data->size().width();
unsigned dstPixelBytesPerRow =
bytesPerPixel * parsedOptions.cropRect.width();
sk_sp<SkImage> skImage;
if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) {
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
skImage =
SkImage::MakeRasterCopy(SkPixmap(info, srcAddr, dstPixelBytesPerRow));
swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow,
parsedOptions.flipY);
} else {
RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(
static_cast<unsigned>(parsedOptions.cropRect.height()) *
parsedOptions.cropRect.width(),
bytesPerPixel);
if (!dstBuffer)
return;
RefPtr<Uint8Array> copiedDataBuffer =
Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength());
if (!srcRect.isEmpty()) {
IntPoint srcPoint = IntPoint(
(parsedOptions.cropRect.x() > 0) ? parsedOptions.cropRect.x() : 0,
(parsedOptions.cropRect.y() > 0) ? parsedOptions.cropRect.y() : 0);
IntPoint dstPoint = IntPoint(
(parsedOptions.cropRect.x() >= 0) ? 0 : -parsedOptions.cropRect.x(),
(parsedOptions.cropRect.y() >= 0) ? 0
: -parsedOptions.cropRect.y());
int copyHeight = data->size().height() - srcPoint.y();
if (parsedOptions.cropRect.height() < copyHeight)
copyHeight = parsedOptions.cropRect.height();
int copyWidth = data->size().width() - srcPoint.x();
if (parsedOptions.cropRect.width() < copyWidth)
copyWidth = parsedOptions.cropRect.width();
for (int i = 0; i < copyHeight; i++) {
unsigned srcStartCopyPosition =
(i + srcPoint.y()) * srcPixelBytesPerRow +
srcPoint.x() * bytesPerPixel;
unsigned srcEndCopyPosition =
srcStartCopyPosition + copyWidth * bytesPerPixel;
unsigned dstStartCopyPosition;
if (parsedOptions.flipY)
dstStartCopyPosition =
(parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) *
dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
else
dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow +
dstPoint.x() * bytesPerPixel;
for (unsigned j = 0; j < srcEndCopyPosition - srcStartCopyPosition;
j++) {
if (kN32_SkColorType == kBGRA_8888_SkColorType) {
if (j % 4 == 0)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j + 2];
else if (j % 4 == 2)
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j - 2];
else
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
} else {
copiedDataBuffer->data()[dstStartCopyPosition + j] =
srcAddr[srcStartCopyPosition + j];
}
}
}
}
skImage = newSkImageFromRaster(info, std::move(copiedDataBuffer),
dstPixelBytesPerRow);
}
if (!skImage)
return;
if (parsedOptions.shouldScaleInput)
m_image = StaticBitmapImage::create(scaleSkImage(
skImage, parsedOptions.resizeWidth, parsedOptions.resizeHeight,
parsedOptions.resizeQuality));
else
m_image = StaticBitmapImage::create(skImage);
if (!m_image)
return;
m_image->setPremultiplied(parsedOptions.premultiplyAlpha);
return;
}
std::unique_ptr<ImageBuffer> buffer = ImageBuffer::create(
parsedOptions.cropRect.size(), NonOpaque, DoNotInitializeImagePixels);
if (!buffer)
return;
if (srcRect.isEmpty()) {
m_image = StaticBitmapImage::create(buffer->newSkImageSnapshot(
PreferNoAcceleration, SnapshotReasonUnknown));
return;
}
IntPoint dstPoint = IntPoint(std::min(0, -parsedOptions.cropRect.x()),
std::min(0, -parsedOptions.cropRect.y()));
if (parsedOptions.cropRect.x() < 0)
dstPoint.setX(-parsedOptions.cropRect.x());
if (parsedOptions.cropRect.y() < 0)
dstPoint.setY(-parsedOptions.cropRect.y());
buffer->putByteArray(Unmultiplied, data->data()->data(), data->size(),
srcRect, dstPoint);
sk_sp<SkImage> skImage =
buffer->newSkImageSnapshot(PreferNoAcceleration, SnapshotReasonUnknown);
if (parsedOptions.flipY)
skImage = flipSkImageVertically(skImage.get(), PremultiplyAlpha);
if (!skImage)
return;
if (parsedOptions.shouldScaleInput) {
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(
parsedOptions.resizeWidth, parsedOptions.resizeHeight);
if (!surface)
return;
SkPaint paint;
paint.setFilterQuality(parsedOptions.resizeQuality);
SkRect dstDrawRect =
SkRect::MakeWH(parsedOptions.resizeWidth, parsedOptions.resizeHeight);
surface->getCanvas()->drawImageRect(skImage, dstDrawRect, &paint);
skImage = surface->makeImageSnapshot();
}
m_image = StaticBitmapImage::create(std::move(skImage));
}
| 172,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WriteFakeData(uint8* audio_data, size_t length) {
Type* output = reinterpret_cast<Type*>(audio_data);
for (size_t i = 0; i < length; i++) {
output[i] = i % 5 + 10;
}
}
Commit Message: Protect AudioRendererAlgorithm from invalid step sizes.
BUG=165430
TEST=unittests and asan pass.
Review URL: https://codereview.chromium.org/11573023
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void WriteFakeData(uint8* audio_data, size_t length) {
| 171,537 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
{
jpc_siz_t *siz;
jpc_cod_t *cod;
jpc_qcd_t *qcd;
int i;
long startoff;
long mainhdrlen;
jpc_enc_cp_t *cp;
jpc_qcc_t *qcc;
jpc_enc_tccp_t *tccp;
uint_fast16_t cmptno;
jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
jpc_fix_t mctsynweight;
jpc_enc_tcp_t *tcp;
jpc_tsfb_t *tsfb;
jpc_tsfb_band_t *bandinfo;
uint_fast16_t numbands;
uint_fast16_t bandno;
uint_fast16_t rlvlno;
uint_fast16_t analgain;
jpc_fix_t absstepsize;
char buf[1024];
jpc_com_t *com;
cp = enc->cp;
startoff = jas_stream_getrwcount(enc->out);
/* Write SOC marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
return -1;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOC marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
/* Write SIZ marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
return -1;
}
siz = &enc->mrk->parms.siz;
siz->caps = 0;
siz->xoff = cp->imgareatlx;
siz->yoff = cp->imgareatly;
siz->width = cp->refgrdwidth;
siz->height = cp->refgrdheight;
siz->tilexoff = cp->tilegrdoffx;
siz->tileyoff = cp->tilegrdoffy;
siz->tilewidth = cp->tilewidth;
siz->tileheight = cp->tileheight;
siz->numcomps = cp->numcmpts;
siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
assert(siz->comps);
for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
siz->comps[i].prec = cp->ccps[i].prec;
siz->comps[i].sgnd = cp->ccps[i].sgnd;
siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SIZ marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
return -1;
}
sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
com = &enc->mrk->parms.com;
com->len = JAS_CAST(uint_fast16_t, strlen(buf));
com->regid = JPC_COM_LATIN;
if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) {
abort();
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COM marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#if 0
if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
return -1;
}
crg = &enc->mrk->parms.crg;
crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write CRG marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#endif
tcp = &cp->tcp;
tccp = &cp->tccp;
for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
bandinfos);
jpc_tsfb_destroy(tsfb);
mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
numbands = 3 * tccp->maxrlvls - 2;
for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
++bandno, ++bandinfo) {
rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
rlvlno, bandinfo->orient);
if (!tcp->intmode) {
absstepsize = jpc_fix_div(jpc_inttofix(1 <<
(analgain + 1)), bandinfo->synenergywt);
} else {
absstepsize = jpc_inttofix(1);
}
cp->ccps[cmptno].stepsizes[bandno] =
jpc_abstorelstepsize(absstepsize,
cp->ccps[cmptno].prec + analgain);
}
cp->ccps[cmptno].numstepsizes = numbands;
}
if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
return -1;
}
cod = &enc->mrk->parms.cod;
cod->csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
cod->compparms.numrlvls = cp->tccp.maxrlvls;
cod->prg = cp->tcp.prg;
cod->numlyrs = cp->tcp.numlyrs;
cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
cod->compparms.cblksty = cp->tccp.cblksty;
cod->compparms.qmfbid = cp->tccp.qmfbid;
cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
if (tccp->csty & JPC_COX_PRT) {
for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
}
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COD marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
return -1;
}
qcd = &enc->mrk->parms.qcd;
qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
qcd->compparms.numguard = cp->tccp.numgbits;
qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcd->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
tccp = &cp->tccp;
for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
return -1;
}
qcc = &enc->mrk->parms.qcc;
qcc->compno = cmptno;
qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
qcc->compparms.numguard = cp->tccp.numgbits;
qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcc->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
#define MAINTLRLEN 2
mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
enc->len += mainhdrlen;
if (enc->cp->totalsize != UINT_FAST32_MAX) {
uint_fast32_t overhead;
overhead = mainhdrlen + MAINTLRLEN;
enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
(enc->cp->totalsize - overhead) : 0;
} else {
enc->mainbodysize = UINT_FAST32_MAX;
}
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jpc_enc_encodemainhdr(jpc_enc_t *enc)
{
jpc_siz_t *siz;
jpc_cod_t *cod;
jpc_qcd_t *qcd;
int i;
long startoff;
long mainhdrlen;
jpc_enc_cp_t *cp;
jpc_qcc_t *qcc;
jpc_enc_tccp_t *tccp;
uint_fast16_t cmptno;
jpc_tsfb_band_t bandinfos[JPC_MAXBANDS];
jpc_fix_t mctsynweight;
jpc_enc_tcp_t *tcp;
jpc_tsfb_t *tsfb;
jpc_tsfb_band_t *bandinfo;
uint_fast16_t numbands;
uint_fast16_t bandno;
uint_fast16_t rlvlno;
uint_fast16_t analgain;
jpc_fix_t absstepsize;
char buf[1024];
jpc_com_t *com;
cp = enc->cp;
startoff = jas_stream_getrwcount(enc->out);
/* Write SOC marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SOC))) {
return -1;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SOC marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
/* Write SIZ marker segment. */
if (!(enc->mrk = jpc_ms_create(JPC_MS_SIZ))) {
return -1;
}
siz = &enc->mrk->parms.siz;
siz->caps = 0;
siz->xoff = cp->imgareatlx;
siz->yoff = cp->imgareatly;
siz->width = cp->refgrdwidth;
siz->height = cp->refgrdheight;
siz->tilexoff = cp->tilegrdoffx;
siz->tileyoff = cp->tilegrdoffy;
siz->tilewidth = cp->tilewidth;
siz->tileheight = cp->tileheight;
siz->numcomps = cp->numcmpts;
siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t));
assert(siz->comps);
for (i = 0; i < JAS_CAST(int, cp->numcmpts); ++i) {
siz->comps[i].prec = cp->ccps[i].prec;
siz->comps[i].sgnd = cp->ccps[i].sgnd;
siz->comps[i].hsamp = cp->ccps[i].sampgrdstepx;
siz->comps[i].vsamp = cp->ccps[i].sampgrdstepy;
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write SIZ marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_COM))) {
return -1;
}
sprintf(buf, "Creator: JasPer Version %s", jas_getversion());
com = &enc->mrk->parms.com;
com->len = JAS_CAST(uint_fast16_t, strlen(buf));
com->regid = JPC_COM_LATIN;
if (!(com->data = JAS_CAST(jas_uchar *, jas_strdup(buf)))) {
abort();
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COM marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#if 0
if (!(enc->mrk = jpc_ms_create(JPC_MS_CRG))) {
return -1;
}
crg = &enc->mrk->parms.crg;
crg->comps = jas_alloc2(crg->numcomps, sizeof(jpc_crgcomp_t));
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write CRG marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
#endif
tcp = &cp->tcp;
tccp = &cp->tccp;
for (cmptno = 0; cmptno < cp->numcmpts; ++cmptno) {
tsfb = jpc_cod_gettsfb(tccp->qmfbid, tccp->maxrlvls - 1);
jpc_tsfb_getbands(tsfb, 0, 0, 1 << tccp->maxrlvls, 1 << tccp->maxrlvls,
bandinfos);
jpc_tsfb_destroy(tsfb);
mctsynweight = jpc_mct_getsynweight(tcp->mctid, cmptno);
numbands = 3 * tccp->maxrlvls - 2;
for (bandno = 0, bandinfo = bandinfos; bandno < numbands;
++bandno, ++bandinfo) {
rlvlno = (bandno) ? ((bandno - 1) / 3 + 1) : 0;
analgain = JPC_NOMINALGAIN(tccp->qmfbid, tccp->maxrlvls,
rlvlno, bandinfo->orient);
if (!tcp->intmode) {
absstepsize = jpc_fix_div(jpc_inttofix(1 <<
(analgain + 1)), bandinfo->synenergywt);
} else {
absstepsize = jpc_inttofix(1);
}
cp->ccps[cmptno].stepsizes[bandno] =
jpc_abstorelstepsize(absstepsize,
cp->ccps[cmptno].prec + analgain);
}
cp->ccps[cmptno].numstepsizes = numbands;
}
if (!(enc->mrk = jpc_ms_create(JPC_MS_COD))) {
return -1;
}
cod = &enc->mrk->parms.cod;
cod->csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.csty = cp->tccp.csty | cp->tcp.csty;
cod->compparms.numdlvls = cp->tccp.maxrlvls - 1;
cod->compparms.numrlvls = cp->tccp.maxrlvls;
cod->prg = cp->tcp.prg;
cod->numlyrs = cp->tcp.numlyrs;
cod->compparms.cblkwidthval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkwidthexpn);
cod->compparms.cblkheightval = JPC_COX_CBLKSIZEEXPN(cp->tccp.cblkheightexpn);
cod->compparms.cblksty = cp->tccp.cblksty;
cod->compparms.qmfbid = cp->tccp.qmfbid;
cod->mctrans = (cp->tcp.mctid != JPC_MCT_NONE);
if (tccp->csty & JPC_COX_PRT) {
for (rlvlno = 0; rlvlno < tccp->maxrlvls; ++rlvlno) {
cod->compparms.rlvls[rlvlno].parwidthval = tccp->prcwidthexpns[rlvlno];
cod->compparms.rlvls[rlvlno].parheightval = tccp->prcheightexpns[rlvlno];
}
}
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
jas_eprintf("cannot write COD marker\n");
return -1;
}
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCD))) {
return -1;
}
qcd = &enc->mrk->parms.qcd;
qcd->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcd->compparms.numstepsizes = cp->ccps[0].numstepsizes;
qcd->compparms.numguard = cp->tccp.numgbits;
qcd->compparms.stepsizes = cp->ccps[0].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcd->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
tccp = &cp->tccp;
for (cmptno = 1; cmptno < cp->numcmpts; ++cmptno) {
if (!(enc->mrk = jpc_ms_create(JPC_MS_QCC))) {
return -1;
}
qcc = &enc->mrk->parms.qcc;
qcc->compno = cmptno;
qcc->compparms.qntsty = (tccp->qmfbid == JPC_COX_INS) ?
JPC_QCX_SEQNT : JPC_QCX_NOQNT;
qcc->compparms.numstepsizes = cp->ccps[cmptno].numstepsizes;
qcc->compparms.numguard = cp->tccp.numgbits;
qcc->compparms.stepsizes = cp->ccps[cmptno].stepsizes;
if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {
return -1;
}
/* We do not want the step size array to be freed! */
qcc->compparms.stepsizes = 0;
jpc_ms_destroy(enc->mrk);
enc->mrk = 0;
}
#define MAINTLRLEN 2
mainhdrlen = jas_stream_getrwcount(enc->out) - startoff;
enc->len += mainhdrlen;
if (enc->cp->totalsize != UINT_FAST32_MAX) {
uint_fast32_t overhead;
overhead = mainhdrlen + MAINTLRLEN;
enc->mainbodysize = (enc->cp->totalsize >= overhead) ?
(enc->cp->totalsize - overhead) : 0;
} else {
enc->mainbodysize = UINT_FAST32_MAX;
}
return 0;
}
| 168,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
for (int page_index : visible_pages_) {
if (pages_[page_index]->GetPage() == page)
return page_index;
}
return -1;
}
Commit Message: Copy visible_pages_ when iterating over it.
On this case, a call inside the loop may cause visible_pages_ to
change.
Bug: 822091
Change-Id: I41b0715faa6fe3e39203cd9142cf5ea38e59aefb
Reviewed-on: https://chromium-review.googlesource.com/964592
Reviewed-by: dsinclair <[email protected]>
Commit-Queue: Henrique Nakashima <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543494}
CWE ID: CWE-20 | int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) {
// Copy visible_pages_ since it can change as a result of loading the page in
// GetPage(). See https://crbug.com/822091.
std::vector<int> visible_pages_copy(visible_pages_);
for (int page_index : visible_pages_copy) {
if (pages_[page_index]->GetPage() == page)
return page_index;
}
return -1;
}
| 172,701 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_delete_sec_context (minor_status,
context_handle,
output_token)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_buffer_t output_token;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
status = val_del_sec_ctx_args(minor_status, context_handle, output_token);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) *context_handle;
if (GSSINT_CHK_LOOP(ctx))
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
status = gssint_delete_internal_sec_context(minor_status,
ctx->mech_type,
&ctx->internal_ctx_id,
output_token);
if (status)
return status;
/* now free up the space for the union context structure */
free(ctx->mech_type->elements);
free(ctx->mech_type);
free(*context_handle);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_delete_sec_context (minor_status,
context_handle,
output_token)
OM_uint32 * minor_status;
gss_ctx_id_t * context_handle;
gss_buffer_t output_token;
{
OM_uint32 status;
gss_union_ctx_id_t ctx;
status = val_del_sec_ctx_args(minor_status, context_handle, output_token);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) *context_handle;
if (GSSINT_CHK_LOOP(ctx))
return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT);
if (ctx->internal_ctx_id != GSS_C_NO_CONTEXT) {
status = gssint_delete_internal_sec_context(minor_status,
ctx->mech_type,
&ctx->internal_ctx_id,
output_token);
if (status)
return status;
}
/* now free up the space for the union context structure */
free(ctx->mech_type->elements);
free(ctx->mech_type);
free(*context_handle);
*context_handle = GSS_C_NO_CONTEXT;
return (GSS_S_COMPLETE);
}
| 168,014 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
size_t width = static_cast<size_t>(input->width());
size_t height = static_cast<size_t>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
size_t imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (size_t i = 0; i < height / 2; i++) {
size_t topFirstElement = i * imageRowBytes;
size_t topLastElement = (i + 1) * imageRowBytes;
size_t bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> flipSkImageVertically(SkImage* input,
AlphaDisposition alphaOp) {
unsigned width = static_cast<unsigned>(input->width());
unsigned height = static_cast<unsigned>(input->height());
SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(),
(alphaOp == PremultiplyAlpha)
? kPremul_SkAlphaType
: kUnpremul_SkAlphaType);
unsigned imageRowBytes = width * info.bytesPerPixel();
RefPtr<Uint8Array> imagePixels = copySkImageData(input, info);
if (!imagePixels)
return nullptr;
for (unsigned i = 0; i < height / 2; i++) {
unsigned topFirstElement = i * imageRowBytes;
unsigned topLastElement = (i + 1) * imageRowBytes;
unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes;
std::swap_ranges(imagePixels->data() + topFirstElement,
imagePixels->data() + topLastElement,
imagePixels->data() + bottomFirstElement);
}
return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes);
}
| 172,502 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: htmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
const xmlChar *base = ctxt->input->base;
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
if (ctxt->input->base != base) {
/*
* We changed encoding from an unknown encoding
* Input buffer changed location, so we better start again
*/
return(htmlParseNameComplex(ctxt));
}
}
if (ctxt->input->base > ctxt->input->cur - len)
return(NULL);
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
CWE ID: CWE-787 | htmlParseNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
const xmlChar *base = ctxt->input->base;
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!IS_LETTER(c) && (c != '_') &&
(c != ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
((IS_LETTER(c)) || (IS_DIGIT(c)) ||
(c == '.') || (c == '-') ||
(c == '_') || (c == ':') ||
(IS_COMBINING(c)) ||
(IS_EXTENDER(c)))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
if (ctxt->input->base != base) {
/*
* We changed encoding from an unknown encoding
* Input buffer changed location, so we better start again
*/
return(htmlParseNameComplex(ctxt));
}
}
if (ctxt->input->cur - ctxt->input->base < len) {
/* Sanity check */
htmlParseErr(ctxt, XML_ERR_INTERNAL_ERROR,
"unexpected change of input buffer", NULL, NULL);
return (NULL);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 172,948 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XvQueryAdaptors(
Display *dpy,
Window window,
unsigned int *p_nAdaptors,
XvAdaptorInfo **p_pAdaptors)
{
XExtDisplayInfo *info = xv_find_display(dpy);
xvQueryAdaptorsReq *req;
xvQueryAdaptorsReply rep;
size_t size;
unsigned int ii, jj;
char *name;
XvAdaptorInfo *pas = NULL, *pa;
XvFormat *pfs, *pf;
char *buffer = NULL;
char *buffer;
char *string;
xvAdaptorInfo *pa;
xvFormat *pf;
} u;
Commit Message:
CWE ID: CWE-125 | XvQueryAdaptors(
Display *dpy,
Window window,
unsigned int *p_nAdaptors,
XvAdaptorInfo **p_pAdaptors)
{
XExtDisplayInfo *info = xv_find_display(dpy);
xvQueryAdaptorsReq *req;
xvQueryAdaptorsReply rep;
size_t size;
unsigned int ii, jj;
char *name;
char *end;
XvAdaptorInfo *pas = NULL, *pa;
XvFormat *pfs, *pf;
char *buffer = NULL;
char *buffer;
char *string;
xvAdaptorInfo *pa;
xvFormat *pf;
} u;
| 165,009 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this);
VLOG(1) << "Unregistering pairing agent";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
UnregisterAgent(
dbus::ObjectPath(kAgentPath),
base::Bind(&base::DoNothing),
base::Bind(&OnUnregisterAgentError));
}
| 171,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: NavigateToAboutBlank() {
GURL about_blank(url::kAboutBlankURL);
content::NavigationController::LoadURLParams params(about_blank);
params.frame_tree_node_id = frame_tree_node_id_;
params.source_site_instance = parent_site_instance_;
params.is_renderer_initiated = true;
web_contents()->GetController().LoadURLWithParams(params);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | NavigateToAboutBlank() {
| 173,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (tmpName[i] != 0) && (i < to_read) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (i < to_read) && (tmpName[i] != 0) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
| 169,167 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
if (client->priv->protocol_timeout > 0) {
g_source_remove (client->priv->protocol_timeout);
}
}
Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists
We used to create the GsmXSMPClient before the XSMP connection is really
accepted. This can lead to some issues, though. An example is:
https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting:
"What is happening is that a new client (probably metacity in your
case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION
phase, which causes a new GsmXSMPClient to be added to the client
store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client
has had a chance to establish a xsmp connection, which means that
client->priv->conn will not be initialized at the point that xsmp_stop
is called on the new unregistered client."
The fix is to create the GsmXSMPClient object when there's a real XSMP
connection. This implies moving the timeout that makes sure we don't
have an empty client to the XSMP server.
https://bugzilla.gnome.org/show_bug.cgi?id=598211
CWE ID: CWE-835 | gsm_xsmp_client_disconnect (GsmXSMPClient *client)
{
if (client->priv->watch_id > 0) {
g_source_remove (client->priv->watch_id);
}
if (client->priv->conn != NULL) {
SmsCleanUp (client->priv->conn);
}
if (client->priv->ice_connection != NULL) {
IceSetShutdownNegotiation (client->priv->ice_connection, FALSE);
IceCloseConnection (client->priv->ice_connection);
}
}
| 168,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int misaligned_load(struct pt_regs *regs,
__u32 opcode,
int displacement_not_indexed,
int width_shift,
int do_sign_extend)
{
/* Return -1 for a fault, 0 for OK */
int error;
int destreg;
__u64 address;
error = generate_and_check_address(regs, opcode,
displacement_not_indexed, width_shift, &address);
if (error < 0) {
return error;
}
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, address);
destreg = (opcode >> 4) & 0x3f;
if (user_mode(regs)) {
__u64 buffer;
if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) {
return -1;
}
if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) {
return -1; /* fault */
}
switch (width_shift) {
case 1:
if (do_sign_extend) {
regs->regs[destreg] = (__u64)(__s64) *(__s16 *) &buffer;
} else {
regs->regs[destreg] = (__u64) *(__u16 *) &buffer;
}
break;
case 2:
regs->regs[destreg] = (__u64)(__s64) *(__s32 *) &buffer;
break;
case 3:
regs->regs[destreg] = buffer;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
} else {
/* kernel mode - we can take short cuts since if we fault, it's a genuine bug */
__u64 lo, hi;
switch (width_shift) {
case 1:
misaligned_kernel_word_load(address, do_sign_extend, ®s->regs[destreg]);
break;
case 2:
asm ("ldlo.l %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.l %1, 3, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
case 3:
asm ("ldlo.q %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.q %1, 7, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
}
return 0;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | static int misaligned_load(struct pt_regs *regs,
__u32 opcode,
int displacement_not_indexed,
int width_shift,
int do_sign_extend)
{
/* Return -1 for a fault, 0 for OK */
int error;
int destreg;
__u64 address;
error = generate_and_check_address(regs, opcode,
displacement_not_indexed, width_shift, &address);
if (error < 0) {
return error;
}
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, address);
destreg = (opcode >> 4) & 0x3f;
if (user_mode(regs)) {
__u64 buffer;
if (!access_ok(VERIFY_READ, (unsigned long) address, 1UL<<width_shift)) {
return -1;
}
if (__copy_user(&buffer, (const void *)(int)address, (1 << width_shift)) > 0) {
return -1; /* fault */
}
switch (width_shift) {
case 1:
if (do_sign_extend) {
regs->regs[destreg] = (__u64)(__s64) *(__s16 *) &buffer;
} else {
regs->regs[destreg] = (__u64) *(__u16 *) &buffer;
}
break;
case 2:
regs->regs[destreg] = (__u64)(__s64) *(__s32 *) &buffer;
break;
case 3:
regs->regs[destreg] = buffer;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
} else {
/* kernel mode - we can take short cuts since if we fault, it's a genuine bug */
__u64 lo, hi;
switch (width_shift) {
case 1:
misaligned_kernel_word_load(address, do_sign_extend, ®s->regs[destreg]);
break;
case 2:
asm ("ldlo.l %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.l %1, 3, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
case 3:
asm ("ldlo.q %1, 0, %0" : "=r" (lo) : "r" (address));
asm ("ldhi.q %1, 7, %0" : "=r" (hi) : "r" (address));
regs->regs[destreg] = lo | hi;
break;
default:
printk("Unexpected width_shift %d in misaligned_load, PC=%08lx\n",
width_shift, (unsigned long) regs->pc);
break;
}
}
return 0;
}
| 165,799 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: log2vis_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* input string encoded in utf-8 */
PyObject *visual = NULL; /* output string encoded in utf-8 */
PyObject *result = NULL; /* unicode output string */
int length = PyUnicode_GET_SIZE (unicode);
logical = PyUnicode_AsUTF8String (unicode);
if (logical == NULL)
goto cleanup;
visual = log2vis_utf8 (logical, length, base_direction, clean, reordernsm);
if (visual == NULL)
goto cleanup;
result = PyUnicode_DecodeUTF8 (PyString_AS_STRING (visual),
PyString_GET_SIZE (visual), "strict");
cleanup:
Py_XDECREF (logical);
Py_XDECREF (visual);
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_unicode (PyObject * unicode, FriBidiParType base_direction, int clean, int reordernsm)
_pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)
{
PyUnicodeObject *logical = NULL; /* input unicode or string object */
FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */
int clean = 0; /* optional flag to clean the string */
int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/
static char *kwargs[] =
{ "logical", "base_direction", "clean", "reordernsm", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kw, "U|iii", kwargs,
&logical, &base, &clean, &reordernsm)) {
return NULL;
}
/* Validate base */
if (!(base == FRIBIDI_TYPE_RTL
|| base == FRIBIDI_TYPE_LTR
|| base == FRIBIDI_TYPE_ON)) {
return PyErr_Format (PyExc_ValueError,
"invalid value %d: use either RTL, LTR or ON",
base);
}
return unicode_log2vis (logical, base, clean, reordernsm);
}
| 165,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gdev_pdf_put_params_impl(gx_device * dev, const gx_device_pdf * save_dev, gs_param_list * plist)
{
int ecode, code;
gx_device_pdf *pdev = (gx_device_pdf *) dev;
float cl = (float)pdev->CompatibilityLevel;
bool locked = pdev->params.LockDistillerParams, ForOPDFRead;
gs_param_name param_name;
pdev->pdf_memory = gs_memory_stable(pdev->memory);
/*
* If this is a pseudo-parameter (pdfmark or DSC),
* don't bother checking for any real ones.
*/
{
gs_param_string_array ppa;
gs_param_string pps;
code = param_read_string_array(plist, (param_name = "pdfmark"), &ppa);
switch (code) {
case 0:
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = pdfmark_process(pdev, &ppa);
if (code >= 0)
return code;
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
code = param_read_string_array(plist, (param_name = "DSC"), &ppa);
switch (code) {
case 0:
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = pdf_dsc_process(pdev, &ppa);
if (code >= 0)
return code;
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
code = param_read_string(plist, (param_name = "pdfpagelabels"), &pps);
switch (code) {
case 0:
{
if (!pdev->ForOPDFRead) {
cos_dict_t *const pcd = pdev->Catalog;
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = cos_dict_put_string(pcd, (const byte *)"/PageLabels", 11,
pps.data, pps.size);
if (code >= 0)
return code;
} else
return 0;
}
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
}
/*
* Check for LockDistillerParams before doing anything else.
* If LockDistillerParams is true and is not being set to false,
* ignore all resettings of PDF-specific parameters. Note that
* LockDistillerParams is read again, and reset if necessary, in
* psdf_put_params.
*/
ecode = param_read_bool(plist, "LockDistillerParams", &locked);
if (ecode < 0)
param_signal_error(plist, param_name, ecode);
/* General parameters. */
{
int efo = 1;
ecode = param_put_int(plist, (param_name = ".EmbedFontObjects"), &efo, ecode);
if (ecode < 0)
param_signal_error(plist, param_name, ecode);
if (efo != 1)
param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
}
{
int cdv = CoreDistVersion;
ecode = param_put_int(plist, (param_name = "CoreDistVersion"), &cdv, ecode);
if (ecode < 0)
return gs_note_error(ecode);
if (cdv != CoreDistVersion)
param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
}
switch (code = param_read_float(plist, (param_name = "CompatibilityLevel"), &cl)) {
default:
ecode = code;
param_signal_error(plist, param_name, ecode);
break;
case 0:
if (!(locked && pdev->params.LockDistillerParams)) {
/*
* Must be 1.2, 1.3, 1.4, or 1.5. Per Adobe documentation, substitute
* the nearest achievable value.
*/
if (cl < (float)1.15)
cl = (float)1.1;
else if (cl < (float)1.25)
cl = (float)1.2;
else if (cl < (float)1.35)
cl = (float)1.3;
else if (cl < (float)1.45)
cl = (float)1.4;
else if (cl < (float)1.55)
cl = (float)1.5;
else if (cl < (float)1.65)
cl = (float)1.6;
else if (cl < (float)1.75)
cl = (float)1.7;
else {
cl = (float)2.0;
if (pdev->params.TransferFunctionInfo == tfi_Preserve)
pdev->params.TransferFunctionInfo = tfi_Apply;
}
}
case 1:
break;
}
{ /* HACK : gs_param_list_s::memory is documented in gsparam.h as
"for allocating coerced arrays". Not sure why zputdeviceparams
sets it to the current memory space, while the device
assumes to store them in the device's memory space.
As a hackish workaround we temporary replace it here.
Doing so because we don't want to change the global code now
because we're unable to test it with all devices.
Bug 688531 "Segmentation fault running pdfwrite from 219-01.ps".
This solution to be reconsidered after fixing
the bug 688533 "zputdeviceparams specifies a wrong memory space.".
*/
gs_memory_t *mem = plist->memory;
plist->memory = pdev->pdf_memory;
code = gs_param_read_items(plist, pdev, pdf_param_items);
if (code < 0 || (code = param_read_bool(plist, "ForOPDFRead", &ForOPDFRead)) < 0)
{
}
if (code == 0 && !pdev->is_ps2write && !(locked && pdev->params.LockDistillerParams))
pdev->ForOPDFRead = ForOPDFRead;
plist->memory = mem;
}
if (code < 0)
ecode = code;
{
/*
* Setting FirstObjectNumber is only legal if the file
* has just been opened and nothing has been written,
* or if we are setting it to the same value.
*/
long fon = pdev->FirstObjectNumber;
if (fon != save_dev->FirstObjectNumber) {
if (fon <= 0 || fon > 0x7fff0000 ||
(pdev->next_id != 0 &&
pdev->next_id !=
save_dev->FirstObjectNumber + pdf_num_initial_ids)
) {
ecode = gs_error_rangecheck;
param_signal_error(plist, "FirstObjectNumber", ecode);
}
}
}
{
/*
* Set ProcessColorModel now, because gx_default_put_params checks
* it.
*/
static const char *const pcm_names[] = {
"DeviceGray", "DeviceRGB", "DeviceCMYK", "DeviceN", 0
};
int pcm = -1;
ecode = param_put_enum(plist, "ProcessColorModel", &pcm,
pcm_names, ecode);
if (pcm >= 0) {
pdf_set_process_color_model(pdev, pcm);
rc_decrement(pdev->icc_struct, "gdev_pdf_put_params_impl, ProcessColorModel changed");
pdev->icc_struct = 0;
}
}
if (ecode < 0)
goto fail;
if (pdev->is_ps2write && (code = param_read_bool(plist, "ProduceDSC", &pdev->ProduceDSC)) < 0) {
param_signal_error(plist, param_name, code);
}
/* PDFA and PDFX are stored in the page device dictionary and therefore
* set on every setpagedevice. However, if we have encountered a file which
* can't be made this way, and the PDFACompatibilityPolicy is 1, we want to
* continue producing the file, but not as a PDF/A or PDF/X file. Its more
* or less impossible to alter the setting in the (potentially saved) page
* device dictionary, so we use this rather clunky method.
*/
if (pdev->PDFA < 0 || pdev->PDFA > 3){
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if(pdev->PDFA != 0 && pdev->AbortPDFAX)
pdev->PDFA = 0;
if(pdev->PDFX && pdev->AbortPDFAX)
pdev->PDFX = 0;
if (pdev->PDFX && pdev->PDFA != 0) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if (pdev->PDFX && pdev->ForOPDFRead) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFX", ecode);
goto fail;
}
if (pdev->PDFA != 0 && pdev->ForOPDFRead) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if (pdev->PDFA == 1 || pdev->PDFX || pdev->CompatibilityLevel < 1.4) {
pdev->HaveTransparency = false;
pdev->PreserveSMask = false;
}
/*
* We have to set version to the new value, because the set of
* legal parameter values for psdf_put_params varies according to
* the version.
*/
if (pdev->PDFX)
cl = (float)1.3; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
if (pdev->PDFA != 0 && cl < 1.4)
cl = (float)1.4;
pdev->version = (cl < 1.2 ? psdf_version_level2 : psdf_version_ll3);
if (pdev->ForOPDFRead) {
pdev->ResourcesBeforeUsage = true;
pdev->HaveCFF = false;
pdev->HavePDFWidths = false;
pdev->HaveStrokeColor = false;
cl = (float)1.2; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
pdev->MaxInlineImageSize = max_long; /* Save printer's RAM from saving temporary image data.
Immediate images doen't need buffering. */
pdev->version = psdf_version_level2;
} else {
pdev->ResourcesBeforeUsage = false;
pdev->HaveCFF = true;
pdev->HavePDFWidths = true;
pdev->HaveStrokeColor = true;
}
pdev->ParamCompatibilityLevel = cl;
if (cl < 1.2) {
pdev->HaveCFF = false;
}
ecode = gdev_psdf_put_params(dev, plist);
if (ecode < 0)
goto fail;
if (pdev->CompatibilityLevel > 1.7 && pdev->params.TransferFunctionInfo == tfi_Preserve) {
pdev->params.TransferFunctionInfo = tfi_Apply;
emprintf(pdev->memory, "\nIt is not possible to preserve transfer functions in PDF 2.0\ntransfer functions will be applied instead\n");
}
if (pdev->params.ConvertCMYKImagesToRGB) {
if (pdev->params.ColorConversionStrategy == ccs_CMYK) {
emprintf(pdev->memory, "ConvertCMYKImagesToRGB is not compatible with ColorConversionStrategy of CMYK\n");
} else {
if (pdev->params.ColorConversionStrategy == ccs_Gray) {
emprintf(pdev->memory, "ConvertCMYKImagesToRGB is not compatible with ColorConversionStrategy of Gray\n");
} else {
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,1);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
}
}
}
switch (pdev->params.ColorConversionStrategy) {
case ccs_ByObjectType:
case ccs_LeaveColorUnchanged:
break;
case ccs_UseDeviceDependentColor:
case ccs_UseDeviceIndependentColor:
case ccs_UseDeviceIndependentColorForImages:
pdev->params.TransferFunctionInfo = tfi_Apply;
break;
case ccs_CMYK:
pdev->params.TransferFunctionInfo = tfi_Apply;
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev, 2);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
break;
case ccs_Gray:
pdev->params.TransferFunctionInfo = tfi_Apply;
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,0);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
break;
case ccs_sRGB:
case ccs_RGB:
pdev->params.TransferFunctionInfo = tfi_Apply;
/* Only bother to do this if we didn't handle it above */
if (!pdev->params.ConvertCMYKImagesToRGB) {
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,1);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
}
break;
default:
break;
}
if (cl < 1.5f && pdev->params.ColorImage.Filter != NULL &&
!strcmp(pdev->params.ColorImage.Filter, "JPXEncode")) {
emprintf(pdev->memory,
"JPXEncode requires CompatibilityLevel >= 1.5 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (cl < 1.5f && pdev->params.GrayImage.Filter != NULL &&
!strcmp(pdev->params.GrayImage.Filter, "JPXEncode")) {
emprintf(pdev->memory,
"JPXEncode requires CompatibilityLevel >= 1.5 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (cl < 1.4f && pdev->params.MonoImage.Filter != NULL &&
!strcmp(pdev->params.MonoImage.Filter, "JBIG2Encode")) {
emprintf(pdev->memory,
"JBIG2Encode requires CompatibilityLevel >= 1.4 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (pdev->HaveTrueTypes && pdev->version == psdf_version_level2) {
pdev->version = psdf_version_level2_with_TT ;
}
if (ecode < 0)
goto fail;
if (pdev->FirstObjectNumber != save_dev->FirstObjectNumber) {
if (pdev->xref.file != 0) {
if (gp_fseek_64(pdev->xref.file, 0L, SEEK_SET) != 0) {
ecode = gs_error_ioerror;
goto fail;
}
pdf_initialize_ids(pdev);
}
}
/* Handle the float/double mismatch. */
pdev->CompatibilityLevel = (int)(cl * 10 + 0.5) / 10.0;
if(pdev->OwnerPassword.size != save_dev->OwnerPassword.size ||
(pdev->OwnerPassword.size != 0 &&
memcmp(pdev->OwnerPassword.data, save_dev->OwnerPassword.data,
pdev->OwnerPassword.size) != 0)) {
if (pdev->is_open) {
if (pdev->PageCount == 0) {
gs_closedevice((gx_device *)save_dev);
return 0;
}
else
emprintf(pdev->memory, "Owner Password changed mid-job, ignoring.\n");
}
}
if (pdev->Linearise && pdev->is_ps2write) {
emprintf(pdev->memory, "Can't linearise PostScript output, ignoring\n");
pdev->Linearise = false;
}
if (pdev->Linearise && pdev->OwnerPassword.size != 0) {
emprintf(pdev->memory, "Can't linearise encrypted PDF, ignoring\n");
pdev->Linearise = false;
}
if (pdev->FlattenFonts)
pdev->PreserveTrMode = false;
return 0;
fail:
/* Restore all the parameters to their original state. */
pdev->version = save_dev->version;
pdf_set_process_color_model(pdev, save_dev->pcm_color_info_index);
pdev->saved_fill_color = save_dev->saved_fill_color;
pdev->saved_stroke_color = save_dev->saved_fill_color;
{
const gs_param_item_t *ppi = pdf_param_items;
for (; ppi->key; ++ppi)
memcpy((char *)pdev + ppi->offset,
(char *)save_dev + ppi->offset,
gs_param_type_sizes[ppi->type]);
pdev->ForOPDFRead = save_dev->ForOPDFRead;
}
return ecode;
}
Commit Message:
CWE ID: CWE-704 | gdev_pdf_put_params_impl(gx_device * dev, const gx_device_pdf * save_dev, gs_param_list * plist)
{
int ecode, code;
gx_device_pdf *pdev = (gx_device_pdf *) dev;
float cl = (float)pdev->CompatibilityLevel;
bool locked = pdev->params.LockDistillerParams, ForOPDFRead;
gs_param_name param_name;
pdev->pdf_memory = gs_memory_stable(pdev->memory);
/*
* If this is a pseudo-parameter (pdfmark or DSC),
* don't bother checking for any real ones.
*/
{
gs_param_string_array ppa;
gs_param_string pps;
code = param_read_string_array(plist, (param_name = "pdfmark"), &ppa);
switch (code) {
case 0:
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = pdfmark_process(pdev, &ppa);
if (code >= 0)
return code;
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
code = param_read_string_array(plist, (param_name = "DSC"), &ppa);
switch (code) {
case 0:
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = pdf_dsc_process(pdev, &ppa);
if (code >= 0)
return code;
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
code = param_read_string(plist, (param_name = "pdfpagelabels"), &pps);
switch (code) {
case 0:
{
if (!pdev->ForOPDFRead) {
cos_dict_t *const pcd = pdev->Catalog;
code = pdfwrite_pdf_open_document(pdev);
if (code < 0)
return code;
code = cos_dict_put_string(pcd, (const byte *)"/PageLabels", 11,
pps.data, pps.size);
if (code >= 0)
return code;
} else
return 0;
}
/* falls through for errors */
default:
param_signal_error(plist, param_name, code);
return code;
case 1:
break;
}
}
/*
* Check for LockDistillerParams before doing anything else.
* If LockDistillerParams is true and is not being set to false,
* ignore all resettings of PDF-specific parameters. Note that
* LockDistillerParams is read again, and reset if necessary, in
* psdf_put_params.
*/
ecode = param_read_bool(plist, (param_name = "LockDistillerParams"), &locked);
if (ecode < 0)
param_signal_error(plist, param_name, ecode);
/* General parameters. */
{
int efo = 1;
ecode = param_put_int(plist, (param_name = ".EmbedFontObjects"), &efo, ecode);
if (ecode < 0)
param_signal_error(plist, param_name, ecode);
if (efo != 1)
param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
}
{
int cdv = CoreDistVersion;
ecode = param_put_int(plist, (param_name = "CoreDistVersion"), &cdv, ecode);
if (ecode < 0)
return gs_note_error(ecode);
if (cdv != CoreDistVersion)
param_signal_error(plist, param_name, ecode = gs_error_rangecheck);
}
switch (code = param_read_float(plist, (param_name = "CompatibilityLevel"), &cl)) {
default:
ecode = code;
param_signal_error(plist, param_name, ecode);
break;
case 0:
if (!(locked && pdev->params.LockDistillerParams)) {
/*
* Must be 1.2, 1.3, 1.4, or 1.5. Per Adobe documentation, substitute
* the nearest achievable value.
*/
if (cl < (float)1.15)
cl = (float)1.1;
else if (cl < (float)1.25)
cl = (float)1.2;
else if (cl < (float)1.35)
cl = (float)1.3;
else if (cl < (float)1.45)
cl = (float)1.4;
else if (cl < (float)1.55)
cl = (float)1.5;
else if (cl < (float)1.65)
cl = (float)1.6;
else if (cl < (float)1.75)
cl = (float)1.7;
else {
cl = (float)2.0;
if (pdev->params.TransferFunctionInfo == tfi_Preserve)
pdev->params.TransferFunctionInfo = tfi_Apply;
}
}
case 1:
break;
}
{ /* HACK : gs_param_list_s::memory is documented in gsparam.h as
"for allocating coerced arrays". Not sure why zputdeviceparams
sets it to the current memory space, while the device
assumes to store them in the device's memory space.
As a hackish workaround we temporary replace it here.
Doing so because we don't want to change the global code now
because we're unable to test it with all devices.
Bug 688531 "Segmentation fault running pdfwrite from 219-01.ps".
This solution to be reconsidered after fixing
the bug 688533 "zputdeviceparams specifies a wrong memory space.".
*/
gs_memory_t *mem = plist->memory;
plist->memory = pdev->pdf_memory;
code = gs_param_read_items(plist, pdev, pdf_param_items);
if (code < 0 || (code = param_read_bool(plist, "ForOPDFRead", &ForOPDFRead)) < 0)
{
}
if (code == 0 && !pdev->is_ps2write && !(locked && pdev->params.LockDistillerParams))
pdev->ForOPDFRead = ForOPDFRead;
plist->memory = mem;
}
if (code < 0)
ecode = code;
{
/*
* Setting FirstObjectNumber is only legal if the file
* has just been opened and nothing has been written,
* or if we are setting it to the same value.
*/
long fon = pdev->FirstObjectNumber;
if (fon != save_dev->FirstObjectNumber) {
if (fon <= 0 || fon > 0x7fff0000 ||
(pdev->next_id != 0 &&
pdev->next_id !=
save_dev->FirstObjectNumber + pdf_num_initial_ids)
) {
ecode = gs_error_rangecheck;
param_signal_error(plist, "FirstObjectNumber", ecode);
}
}
}
{
/*
* Set ProcessColorModel now, because gx_default_put_params checks
* it.
*/
static const char *const pcm_names[] = {
"DeviceGray", "DeviceRGB", "DeviceCMYK", "DeviceN", 0
};
int pcm = -1;
ecode = param_put_enum(plist, "ProcessColorModel", &pcm,
pcm_names, ecode);
if (pcm >= 0) {
pdf_set_process_color_model(pdev, pcm);
rc_decrement(pdev->icc_struct, "gdev_pdf_put_params_impl, ProcessColorModel changed");
pdev->icc_struct = 0;
}
}
if (ecode < 0)
goto fail;
if (pdev->is_ps2write && (code = param_read_bool(plist, "ProduceDSC", &pdev->ProduceDSC)) < 0) {
param_signal_error(plist, param_name, code);
}
/* PDFA and PDFX are stored in the page device dictionary and therefore
* set on every setpagedevice. However, if we have encountered a file which
* can't be made this way, and the PDFACompatibilityPolicy is 1, we want to
* continue producing the file, but not as a PDF/A or PDF/X file. Its more
* or less impossible to alter the setting in the (potentially saved) page
* device dictionary, so we use this rather clunky method.
*/
if (pdev->PDFA < 0 || pdev->PDFA > 3){
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if(pdev->PDFA != 0 && pdev->AbortPDFAX)
pdev->PDFA = 0;
if(pdev->PDFX && pdev->AbortPDFAX)
pdev->PDFX = 0;
if (pdev->PDFX && pdev->PDFA != 0) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if (pdev->PDFX && pdev->ForOPDFRead) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFX", ecode);
goto fail;
}
if (pdev->PDFA != 0 && pdev->ForOPDFRead) {
ecode = gs_note_error(gs_error_rangecheck);
param_signal_error(plist, "PDFA", ecode);
goto fail;
}
if (pdev->PDFA == 1 || pdev->PDFX || pdev->CompatibilityLevel < 1.4) {
pdev->HaveTransparency = false;
pdev->PreserveSMask = false;
}
/*
* We have to set version to the new value, because the set of
* legal parameter values for psdf_put_params varies according to
* the version.
*/
if (pdev->PDFX)
cl = (float)1.3; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
if (pdev->PDFA != 0 && cl < 1.4)
cl = (float)1.4;
pdev->version = (cl < 1.2 ? psdf_version_level2 : psdf_version_ll3);
if (pdev->ForOPDFRead) {
pdev->ResourcesBeforeUsage = true;
pdev->HaveCFF = false;
pdev->HavePDFWidths = false;
pdev->HaveStrokeColor = false;
cl = (float)1.2; /* Instead pdev->CompatibilityLevel = 1.2; - see below. */
pdev->MaxInlineImageSize = max_long; /* Save printer's RAM from saving temporary image data.
Immediate images doen't need buffering. */
pdev->version = psdf_version_level2;
} else {
pdev->ResourcesBeforeUsage = false;
pdev->HaveCFF = true;
pdev->HavePDFWidths = true;
pdev->HaveStrokeColor = true;
}
pdev->ParamCompatibilityLevel = cl;
if (cl < 1.2) {
pdev->HaveCFF = false;
}
ecode = gdev_psdf_put_params(dev, plist);
if (ecode < 0)
goto fail;
if (pdev->CompatibilityLevel > 1.7 && pdev->params.TransferFunctionInfo == tfi_Preserve) {
pdev->params.TransferFunctionInfo = tfi_Apply;
emprintf(pdev->memory, "\nIt is not possible to preserve transfer functions in PDF 2.0\ntransfer functions will be applied instead\n");
}
if (pdev->params.ConvertCMYKImagesToRGB) {
if (pdev->params.ColorConversionStrategy == ccs_CMYK) {
emprintf(pdev->memory, "ConvertCMYKImagesToRGB is not compatible with ColorConversionStrategy of CMYK\n");
} else {
if (pdev->params.ColorConversionStrategy == ccs_Gray) {
emprintf(pdev->memory, "ConvertCMYKImagesToRGB is not compatible with ColorConversionStrategy of Gray\n");
} else {
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,1);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
}
}
}
switch (pdev->params.ColorConversionStrategy) {
case ccs_ByObjectType:
case ccs_LeaveColorUnchanged:
break;
case ccs_UseDeviceDependentColor:
case ccs_UseDeviceIndependentColor:
case ccs_UseDeviceIndependentColorForImages:
pdev->params.TransferFunctionInfo = tfi_Apply;
break;
case ccs_CMYK:
pdev->params.TransferFunctionInfo = tfi_Apply;
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev, 2);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
break;
case ccs_Gray:
pdev->params.TransferFunctionInfo = tfi_Apply;
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,0);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
break;
case ccs_sRGB:
case ccs_RGB:
pdev->params.TransferFunctionInfo = tfi_Apply;
/* Only bother to do this if we didn't handle it above */
if (!pdev->params.ConvertCMYKImagesToRGB) {
if (pdev->icc_struct)
rc_decrement(pdev->icc_struct,
"reset default profile\n");
pdf_set_process_color_model(pdev,1);
ecode = gsicc_init_device_profile_struct((gx_device *)pdev, NULL, 0);
if (ecode < 0)
goto fail;
}
break;
default:
break;
}
if (cl < 1.5f && pdev->params.ColorImage.Filter != NULL &&
!strcmp(pdev->params.ColorImage.Filter, "JPXEncode")) {
emprintf(pdev->memory,
"JPXEncode requires CompatibilityLevel >= 1.5 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (cl < 1.5f && pdev->params.GrayImage.Filter != NULL &&
!strcmp(pdev->params.GrayImage.Filter, "JPXEncode")) {
emprintf(pdev->memory,
"JPXEncode requires CompatibilityLevel >= 1.5 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (cl < 1.4f && pdev->params.MonoImage.Filter != NULL &&
!strcmp(pdev->params.MonoImage.Filter, "JBIG2Encode")) {
emprintf(pdev->memory,
"JBIG2Encode requires CompatibilityLevel >= 1.4 .\n");
ecode = gs_note_error(gs_error_rangecheck);
}
if (pdev->HaveTrueTypes && pdev->version == psdf_version_level2) {
pdev->version = psdf_version_level2_with_TT ;
}
if (ecode < 0)
goto fail;
if (pdev->FirstObjectNumber != save_dev->FirstObjectNumber) {
if (pdev->xref.file != 0) {
if (gp_fseek_64(pdev->xref.file, 0L, SEEK_SET) != 0) {
ecode = gs_error_ioerror;
goto fail;
}
pdf_initialize_ids(pdev);
}
}
/* Handle the float/double mismatch. */
pdev->CompatibilityLevel = (int)(cl * 10 + 0.5) / 10.0;
if(pdev->OwnerPassword.size != save_dev->OwnerPassword.size ||
(pdev->OwnerPassword.size != 0 &&
memcmp(pdev->OwnerPassword.data, save_dev->OwnerPassword.data,
pdev->OwnerPassword.size) != 0)) {
if (pdev->is_open) {
if (pdev->PageCount == 0) {
gs_closedevice((gx_device *)save_dev);
return 0;
}
else
emprintf(pdev->memory, "Owner Password changed mid-job, ignoring.\n");
}
}
if (pdev->Linearise && pdev->is_ps2write) {
emprintf(pdev->memory, "Can't linearise PostScript output, ignoring\n");
pdev->Linearise = false;
}
if (pdev->Linearise && pdev->OwnerPassword.size != 0) {
emprintf(pdev->memory, "Can't linearise encrypted PDF, ignoring\n");
pdev->Linearise = false;
}
if (pdev->FlattenFonts)
pdev->PreserveTrMode = false;
return 0;
fail:
/* Restore all the parameters to their original state. */
pdev->version = save_dev->version;
pdf_set_process_color_model(pdev, save_dev->pcm_color_info_index);
pdev->saved_fill_color = save_dev->saved_fill_color;
pdev->saved_stroke_color = save_dev->saved_fill_color;
{
const gs_param_item_t *ppi = pdf_param_items;
for (; ppi->key; ++ppi)
memcpy((char *)pdev + ppi->offset,
(char *)save_dev + ppi->offset,
gs_param_type_sizes[ppi->type]);
pdev->ForOPDFRead = save_dev->ForOPDFRead;
}
return ecode;
}
| 164,704 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->length * 6 / 5;
if (newlen == x->length)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
Commit Message: Merge pull request #27 from kcwu/fix-strgrow
Fix potential heap buffer corruption due to Strgrow
CWE ID: CWE-119 | Strgrow(Str x)
{
char *old = x->ptr;
int newlen;
newlen = x->area_size * 6 / 5;
if (newlen == x->area_size)
newlen += 2;
x->ptr = GC_MALLOC_ATOMIC(newlen);
x->area_size = newlen;
bcopy((void *)old, (void *)x->ptr, x->length);
GC_free(old);
}
| 166,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: eXosip_init (struct eXosip_t *excontext)
{
osip_t *osip;
int i;
memset (excontext, 0, sizeof (eXosip_t));
excontext->dscp = 0x1A;
snprintf (excontext->ipv4_for_gateway, 256, "%s", "217.12.3.11");
snprintf (excontext->ipv6_for_gateway, 256, "%s", "2001:638:500:101:2e0:81ff:fe24:37c6");
#ifdef WIN32
/* Initializing windows socket library */
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (1, 1);
i = WSAStartup (wVersionRequested, &wsaData);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_WARNING, NULL, "eXosip: Unable to initialize WINSOCK, reason: %d\n", i));
/* return -1; It might be already initilized?? */
}
}
#endif
excontext->user_agent = osip_strdup ("eXosip/" EXOSIP_VERSION);
if (excontext->user_agent == NULL)
return OSIP_NOMEM;
excontext->j_calls = NULL;
excontext->j_stop_ua = 0;
#ifndef OSIP_MONOTHREAD
excontext->j_thread = NULL;
#endif
i = osip_list_init (&excontext->j_transactions);
excontext->j_reg = NULL;
#ifndef OSIP_MONOTHREAD
#if !defined (_WIN32_WCE)
excontext->j_cond = (struct osip_cond *) osip_cond_init ();
if (excontext->j_cond == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
return OSIP_NOMEM;
}
#endif
excontext->j_mutexlock = (struct osip_mutex *) osip_mutex_init ();
if (excontext->j_mutexlock == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
#if !defined (_WIN32_WCE)
osip_cond_destroy ((struct osip_cond *) excontext->j_cond);
excontext->j_cond = NULL;
#endif
return OSIP_NOMEM;
}
#endif
i = osip_init (&osip);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_ERROR, NULL, "eXosip: Cannot initialize osip!\n"));
return i;
}
osip_set_application_context (osip, &excontext);
_eXosip_set_callbacks (osip);
excontext->j_osip = osip;
#ifndef OSIP_MONOTHREAD
/* open a TCP socket to wake up the application when needed. */
excontext->j_socketctl = jpipe ();
if (excontext->j_socketctl == NULL)
return OSIP_UNDEFINED_ERROR;
excontext->j_socketctl_event = jpipe ();
if (excontext->j_socketctl_event == NULL)
return OSIP_UNDEFINED_ERROR;
#endif
/* To be changed in osip! */
excontext->j_events = (osip_fifo_t *) osip_malloc (sizeof (osip_fifo_t));
if (excontext->j_events == NULL)
return OSIP_NOMEM;
osip_fifo_init (excontext->j_events);
excontext->use_rport = 1;
excontext->dns_capabilities = 2;
excontext->enable_dns_cache = 1;
excontext->ka_interval = 17000;
snprintf(excontext->ka_crlf, sizeof(excontext->ka_crlf), "\r\n\r\n");
excontext->ka_options = 0;
excontext->autoanswer_bye = 1;
excontext->auto_masquerade_contact = 1;
excontext->masquerade_via=0;
return OSIP_SUCCESS;
}
Commit Message:
CWE ID: CWE-189 | eXosip_init (struct eXosip_t *excontext)
{
osip_t *osip;
int i;
memset (excontext, 0, sizeof (eXosip_t));
excontext->dscp = 0x1A;
snprintf (excontext->ipv4_for_gateway, 256, "%s", "217.12.3.11");
snprintf (excontext->ipv6_for_gateway, 256, "%s", "2001:638:500:101:2e0:81ff:fe24:37c6");
#ifdef WIN32
/* Initializing windows socket library */
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD (1, 1);
i = WSAStartup (wVersionRequested, &wsaData);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_WARNING, NULL, "eXosip: Unable to initialize WINSOCK, reason: %d\n", i));
/* return -1; It might be already initilized?? */
}
}
#endif
excontext->user_agent = osip_strdup ("eXosip/" EXOSIP_VERSION);
if (excontext->user_agent == NULL)
return OSIP_NOMEM;
excontext->j_calls = NULL;
excontext->j_stop_ua = 0;
#ifndef OSIP_MONOTHREAD
excontext->j_thread = NULL;
#endif
i = osip_list_init (&excontext->j_transactions);
excontext->j_reg = NULL;
#ifndef OSIP_MONOTHREAD
#if !defined (_WIN32_WCE)
excontext->j_cond = (struct osip_cond *) osip_cond_init ();
if (excontext->j_cond == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
return OSIP_NOMEM;
}
#endif
excontext->j_mutexlock = (struct osip_mutex *) osip_mutex_init ();
if (excontext->j_mutexlock == NULL) {
osip_free (excontext->user_agent);
excontext->user_agent = NULL;
#if !defined (_WIN32_WCE)
osip_cond_destroy ((struct osip_cond *) excontext->j_cond);
excontext->j_cond = NULL;
#endif
return OSIP_NOMEM;
}
#endif
i = osip_init (&osip);
if (i != 0) {
OSIP_TRACE (osip_trace (__FILE__, __LINE__, OSIP_ERROR, NULL, "eXosip: Cannot initialize osip!\n"));
return i;
}
osip_set_application_context (osip, &excontext);
_eXosip_set_callbacks (osip);
excontext->j_osip = osip;
#ifndef OSIP_MONOTHREAD
/* open a TCP socket to wake up the application when needed. */
excontext->j_socketctl = jpipe ();
if (excontext->j_socketctl == NULL)
return OSIP_UNDEFINED_ERROR;
excontext->j_socketctl_event = jpipe ();
if (excontext->j_socketctl_event == NULL)
return OSIP_UNDEFINED_ERROR;
#endif
/* To be changed in osip! */
excontext->j_events = (osip_fifo_t *) osip_malloc (sizeof (osip_fifo_t));
if (excontext->j_events == NULL)
return OSIP_NOMEM;
osip_fifo_init (excontext->j_events);
excontext->use_rport = 1;
excontext->dns_capabilities = 2;
excontext->enable_dns_cache = 1;
excontext->ka_interval = 17000;
snprintf(excontext->ka_crlf, sizeof(excontext->ka_crlf), "\r\n\r\n");
excontext->ka_options = 0;
excontext->autoanswer_bye = 1;
excontext->auto_masquerade_contact = 1;
excontext->masquerade_via=0;
excontext->use_ephemeral_port=1;
return OSIP_SUCCESS;
}
| 165,429 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_vld_decode(
dec_state_t *ps_dec,
WORD16 *pi2_outAddr, /*!< Address where decoded symbols will be stored */
const UWORD8 *pu1_scan, /*!< Scan table to be used */
UWORD8 *pu1_pos, /*!< Scan table to be used */
UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */
UWORD16 u2_chroma_flag, /*!< Chroma Block or not */
UWORD16 u2_d_picture, /*!< D Picture or not */
UWORD16 u2_intra_vlc_format, /*!< Intra VLC format */
UWORD16 u2_mpeg2, /*!< MPEG-2 or not */
WORD32 *pi4_num_coeffs /*!< Returns the number of coeffs in block */
)
{
UWORD32 u4_sym_len;
UWORD32 u4_decoded_value;
UWORD32 u4_level_first_byte;
WORD32 u4_level;
UWORD32 u4_run, u4_numCoeffs;
UWORD32 u4_buf;
UWORD32 u4_buf_nxt;
UWORD32 u4_offset;
UWORD32 *pu4_buf_aligned;
UWORD32 u4_bits;
stream_t *ps_stream = &ps_dec->s_bit_stream;
WORD32 u4_pos;
UWORD32 u4_nz_cols;
UWORD32 u4_nz_rows;
*pi4_num_coeffs = 0;
ps_dec->u4_non_zero_cols = 0;
ps_dec->u4_non_zero_rows = 0;
u4_nz_cols = ps_dec->u4_non_zero_cols;
u4_nz_rows = ps_dec->u4_non_zero_rows;
GET_TEMP_STREAM_DATA(u4_buf,u4_buf_nxt,u4_offset,pu4_buf_aligned,ps_stream)
/**************************************************************************/
/* Decode the DC coefficient in case of Intra block */
/**************************************************************************/
if(u2_intra_flag)
{
WORD32 dc_size;
WORD32 dc_diff;
WORD32 maxLen;
WORD32 idx;
maxLen = MPEG2_DCT_DC_SIZE_LEN;
idx = 0;
if(u2_chroma_flag != 0)
{
maxLen += 1;
idx++;
}
{
WORD16 end = 0;
UWORD32 maxLen_tmp = maxLen;
UWORD16 m_iBit;
/* Get the maximum number of bits needed to decode a symbol */
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,maxLen)
do
{
maxLen_tmp--;
/* Read one bit at a time from the variable to decode the huffman code */
m_iBit = (UWORD8)((u4_bits >> maxLen_tmp) & 0x1);
/* Get the next node pointer or the symbol from the tree */
end = gai2_impeg2d_dct_dc_size[idx][end][m_iBit];
}while(end > 0);
dc_size = end + MPEG2_DCT_DC_SIZE_OFFSET;
/* Flush the appropriate number of bits from the stream */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,(maxLen - maxLen_tmp),pu4_buf_aligned)
}
if (dc_size != 0)
{
UWORD32 u4_bits;
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, dc_size)
dc_diff = u4_bits;
if ((dc_diff & (1 << (dc_size - 1))) == 0) //v Probably the prediction algo?
dc_diff -= (1 << dc_size) - 1;
}
else
{
dc_diff = 0;
}
pi2_outAddr[*pi4_num_coeffs] = dc_diff;
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
if (0 != dc_diff)
{
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
u4_numCoeffs = 1;
}
/**************************************************************************/
/* Decoding of first AC coefficient in case of non Intra block */
/**************************************************************************/
else
{
/* First symbol can be 1s */
UWORD32 u4_bits;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,1)
if(u4_bits == 1)
{
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,1, pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, 1)
if(u4_bits == 1)
{
pi2_outAddr[*pi4_num_coeffs] = -1;
}
else
{
pi2_outAddr[*pi4_num_coeffs] = 1;
}
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
u4_numCoeffs = 1;
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
else
{
u4_numCoeffs = 0;
}
}
if (1 == u2_d_picture)
{
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE);
}
if (1 == u2_intra_vlc_format && u2_intra_flag)
{
while(1)
{
UWORD32 lead_zeros;
WORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,u4_sym_len)
DecodedValue = gau2_impeg2d_tab_one_1_9[u4_bits >> 8];
u4_sym_len = (DecodedValue & 0xf);
u4_level = DecodedValue >> 9;
/* One table lookup */
if(0 != u4_level)
{
u4_run = ((DecodedValue >> 4) & 0x1f);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if (DecodedValue == END_OF_BLOCK_ONE)
{
u4_sym_len = 4;
break;
}
else
{
/*Second table lookup*/
lead_zeros = CLZ(u4_bits) - 20;/* -16 since we are dealing with WORD32 */
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
if (1 == lead_zeros)
{
u4_sym_len = ((u4_bits & 0x18) >> 3) == 2 ? 11:10;
}
else
{
u4_sym_len = 11 + lead_zeros;
}
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_one_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG2 Escape Code */
/*********************************************************************/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
}
else
{
while(1)
{
UWORD32 lead_zeros;
UWORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf, u4_buf_nxt, u4_offset, u4_bits, u4_sym_len)
DecodedValue = gau2_impeg2d_tab_zero_1_9[u4_bits >> 8];
u4_sym_len = BITS(DecodedValue, 3, 0);
u4_level = ((WORD16) DecodedValue) >> 9;
if (0 != u4_level)
{
u4_run = BITS(DecodedValue, 8,4);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if(DecodedValue == END_OF_BLOCK_ZERO)
{
u4_sym_len = 2;
break;
}
else
{
lead_zeros = CLZ(u4_bits) - 20;/* -15 since we are dealing with WORD32 */
/*Second table lookup*/
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
u4_sym_len = 11 + lead_zeros;
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_zero_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
if (1 == lead_zeros)
u4_sym_len--;
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*Escape Sequence*/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
}
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
}
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Fixed stack buffer overflow
Bugfix: 25812590
Moved check for numCoeffs > 64 inside the coeff decode loop
Change-Id: I444b77ef2a3da9233ec14bb72ac70b7e2fa56bd1
(cherry picked from commit ff3496c45c571da7eb93d6f9f05758813468fc72)
CWE ID: CWE-119 | IMPEG2D_ERROR_CODES_T impeg2d_vld_decode(
dec_state_t *ps_dec,
WORD16 *pi2_outAddr, /*!< Address where decoded symbols will be stored */
const UWORD8 *pu1_scan, /*!< Scan table to be used */
UWORD8 *pu1_pos, /*!< Scan table to be used */
UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */
UWORD16 u2_chroma_flag, /*!< Chroma Block or not */
UWORD16 u2_d_picture, /*!< D Picture or not */
UWORD16 u2_intra_vlc_format, /*!< Intra VLC format */
UWORD16 u2_mpeg2, /*!< MPEG-2 or not */
WORD32 *pi4_num_coeffs /*!< Returns the number of coeffs in block */
)
{
UWORD32 u4_sym_len;
UWORD32 u4_decoded_value;
UWORD32 u4_level_first_byte;
WORD32 u4_level;
UWORD32 u4_run, u4_numCoeffs;
UWORD32 u4_buf;
UWORD32 u4_buf_nxt;
UWORD32 u4_offset;
UWORD32 *pu4_buf_aligned;
UWORD32 u4_bits;
stream_t *ps_stream = &ps_dec->s_bit_stream;
WORD32 u4_pos;
UWORD32 u4_nz_cols;
UWORD32 u4_nz_rows;
*pi4_num_coeffs = 0;
ps_dec->u4_non_zero_cols = 0;
ps_dec->u4_non_zero_rows = 0;
u4_nz_cols = ps_dec->u4_non_zero_cols;
u4_nz_rows = ps_dec->u4_non_zero_rows;
GET_TEMP_STREAM_DATA(u4_buf,u4_buf_nxt,u4_offset,pu4_buf_aligned,ps_stream)
/**************************************************************************/
/* Decode the DC coefficient in case of Intra block */
/**************************************************************************/
if(u2_intra_flag)
{
WORD32 dc_size;
WORD32 dc_diff;
WORD32 maxLen;
WORD32 idx;
maxLen = MPEG2_DCT_DC_SIZE_LEN;
idx = 0;
if(u2_chroma_flag != 0)
{
maxLen += 1;
idx++;
}
{
WORD16 end = 0;
UWORD32 maxLen_tmp = maxLen;
UWORD16 m_iBit;
/* Get the maximum number of bits needed to decode a symbol */
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,maxLen)
do
{
maxLen_tmp--;
/* Read one bit at a time from the variable to decode the huffman code */
m_iBit = (UWORD8)((u4_bits >> maxLen_tmp) & 0x1);
/* Get the next node pointer or the symbol from the tree */
end = gai2_impeg2d_dct_dc_size[idx][end][m_iBit];
}while(end > 0);
dc_size = end + MPEG2_DCT_DC_SIZE_OFFSET;
/* Flush the appropriate number of bits from the stream */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,(maxLen - maxLen_tmp),pu4_buf_aligned)
}
if (dc_size != 0)
{
UWORD32 u4_bits;
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, dc_size)
dc_diff = u4_bits;
if ((dc_diff & (1 << (dc_size - 1))) == 0) //v Probably the prediction algo?
dc_diff -= (1 << dc_size) - 1;
}
else
{
dc_diff = 0;
}
pi2_outAddr[*pi4_num_coeffs] = dc_diff;
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
if (0 != dc_diff)
{
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
u4_numCoeffs = 1;
}
/**************************************************************************/
/* Decoding of first AC coefficient in case of non Intra block */
/**************************************************************************/
else
{
/* First symbol can be 1s */
UWORD32 u4_bits;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,1)
if(u4_bits == 1)
{
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,1, pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, 1)
if(u4_bits == 1)
{
pi2_outAddr[*pi4_num_coeffs] = -1;
}
else
{
pi2_outAddr[*pi4_num_coeffs] = 1;
}
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
u4_numCoeffs = 1;
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
else
{
u4_numCoeffs = 0;
}
}
if (1 == u2_d_picture)
{
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE);
}
if (1 == u2_intra_vlc_format && u2_intra_flag)
{
while(1)
{
UWORD32 lead_zeros;
WORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,u4_sym_len)
DecodedValue = gau2_impeg2d_tab_one_1_9[u4_bits >> 8];
u4_sym_len = (DecodedValue & 0xf);
u4_level = DecodedValue >> 9;
/* One table lookup */
if(0 != u4_level)
{
u4_run = ((DecodedValue >> 4) & 0x1f);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if (DecodedValue == END_OF_BLOCK_ONE)
{
u4_sym_len = 4;
break;
}
else
{
/*Second table lookup*/
lead_zeros = CLZ(u4_bits) - 20;/* -16 since we are dealing with WORD32 */
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
if (1 == lead_zeros)
{
u4_sym_len = ((u4_bits & 0x18) >> 3) == 2 ? 11:10;
}
else
{
u4_sym_len = 11 + lead_zeros;
}
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_one_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG2 Escape Code */
/*********************************************************************/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
}
else
{
while(1)
{
UWORD32 lead_zeros;
UWORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf, u4_buf_nxt, u4_offset, u4_bits, u4_sym_len)
DecodedValue = gau2_impeg2d_tab_zero_1_9[u4_bits >> 8];
u4_sym_len = BITS(DecodedValue, 3, 0);
u4_level = ((WORD16) DecodedValue) >> 9;
if (0 != u4_level)
{
u4_run = BITS(DecodedValue, 8,4);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if(DecodedValue == END_OF_BLOCK_ZERO)
{
u4_sym_len = 2;
break;
}
else
{
lead_zeros = CLZ(u4_bits) - 20;/* -15 since we are dealing with WORD32 */
/*Second table lookup*/
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
u4_sym_len = 11 + lead_zeros;
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_zero_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
if (1 == lead_zeros)
u4_sym_len--;
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*Escape Sequence*/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
}
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 173,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int open_debug_log(void) {
/* don't do anything if we're not actually running... */
if(verify_config || test_scheduling == TRUE)
return OK;
/* don't do anything if we're not debugging */
if(debug_level == DEBUGL_NONE)
return OK;
if((debug_file_fp = fopen(debug_file, "a+")) == NULL)
return ERROR;
(void)fcntl(fileno(debug_file_fp), F_SETFD, FD_CLOEXEC);
return OK;
}
Commit Message: Merge branch 'maint'
CWE ID: CWE-264 | int open_debug_log(void) {
int open_debug_log(void)
{
int fh;
struct stat st;
/* don't do anything if we're not actually running... */
if(verify_config || test_scheduling == TRUE)
return OK;
/* don't do anything if we're not debugging */
if(debug_level == DEBUGL_NONE)
return OK;
if ((fh = open(debug_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1)
return ERROR;
if((debug_file_fp = fdopen(fh, "a+")) == NULL)
return ERROR;
if ((fstat(fh, &st)) == -1) {
debug_file_fp = NULL;
close(fh);
return ERROR;
}
if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) {
debug_file_fp = NULL;
close(fh);
return ERROR;
}
(void)fcntl(fh, F_SETFD, FD_CLOEXEC);
return OK;
}
| 166,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int rds_rdma_extra_size(struct rds_rdma_args *args)
{
struct rds_iovec vec;
struct rds_iovec __user *local_vec;
int tot_pages = 0;
unsigned int nr_pages;
unsigned int i;
local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;
/* figure out the number of pages in the vector */
for (i = 0; i < args->nr_local; i++) {
if (copy_from_user(&vec, &local_vec[i],
sizeof(struct rds_iovec)))
return -EFAULT;
nr_pages = rds_pages_in_vec(&vec);
if (nr_pages == 0)
return -EINVAL;
tot_pages += nr_pages;
/*
* nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,
* so tot_pages cannot overflow without first going negative.
*/
if (tot_pages < 0)
return -EINVAL;
}
return tot_pages * sizeof(struct scatterlist);
}
Commit Message: RDS: Heap OOB write in rds_message_alloc_sgs()
When args->nr_local is 0, nr_pages gets also 0 due some size
calculation via rds_rm_size(), which is later used to allocate
pages for DMA, this bug produces a heap Out-Of-Bound write access
to a specific memory region.
Signed-off-by: Mohamed Ghannam <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-787 | int rds_rdma_extra_size(struct rds_rdma_args *args)
{
struct rds_iovec vec;
struct rds_iovec __user *local_vec;
int tot_pages = 0;
unsigned int nr_pages;
unsigned int i;
local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr;
if (args->nr_local == 0)
return -EINVAL;
/* figure out the number of pages in the vector */
for (i = 0; i < args->nr_local; i++) {
if (copy_from_user(&vec, &local_vec[i],
sizeof(struct rds_iovec)))
return -EFAULT;
nr_pages = rds_pages_in_vec(&vec);
if (nr_pages == 0)
return -EINVAL;
tot_pages += nr_pages;
/*
* nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1,
* so tot_pages cannot overflow without first going negative.
*/
if (tot_pages < 0)
return -EINVAL;
}
return tot_pages * sizeof(struct scatterlist);
}
| 169,354 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ne2000_buffer_full(NE2000State *s)
{
int avail, index, boundary;
index = s->curpag << 8;
boundary = s->boundary << 8;
if (index < boundary)
return 1;
return 0;
}
Commit Message:
CWE ID: CWE-20 | static int ne2000_buffer_full(NE2000State *s)
{
int avail, index, boundary;
if (s->stop <= s->start) {
return 1;
}
index = s->curpag << 8;
boundary = s->boundary << 8;
if (index < boundary)
return 1;
return 0;
}
| 165,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
{
jas_matrix_t *y;
int i;
int j;
y = jas_matrix_create(x->numrows_, x->numcols_);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | jas_matrix_t *jas_matrix_copy(jas_matrix_t *x)
{
jas_matrix_t *y;
jas_matind_t i;
jas_matind_t j;
y = jas_matrix_create(x->numrows_, x->numcols_);
for (i = 0; i < x->numrows_; ++i) {
for (j = 0; j < x->numcols_; ++j) {
*jas_matrix_getref(y, i, j) = jas_matrix_get(x, i, j);
}
}
return y;
}
| 168,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Block* BlockGroup::GetBlock() const
{
return &m_block;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Block* BlockGroup::GetBlock() const
| 174,286 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t GraphicBuffer::unflatten(
void const*& buffer, size_t& size, int const*& fds, size_t& count) {
if (size < 8*sizeof(int)) return NO_MEMORY;
int const* buf = static_cast<int const*>(buffer);
if (buf[0] != 'GBFR') return BAD_TYPE;
const size_t numFds = buf[8];
const size_t numInts = buf[9];
const size_t sizeNeeded = (10 + numInts) * sizeof(int);
if (size < sizeNeeded) return NO_MEMORY;
size_t fdCountNeeded = 0;
if (count < fdCountNeeded) return NO_MEMORY;
if (handle) {
free_handle();
}
if (numFds || numInts) {
width = buf[1];
height = buf[2];
stride = buf[3];
format = buf[4];
usage = buf[5];
native_handle* h = native_handle_create(numFds, numInts);
memcpy(h->data, fds, numFds*sizeof(int));
memcpy(h->data + numFds, &buf[10], numInts*sizeof(int));
handle = h;
} else {
width = height = stride = format = usage = 0;
handle = NULL;
}
mId = static_cast<uint64_t>(buf[6]) << 32;
mId |= static_cast<uint32_t>(buf[7]);
mOwner = ownHandle;
if (handle != 0) {
status_t err = mBufferMapper.registerBuffer(handle);
if (err != NO_ERROR) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: registerBuffer failed: %s (%d)",
strerror(-err), err);
return err;
}
}
buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded);
size -= sizeNeeded;
fds += numFds;
count -= numFds;
return NO_ERROR;
}
Commit Message: Fix for corruption when numFds or numInts is too large.
Bug: 18076253
Change-Id: I4c5935440013fc755e1d123049290383f4659fb6
(cherry picked from commit dfd06b89a4b77fc75eb85a3c1c700da3621c0118)
CWE ID: CWE-189 | status_t GraphicBuffer::unflatten(
void const*& buffer, size_t& size, int const*& fds, size_t& count) {
if (size < 8*sizeof(int)) return NO_MEMORY;
int const* buf = static_cast<int const*>(buffer);
if (buf[0] != 'GBFR') return BAD_TYPE;
const size_t numFds = buf[8];
const size_t numInts = buf[9];
const size_t maxNumber = UINT_MAX / sizeof(int);
if (numFds >= maxNumber || numInts >= (maxNumber - 10)) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: numFds or numInts is too large: %d, %d",
numFds, numInts);
return BAD_VALUE;
}
const size_t sizeNeeded = (10 + numInts) * sizeof(int);
if (size < sizeNeeded) return NO_MEMORY;
size_t fdCountNeeded = numFds;
if (count < fdCountNeeded) return NO_MEMORY;
if (handle) {
free_handle();
}
if (numFds || numInts) {
width = buf[1];
height = buf[2];
stride = buf[3];
format = buf[4];
usage = buf[5];
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: native_handle_create failed");
return NO_MEMORY;
}
memcpy(h->data, fds, numFds*sizeof(int));
memcpy(h->data + numFds, &buf[10], numInts*sizeof(int));
handle = h;
} else {
width = height = stride = format = usage = 0;
handle = NULL;
}
mId = static_cast<uint64_t>(buf[6]) << 32;
mId |= static_cast<uint32_t>(buf[7]);
mOwner = ownHandle;
if (handle != 0) {
status_t err = mBufferMapper.registerBuffer(handle);
if (err != NO_ERROR) {
width = height = stride = format = usage = 0;
handle = NULL;
ALOGE("unflatten: registerBuffer failed: %s (%d)",
strerror(-err), err);
return err;
}
}
buffer = reinterpret_cast<void const*>(static_cast<int const*>(buffer) + sizeNeeded);
size -= sizeNeeded;
fds += numFds;
count -= numFds;
return NO_ERROR;
}
| 173,374 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionIntMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = jsNumber(impl->intMethodWithArgs(intArg, strArg, objArg));
return JSValue::encode(result);
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionIntMethodWithArgs(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestObj::s_info))
return throwVMTypeError(exec);
JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info);
TestObj* impl = static_cast<TestObj*>(castedThis->impl());
if (exec->argumentCount() < 3)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
int intArg(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toInt32(exec));
if (exec->hadException())
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 2, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = jsNumber(impl->intMethodWithArgs(intArg, strArg, objArg));
return JSValue::encode(result);
}
| 170,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SendTabToSelfInfoBarDelegate::OpenTab() {
NOTIMPLEMENTED();
}
Commit Message: [SendTabToSelf] Added logic to display an infobar for the feature.
This CL is one of many to come. It covers:
* Creation of the infobar from the SendTabToSelfInfoBarController
* Plumbed the call to create the infobar to the native code.
* Open the link when user taps on the link
In follow-up CLs, the following will be done:
* Instantiate the InfobarController in the ChromeActivity
* Listen for Model changes in the Controller
Bug: 949233,963193
Change-Id: I5df1359debb5f0f35c32c2df3b691bf9129cdeb8
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1604406
Reviewed-by: Tommy Nyquist <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Mikel Astiz <[email protected]>
Reviewed-by: sebsg <[email protected]>
Reviewed-by: Jeffrey Cohen <[email protected]>
Reviewed-by: Matthew Jones <[email protected]>
Commit-Queue: Tanya Gupta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660854}
CWE ID: CWE-190 | void SendTabToSelfInfoBarDelegate::OpenTab() {
content::OpenURLParams open_url_params(
entry_->GetURL(), content::Referrer(),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui::PageTransition::PAGE_TRANSITION_LINK,
false /* is_renderer_initiated */);
web_contents_->OpenURL(open_url_params);
// TODO(crbug.com/944602): Update the model to reflect that an infobar is
// shown.
}
| 172,541 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ip_forward(struct sk_buff *skb)
{
u32 mtu;
struct iphdr *iph; /* Our header */
struct rtable *rt; /* Route we use */
struct ip_options *opt = &(IPCB(skb)->opt);
/* that should never happen */
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))
goto drop;
if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))
return NET_RX_SUCCESS;
skb_forward_csum(skb);
/*
* According to the RFC, we must first decrease the TTL field. If
* that reaches zero, we must reply an ICMP control message telling
* that the packet's lifetime expired.
*/
if (ip_hdr(skb)->ttl <= 1)
goto too_many_hops;
if (!xfrm4_route_forward(skb))
goto drop;
rt = skb_rtable(skb);
if (opt->is_strictroute && rt->rt_uses_gateway)
goto sr_failed;
IPCB(skb)->flags |= IPSKB_FORWARDED;
mtu = ip_dst_mtu_maybe_forward(&rt->dst, true);
if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {
IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
goto drop;
}
/* We are about to mangle packet. Copy it! */
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))
goto drop;
iph = ip_hdr(skb);
/* Decrease ttl after skb cow done */
ip_decrease_ttl(iph);
/*
* We now generate an ICMP HOST REDIRECT giving the route
* we calculated.
*/
if (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb))
ip_rt_send_redirect(skb);
skb->priority = rt_tos2priority(iph->tos);
return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,
rt->dst.dev, ip_forward_finish);
sr_failed:
/*
* Strict routing permits no gatewaying
*/
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);
goto drop;
too_many_hops:
/* Tell the sender its packet died... */
IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);
icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
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 | int ip_forward(struct sk_buff *skb)
{
u32 mtu;
struct iphdr *iph; /* Our header */
struct rtable *rt; /* Route we use */
struct ip_options *opt = &(IPCB(skb)->opt);
/* that should never happen */
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))
goto drop;
if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))
return NET_RX_SUCCESS;
skb_forward_csum(skb);
/*
* According to the RFC, we must first decrease the TTL field. If
* that reaches zero, we must reply an ICMP control message telling
* that the packet's lifetime expired.
*/
if (ip_hdr(skb)->ttl <= 1)
goto too_many_hops;
if (!xfrm4_route_forward(skb))
goto drop;
rt = skb_rtable(skb);
if (opt->is_strictroute && rt->rt_uses_gateway)
goto sr_failed;
IPCB(skb)->flags |= IPSKB_FORWARDED;
mtu = ip_dst_mtu_maybe_forward(&rt->dst, true);
if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {
IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
goto drop;
}
/* We are about to mangle packet. Copy it! */
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))
goto drop;
iph = ip_hdr(skb);
/* Decrease ttl after skb cow done */
ip_decrease_ttl(iph);
/*
* We now generate an ICMP HOST REDIRECT giving the route
* we calculated.
*/
if (IPCB(skb)->flags & IPSKB_DOREDIRECT && !opt->srr &&
!skb_sec_path(skb))
ip_rt_send_redirect(skb);
skb->priority = rt_tos2priority(iph->tos);
return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,
rt->dst.dev, ip_forward_finish);
sr_failed:
/*
* Strict routing permits no gatewaying
*/
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);
goto drop;
too_many_hops:
/* Tell the sender its packet died... */
IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);
icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
| 166,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateFloatArray( double *numbers, int count )
{
int i;
cJSON *n = 0, *p = 0, *a = cJSON_CreateArray();
for ( i = 0; a && i < count; ++i ) {
n = cJSON_CreateFloat( numbers[i] );
if ( ! i )
a->child = n;
else
suffix_object( p, n );
p = n;
}
return a;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateFloatArray( double *numbers, int count )
| 167,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string SanitizeRemoteBase(const std::string& value) {
GURL url(value);
std::string path = url.path();
std::vector<std::string> parts = base::SplitString(
path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
std::string revision = parts.size() > 2 ? parts[2] : "";
revision = SanitizeRevision(revision);
path = base::StringPrintf("/%s/%s/", kRemoteFrontendPath, revision.c_str());
return SanitizeFrontendURL(url, url::kHttpsScheme,
kRemoteFrontendDomain, path, false).spec();
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | std::string SanitizeRemoteBase(const std::string& value) {
| 172,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < maxh; ++i)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < maxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc422_to_rgb() */
Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745)
42x Images with an odd x0/y0 lead to subsampled component starting at the
2nd column/line.
That is offset = comp->dx * comp->x0 - image->x0 = 1
Fix #726
CWE ID: CWE-125 | static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, offx, loopmaxw;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if(r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
for(i=0U; i < maxh; ++i)
{
size_t j;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
for(j=0U; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < loopmaxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc422_to_rgb() */
| 168,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void NavigationRequest::OnStartChecksComplete(
NavigationThrottle::ThrottleCheckResult result) {
DCHECK(result.action() != NavigationThrottle::DEFER);
DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE);
if (on_start_checks_complete_closure_)
on_start_checks_complete_closure_.Run();
if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE ||
result.action() == NavigationThrottle::CANCEL ||
result.action() == NavigationThrottle::BLOCK_REQUEST ||
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
#if DCHECK_IS_ON()
if (result.action() == NavigationThrottle::BLOCK_REQUEST) {
DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT ||
result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR);
}
else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) {
DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED);
}
#endif
bool collapse_frame =
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(
&NavigationRequest::OnRequestFailedInternal,
weak_factory_.GetWeakPtr(),
network::URLLoaderCompletionStatus(result.net_error_code()),
true /* skip_throttles */, result.error_page_content(),
collapse_frame));
return;
}
DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_);
RenderFrameHostImpl* navigating_frame_host =
associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE
? frame_tree_node_->render_manager()->speculative_frame_host()
: frame_tree_node_->current_frame_host();
DCHECK(navigating_frame_host);
navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess());
BrowserContext* browser_context =
frame_tree_node_->navigator()->GetController()->GetBrowserContext();
StoragePartition* partition = BrowserContext::GetStoragePartition(
browser_context, navigating_frame_host->GetSiteInstance());
DCHECK(partition);
DCHECK(!loader_);
bool can_create_service_worker =
(frame_tree_node_->pending_frame_policy().sandbox_flags &
blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin;
request_params_.should_create_service_worker = can_create_service_worker;
if (can_create_service_worker) {
ServiceWorkerContextWrapper* service_worker_context =
static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
navigation_handle_->InitServiceWorkerHandle(service_worker_context);
}
if (IsSchemeSupportedForAppCache(common_params_.url)) {
if (navigating_frame_host->GetRenderViewHost()
->GetWebkitPreferences()
.application_cache_enabled) {
navigation_handle_->InitAppCacheHandle(
static_cast<ChromeAppCacheService*>(partition->GetAppCacheService()));
}
}
request_params_.navigation_timing.fetch_start = base::TimeTicks::Now();
GURL base_url;
#if defined(OS_ANDROID)
NavigationEntry* last_committed_entry =
frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry();
if (last_committed_entry)
base_url = last_committed_entry->GetBaseURLForDataURL();
#endif
const GURL& top_document_url =
!base_url.is_empty()
? base_url
: frame_tree_node_->frame_tree()->root()->current_url();
const FrameTreeNode* current = frame_tree_node_->parent();
bool ancestors_are_same_site = true;
while (current && ancestors_are_same_site) {
if (!net::registry_controlled_domains::SameDomainOrHost(
top_document_url, current->current_url(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
ancestors_are_same_site = false;
}
current = current->parent();
}
const GURL& site_for_cookies =
ancestors_are_same_site
? (frame_tree_node_->IsMainFrame() ? common_params_.url
: top_document_url)
: GURL::EmptyGURL();
bool parent_is_main_frame = !frame_tree_node_->parent()
? false
: frame_tree_node_->parent()->IsMainFrame();
std::unique_ptr<NavigationUIData> navigation_ui_data;
if (navigation_handle_->GetNavigationUIData())
navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone();
bool is_for_guests_only =
navigation_handle_->GetStartingSiteInstance()->GetSiteURL().
SchemeIs(kGuestScheme);
bool report_raw_headers = false;
RenderFrameDevToolsAgentHost::ApplyOverrides(
frame_tree_node_, begin_params_.get(), &report_raw_headers);
RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this);
loader_ = NavigationURLLoader::Create(
browser_context->GetResourceContext(), partition,
std::make_unique<NavigationRequestInfo>(
common_params_, begin_params_.Clone(), site_for_cookies,
frame_tree_node_->IsMainFrame(), parent_is_main_frame,
IsSecureFrame(frame_tree_node_->parent()),
frame_tree_node_->frame_tree_node_id(), is_for_guests_only,
report_raw_headers,
navigating_frame_host->GetVisibilityState() ==
blink::mojom::PageVisibilityState::kPrerender,
upgrade_if_insecure_,
blob_url_loader_factory_ ? blob_url_loader_factory_->Clone()
: nullptr,
devtools_navigation_token(),
frame_tree_node_->devtools_frame_token()),
std::move(navigation_ui_data),
navigation_handle_->service_worker_handle(),
navigation_handle_->appcache_handle(), this);
}
Commit Message: Use an opaque URL rather than an empty URL for request's site for cookies.
Apparently this makes a big difference to the cookie settings backend.
Bug: 881715
Change-Id: Id87fa0c6a858bae6a3f8fff4d6af3f974b00d5e4
Reviewed-on: https://chromium-review.googlesource.com/1212846
Commit-Queue: Mike West <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#589512}
CWE ID: CWE-20 | void NavigationRequest::OnStartChecksComplete(
NavigationThrottle::ThrottleCheckResult result) {
DCHECK(result.action() != NavigationThrottle::DEFER);
DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE);
if (on_start_checks_complete_closure_)
on_start_checks_complete_closure_.Run();
if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE ||
result.action() == NavigationThrottle::CANCEL ||
result.action() == NavigationThrottle::BLOCK_REQUEST ||
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) {
#if DCHECK_IS_ON()
if (result.action() == NavigationThrottle::BLOCK_REQUEST) {
DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT ||
result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR);
}
else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) {
DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED);
}
#endif
bool collapse_frame =
result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::BindOnce(
&NavigationRequest::OnRequestFailedInternal,
weak_factory_.GetWeakPtr(),
network::URLLoaderCompletionStatus(result.net_error_code()),
true /* skip_throttles */, result.error_page_content(),
collapse_frame));
return;
}
DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_);
RenderFrameHostImpl* navigating_frame_host =
associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE
? frame_tree_node_->render_manager()->speculative_frame_host()
: frame_tree_node_->current_frame_host();
DCHECK(navigating_frame_host);
navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess());
BrowserContext* browser_context =
frame_tree_node_->navigator()->GetController()->GetBrowserContext();
StoragePartition* partition = BrowserContext::GetStoragePartition(
browser_context, navigating_frame_host->GetSiteInstance());
DCHECK(partition);
DCHECK(!loader_);
bool can_create_service_worker =
(frame_tree_node_->pending_frame_policy().sandbox_flags &
blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin;
request_params_.should_create_service_worker = can_create_service_worker;
if (can_create_service_worker) {
ServiceWorkerContextWrapper* service_worker_context =
static_cast<ServiceWorkerContextWrapper*>(
partition->GetServiceWorkerContext());
navigation_handle_->InitServiceWorkerHandle(service_worker_context);
}
if (IsSchemeSupportedForAppCache(common_params_.url)) {
if (navigating_frame_host->GetRenderViewHost()
->GetWebkitPreferences()
.application_cache_enabled) {
navigation_handle_->InitAppCacheHandle(
static_cast<ChromeAppCacheService*>(partition->GetAppCacheService()));
}
}
request_params_.navigation_timing.fetch_start = base::TimeTicks::Now();
GURL base_url;
#if defined(OS_ANDROID)
NavigationEntry* last_committed_entry =
frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry();
if (last_committed_entry)
base_url = last_committed_entry->GetBaseURLForDataURL();
#endif
const GURL& top_document_url =
!base_url.is_empty()
? base_url
: frame_tree_node_->frame_tree()->root()->current_url();
// not, the |site_for_cookies| is set to an opaque URL.
const FrameTreeNode* current = frame_tree_node_->parent();
bool ancestors_are_same_site = true;
while (current && ancestors_are_same_site) {
if (!net::registry_controlled_domains::SameDomainOrHost(
top_document_url, current->current_url(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) {
ancestors_are_same_site = false;
}
current = current->parent();
}
const GURL& site_for_cookies =
(ancestors_are_same_site || !base_url.is_empty())
? (frame_tree_node_->IsMainFrame() ? common_params_.url
: top_document_url)
: GURL("data:,");
bool parent_is_main_frame = !frame_tree_node_->parent()
? false
: frame_tree_node_->parent()->IsMainFrame();
std::unique_ptr<NavigationUIData> navigation_ui_data;
if (navigation_handle_->GetNavigationUIData())
navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone();
bool is_for_guests_only =
navigation_handle_->GetStartingSiteInstance()->GetSiteURL().
SchemeIs(kGuestScheme);
bool report_raw_headers = false;
RenderFrameDevToolsAgentHost::ApplyOverrides(
frame_tree_node_, begin_params_.get(), &report_raw_headers);
RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this);
loader_ = NavigationURLLoader::Create(
browser_context->GetResourceContext(), partition,
std::make_unique<NavigationRequestInfo>(
common_params_, begin_params_.Clone(), site_for_cookies,
frame_tree_node_->IsMainFrame(), parent_is_main_frame,
IsSecureFrame(frame_tree_node_->parent()),
frame_tree_node_->frame_tree_node_id(), is_for_guests_only,
report_raw_headers,
navigating_frame_host->GetVisibilityState() ==
blink::mojom::PageVisibilityState::kPrerender,
upgrade_if_insecure_,
blob_url_loader_factory_ ? blob_url_loader_factory_->Clone()
: nullptr,
devtools_navigation_token(),
frame_tree_node_->devtools_frame_token()),
std::move(navigation_ui_data),
navigation_handle_->service_worker_handle(),
navigation_handle_->appcache_handle(), this);
}
| 172,279 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
ALOGV("setNextPlayer");
Mutex::Autolock l(mLock);
sp<Client> c = static_cast<Client*>(player.get());
mNextClient = c;
if (c != NULL) {
if (mAudioOutput != NULL) {
mAudioOutput->setNextOutput(c->mAudioOutput);
} else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
ALOGE("no current audio output");
}
if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
mPlayer->setNextPlayer(mNextClient->getPlayer());
}
}
return OK;
}
Commit Message: MediaPlayerService: avoid invalid static cast
Bug: 30204103
Change-Id: Ie0dd3568a375f1e9fed8615ad3d85184bcc99028
(cherry picked from commit ee0a0e39acdcf8f97e0d6945c31ff36a06a36e9d)
CWE ID: CWE-264 | status_t MediaPlayerService::Client::setNextPlayer(const sp<IMediaPlayer>& player) {
ALOGV("setNextPlayer");
Mutex::Autolock l(mLock);
sp<Client> c = static_cast<Client*>(player.get());
if (!mService->hasClient(c)) {
return BAD_VALUE;
}
mNextClient = c;
if (c != NULL) {
if (mAudioOutput != NULL) {
mAudioOutput->setNextOutput(c->mAudioOutput);
} else if ((mPlayer != NULL) && !mPlayer->hardwareOutput()) {
ALOGE("no current audio output");
}
if ((mPlayer != NULL) && (mNextClient->getPlayer() != NULL)) {
mPlayer->setNextPlayer(mNextClient->getPlayer());
}
}
return OK;
}
| 173,398 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Adding Error Check for f_code Parameters
In MPEG1, the valid range for the forward and backward f_code parameters
is [1, 7]. Adding a check to enforce this. Without the check, the value
could be 0. We read (f_code - 1) bits from the stream and reading a
negative number of bits from the stream is undefined.
Bug: 64550583
Test: monitored temp ALOGD() output
Change-Id: Ia452cd43a28e9d566401f515947164635361782f
(cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689)
CWE ID: CWE-200 | IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
/* Flush temporal reference */
impeg2d_bit_stream_get(ps_stream,10);
/* Picture type */
ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3);
if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC))
{
impeg2d_next_code(ps_dec, PICTURE_START_CODE);
return IMPEG2D_INVALID_PIC_TYPE;
}
/* Flush vbv_delay */
impeg2d_bit_stream_get(ps_stream,16);
if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->e_pic_type == B_PIC)
{
ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream);
ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3);
}
if(ps_dec->u2_is_mpeg2 == 0)
{
if (ps_dec->u2_forw_f_code < 1 || ps_dec->u2_forw_f_code > 7 ||
ps_dec->u2_back_f_code < 1 || ps_dec->u2_back_f_code > 7)
{
return IMPEG2D_UNKNOWN_ERROR;
}
ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code;
ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code;
}
/*-----------------------------------------------------------------------*/
/* Flush the extra bit value */
/* */
/* while(impeg2d_bit_stream_nxt() == '1') */
/* { */
/* extra_bit_picture 1 */
/* extra_information_picture 8 */
/* } */
/* extra_bit_picture 1 */
/*-----------------------------------------------------------------------*/
while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 &&
ps_stream->u4_offset < ps_stream->u4_max_offset)
{
impeg2d_bit_stream_get(ps_stream,9);
}
impeg2d_bit_stream_get_bit(ps_stream);
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
| 174,103 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"s256");
}
Commit Message:
CWE ID: CWE-20 | size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"*s256");
}
| 164,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || !image->hasImage() || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void PageSerializer::addImageToResources(ImageResource* image, RenderObject* imageRenderer, const KURL& url)
{
if (!shouldAddURL(url))
return;
if (!image || image->image() == Image::nullImage())
return;
RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
if (!data)
data = image->image()->data();
addToResources(image, data, url);
}
| 171,564 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DatabaseMessageFilter::OnHandleSqliteError(
const string16& origin_identifier,
const string16& database_name,
int error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
db_tracker_->HandleSqliteError(origin_identifier, database_name, error);
}
Commit Message: WebDatabase: check path traversal in origin_identifier
BUG=172264
Review URL: https://chromiumcodereview.appspot.com/12212091
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-22 | void DatabaseMessageFilter::OnHandleSqliteError(
const string16& origin_identifier,
const string16& database_name,
int error) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) {
RecordAction(UserMetricsAction("BadMessageTerminate_DBMF"));
BadMessageReceived();
return;
}
db_tracker_->HandleSqliteError(origin_identifier, database_name, error);
}
| 171,478 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data,
krb5_kvno mkvno) {
struct berval **ret = NULL;
int currkvno;
int num_versions = 1;
int i, j, last;
krb5_error_code err = 0;
krb5_key_data *key_data;
if (n_key_data <= 0)
return NULL;
/* Make a shallow copy of the key data so we can alter it. */
key_data = k5calloc(n_key_data, sizeof(*key_data), &err);
if (key_data_in == NULL)
goto cleanup;
memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data));
/* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt
* field. For compatibility, always encode a salt field. */
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_ver == 1) {
key_data[i].key_data_ver = 2;
key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL;
key_data[i].key_data_length[1] = 0;
key_data[i].key_data_contents[1] = NULL;
}
}
/* Find the number of key versions */
for (i = 0; i < n_key_data - 1; i++)
if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)
num_versions++;
ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *));
if (ret == NULL) {
err = ENOMEM;
goto cleanup;
}
for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) {
krb5_data *code;
if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {
ret[j] = k5alloc(sizeof(struct berval), &err);
if (ret[j] == NULL)
goto cleanup;
err = asn1_encode_sequence_of_keys(key_data + last,
(krb5_int16)i - last + 1,
mkvno, &code);
if (err)
goto cleanup;
/*CHECK_NULL(ret[j]); */
ret[j]->bv_len = code->length;
ret[j]->bv_val = code->data;
free(code);
j++;
last = i + 1;
currkvno = key_data[i].key_data_kvno;
}
}
ret[num_versions] = NULL;
cleanup:
free(key_data);
if (err != 0) {
if (ret != NULL) {
for (i = 0; i <= num_versions; i++)
if (ret[i] != NULL)
free (ret[i]);
free (ret);
ret = NULL;
}
}
return ret;
}
Commit Message: Fix LDAP key data segmentation [CVE-2014-4345]
For principal entries having keys with multiple kvnos (due to use of
-keepold), the LDAP KDB module makes an attempt to store all the keys
having the same kvno into a single krbPrincipalKey attribute value.
There is a fencepost error in the loop, causing currkvno to be set to
the just-processed value instead of the next kvno. As a result, the
second and all following groups of multiple keys by kvno are each
stored in two krbPrincipalKey attribute values. Fix the loop to use
the correct kvno value.
CVE-2014-4345:
In MIT krb5, when kadmind is configured to use LDAP for the KDC
database, an authenticated remote attacker can cause it to perform an
out-of-bounds write (buffer overrun) by performing multiple cpw
-keepold operations. An off-by-one error while copying key
information to the new database entry results in keys sharing a common
kvno being written to different array buckets, in an array whose size
is determined by the number of kvnos present. After sufficient
iterations, the extra writes extend past the end of the
(NULL-terminated) array. The NULL terminator is always written after
the end of the loop, so no out-of-bounds data is read, it is only
written.
Historically, it has been possible to convert an out-of-bounds write
into remote code execution in some cases, though the necessary
exploits must be tailored to the individual application and are
usually quite complicated. Depending on the allocated length of the
array, an out-of-bounds write may also cause a segmentation fault
and/or application crash.
CVSSv2 Vector: AV:N/AC:M/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C
[[email protected]: clarified commit message]
[[email protected]: CVE summary, CVSSv2 vector]
(cherry picked from commit 81c332e29f10887c6b9deb065f81ba259f4c7e03)
ticket: 7980
version_fixed: 1.12.2
status: resolved
CWE ID: CWE-189 | krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data,
krb5_kvno mkvno) {
struct berval **ret = NULL;
int currkvno;
int num_versions = 1;
int i, j, last;
krb5_error_code err = 0;
krb5_key_data *key_data;
if (n_key_data <= 0)
return NULL;
/* Make a shallow copy of the key data so we can alter it. */
key_data = k5calloc(n_key_data, sizeof(*key_data), &err);
if (key_data_in == NULL)
goto cleanup;
memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data));
/* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt
* field. For compatibility, always encode a salt field. */
for (i = 0; i < n_key_data; i++) {
if (key_data[i].key_data_ver == 1) {
key_data[i].key_data_ver = 2;
key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL;
key_data[i].key_data_length[1] = 0;
key_data[i].key_data_contents[1] = NULL;
}
}
/* Find the number of key versions */
for (i = 0; i < n_key_data - 1; i++)
if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno)
num_versions++;
ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *));
if (ret == NULL) {
err = ENOMEM;
goto cleanup;
}
for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) {
krb5_data *code;
if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) {
ret[j] = k5alloc(sizeof(struct berval), &err);
if (ret[j] == NULL)
goto cleanup;
err = asn1_encode_sequence_of_keys(key_data + last,
(krb5_int16)i - last + 1,
mkvno, &code);
if (err)
goto cleanup;
/*CHECK_NULL(ret[j]); */
ret[j]->bv_len = code->length;
ret[j]->bv_val = code->data;
free(code);
j++;
last = i + 1;
if (i < n_key_data - 1)
currkvno = key_data[i + 1].key_data_kvno;
}
}
ret[num_versions] = NULL;
cleanup:
free(key_data);
if (err != 0) {
if (ret != NULL) {
for (i = 0; i <= num_versions; i++)
if (ret[i] != NULL)
free (ret[i]);
free (ret);
ret = NULL;
}
}
return ret;
}
| 166,309 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_compat_entry_size_and_hooks(struct compat_arpt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_arpt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_arpt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct arpt_entry *)e);
if (ret)
return ret;
off = sizeof(struct arpt_entry) - sizeof(struct compat_arpt_entry);
entry_offset = (void *)e - (void *)base;
t = compat_arpt_get_target(e);
target = xt_request_find_target(NFPROTO_ARP, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto out;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(NFPROTO_ARP, entry_offset, off);
if (ret)
goto release_target;
/* Check hooks & underflows */
for (h = 0; h < NF_ARP_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
release_target:
module_put(t->u.kernel.target->me);
out:
return ret;
}
| 167,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
DCHECK(thread_checker_.CalledOnValidThread());
return true;
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | bool DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
| 172,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125 | METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
int cmaplen = source->cmap_length;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
| 169,836 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsAndroid::OpenURL(JNIEnv* env,
jobject obj,
jstring url,
jboolean user_gesture,
jboolean is_renderer_initiated) {
GURL gurl(base::android::ConvertJavaStringToUTF8(env, url));
OpenURLParams open_params(gurl,
Referrer(),
CURRENT_TAB,
ui::PAGE_TRANSITION_LINK,
is_renderer_initiated);
open_params.user_gesture = user_gesture;
web_contents_->OpenURL(open_params);
}
Commit Message: Revert "Load web contents after tab is created."
This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d.
BUG=432562
[email protected],[email protected],[email protected]
Review URL: https://codereview.chromium.org/894003005
Cr-Commit-Position: refs/heads/master@{#314469}
CWE ID: CWE-399 | void WebContentsAndroid::OpenURL(JNIEnv* env,
| 171,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Cues::LoadCuePoint() const {
const long long stop = m_start + m_size;
if (m_pos >= stop)
return false; // nothing else to do
Init();
IMkvReader* const pReader = m_pSegment->m_pReader;
while (m_pos < stop) {
const long long idpos = m_pos;
long len;
const long long id = ReadUInt(pReader, m_pos, len);
assert(id >= 0); // TODO
assert((m_pos + len) <= stop);
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
assert(size >= 0);
assert((m_pos + len) <= stop);
m_pos += len; // consume Size field
assert((m_pos + size) <= stop);
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
assert(m_pos <= stop);
continue;
}
assert(m_preload_count > 0);
CuePoint* const pCP = m_cue_points[m_count];
assert(pCP);
assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos));
if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos))
return false;
pCP->Load(pReader);
++m_count;
--m_preload_count;
m_pos += size; // consume payload
assert(m_pos <= stop);
return true; // yes, we loaded a cue point
}
}
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 | bool Cues::LoadCuePoint() const {
const long long stop = m_start + m_size;
if (m_pos >= stop)
return false; // nothing else to do
if (!Init()) {
m_pos = stop;
return false;
}
IMkvReader* const pReader = m_pSegment->m_pReader;
while (m_pos < stop) {
const long long idpos = m_pos;
long len;
const long long id = ReadID(pReader, m_pos, len);
if (id < 0 || (m_pos + len) > stop)
return false;
m_pos += len; // consume ID
const long long size = ReadUInt(pReader, m_pos, len);
if (size < 0 || (m_pos + len) > stop)
return false;
m_pos += len; // consume Size field
if ((m_pos + size) > stop)
return false;
if (id != 0x3B) { // CuePoint ID
m_pos += size; // consume payload
if (m_pos > stop)
return false;
continue;
}
if (m_preload_count < 1)
return false;
CuePoint* const pCP = m_cue_points[m_count];
if (!pCP || (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)))
return false;
if (!pCP->Load(pReader)) {
m_pos = stop;
return false;
}
++m_count;
--m_preload_count;
m_pos += size; // consume payload
if (m_pos > stop)
return false;
return true; // yes, we loaded a cue point
}
}
| 173,831 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_CreateFalse( void )
{
cJSON *item = cJSON_New_Item();
if ( item )
item->type = cJSON_False;
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | cJSON *cJSON_CreateFalse( void )
| 167,271 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UserSelectionScreen::FillMultiProfileUserPrefs(
user_manager::User* user,
base::DictionaryValue* user_dict,
bool is_signin_to_add) {
if (!is_signin_to_add) {
user_dict->SetBoolean(kKeyMultiProfilesAllowed, true);
return;
}
bool is_user_allowed;
ash::mojom::MultiProfileUserBehavior policy;
GetMultiProfilePolicy(user, &is_user_allowed, &policy);
user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed);
user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy));
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID: | void UserSelectionScreen::FillMultiProfileUserPrefs(
const user_manager::User* user,
base::DictionaryValue* user_dict,
bool is_signin_to_add) {
if (!is_signin_to_add) {
user_dict->SetBoolean(kKeyMultiProfilesAllowed, true);
return;
}
bool is_user_allowed;
ash::mojom::MultiProfileUserBehavior policy;
GetMultiProfilePolicy(user, &is_user_allowed, &policy);
user_dict->SetBoolean(kKeyMultiProfilesAllowed, is_user_allowed);
user_dict->SetInteger(kKeyMultiProfilesPolicy, static_cast<int>(policy));
}
| 172,199 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(info ? info->InitialURL().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
Commit Message: Fix the |name| of PerformanceNavigationTiming
Previously, the |name| of a PerformanceNavigationTiming entry was the initial
URL (the request URL). After this CL, it is the response URL, so for example
a url of the form 'redirect?location=newLoc' will have 'newLoc' as the |name|.
Bug: 797465
Change-Id: Icab53ad8027d066422562c82bcf0354c264fea40
Reviewed-on: https://chromium-review.googlesource.com/996579
Reviewed-by: Yoav Weiss <[email protected]>
Commit-Queue: Nicolás Peña Moreno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548773}
CWE ID: CWE-200 | PerformanceNavigationTiming::PerformanceNavigationTiming(
LocalFrame* frame,
ResourceTimingInfo* info,
TimeTicks time_origin,
const WebVector<WebServerTimingInfo>& server_timing)
: PerformanceResourceTiming(
info ? info->FinalResponse().Url().GetString() : "",
"navigation",
time_origin,
server_timing),
ContextClient(frame),
resource_timing_info_(info) {
DCHECK(frame);
DCHECK(info);
}
| 173,225 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SoundTriggerHwService::Module::loadSoundModel(const sp<IMemory>& modelMemory,
sound_model_handle_t *handle)
{
ALOGV("loadSoundModel() handle");
if (!captureHotwordAllowed()) {
return PERMISSION_DENIED;
}
if (modelMemory == 0 || modelMemory->pointer() == NULL) {
ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()");
return BAD_VALUE;
}
struct sound_trigger_sound_model *sound_model =
(struct sound_trigger_sound_model *)modelMemory->pointer();
AutoMutex lock(mLock);
if (mModels.size() >= mDescriptor.properties.max_sound_models) {
ALOGW("loadSoundModel(): Not loading, max number of models (%d) would be exceeded",
mDescriptor.properties.max_sound_models);
return INVALID_OPERATION;
}
status_t status = mHwDevice->load_sound_model(mHwDevice, sound_model,
SoundTriggerHwService::soundModelCallback,
this, handle);
if (status != NO_ERROR) {
return status;
}
audio_session_t session;
audio_io_handle_t ioHandle;
audio_devices_t device;
status = AudioSystem::acquireSoundTriggerSession(&session, &ioHandle, &device);
if (status != NO_ERROR) {
return status;
}
sp<Model> model = new Model(*handle, session, ioHandle, device, sound_model->type);
mModels.replaceValueFor(*handle, model);
return status;
}
Commit Message: soundtrigger: add size check on sound model and recogntion data
Bug: 30148546
Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0
(cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8)
(cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd)
CWE ID: CWE-264 | status_t SoundTriggerHwService::Module::loadSoundModel(const sp<IMemory>& modelMemory,
sound_model_handle_t *handle)
{
ALOGV("loadSoundModel() handle");
if (!captureHotwordAllowed()) {
return PERMISSION_DENIED;
}
if (modelMemory == 0 || modelMemory->pointer() == NULL) {
ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()");
return BAD_VALUE;
}
struct sound_trigger_sound_model *sound_model =
(struct sound_trigger_sound_model *)modelMemory->pointer();
size_t structSize;
if (sound_model->type == SOUND_MODEL_TYPE_KEYPHRASE) {
structSize = sizeof(struct sound_trigger_phrase_sound_model);
} else {
structSize = sizeof(struct sound_trigger_sound_model);
}
if (sound_model->data_offset < structSize ||
sound_model->data_size > (UINT_MAX - sound_model->data_offset) ||
modelMemory->size() < sound_model->data_offset ||
sound_model->data_size > (modelMemory->size() - sound_model->data_offset)) {
android_errorWriteLog(0x534e4554, "30148546");
ALOGE("loadSoundModel() data_size is too big");
return BAD_VALUE;
}
AutoMutex lock(mLock);
if (mModels.size() >= mDescriptor.properties.max_sound_models) {
ALOGW("loadSoundModel(): Not loading, max number of models (%d) would be exceeded",
mDescriptor.properties.max_sound_models);
return INVALID_OPERATION;
}
status_t status = mHwDevice->load_sound_model(mHwDevice, sound_model,
SoundTriggerHwService::soundModelCallback,
this, handle);
if (status != NO_ERROR) {
return status;
}
audio_session_t session;
audio_io_handle_t ioHandle;
audio_devices_t device;
status = AudioSystem::acquireSoundTriggerSession(&session, &ioHandle, &device);
if (status != NO_ERROR) {
return status;
}
sp<Model> model = new Model(*handle, session, ioHandle, device, sound_model->type);
mModels.replaceValueFor(*handle, model);
return status;
}
| 173,399 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PageInfo::ComputeUIInputs(
const GURL& url,
security_state::SecurityLevel security_level,
const security_state::VisibleSecurityState& visible_security_state) {
#if !defined(OS_ANDROID)
DCHECK(!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme) &&
!url.SchemeIs(content::kViewSourceScheme) &&
!url.SchemeIs(content_settings::kExtensionScheme));
#endif
bool is_chrome_ui_native_scheme = false;
#if defined(OS_ANDROID)
is_chrome_ui_native_scheme = url.SchemeIs(chrome::kChromeUINativeScheme);
#endif
security_level_ = security_level;
if (url.SchemeIs(url::kAboutScheme)) {
DCHECK_EQ(url::kAboutBlankURL, url.spec());
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
site_details_message_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY);
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
site_connection_details_ = l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
UTF8ToUTF16(url.spec()));
return;
}
if (url.SchemeIs(content::kChromeUIScheme) || is_chrome_ui_native_scheme) {
site_identity_status_ = SITE_IDENTITY_STATUS_INTERNAL_PAGE;
site_details_message_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE);
site_connection_status_ = SITE_CONNECTION_STATUS_INTERNAL_PAGE;
return;
}
certificate_ = visible_security_state.certificate;
if (certificate_ &&
(!net::IsCertStatusError(visible_security_state.cert_status) ||
net::IsCertStatusMinorError(visible_security_state.cert_status))) {
if (security_level == security_state::SECURE_WITH_POLICY_INSTALLED_CERT) {
#if defined(OS_CHROMEOS)
site_identity_status_ = SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT;
site_details_message_ = l10n_util::GetStringFUTF16(
IDS_CERT_POLICY_PROVIDED_CERT_MESSAGE, UTF8ToUTF16(url.host()));
#else
DCHECK(false) << "Policy certificates exist only on ChromeOS";
#endif
} else if (net::IsCertStatusMinorError(
visible_security_state.cert_status)) {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN;
base::string16 issuer_name(
UTF8ToUTF16(certificate_->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_details_message_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name));
site_details_message_ += ASCIIToUTF16("\n\n");
if (visible_security_state.cert_status &
net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) {
site_details_message_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION);
} else if (visible_security_state.cert_status &
net::CERT_STATUS_NO_REVOCATION_MECHANISM) {
site_details_message_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM);
} else {
NOTREACHED() << "Need to specify string for this warning";
}
} else {
if (visible_security_state.cert_status & net::CERT_STATUS_IS_EV) {
site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT;
DCHECK(!certificate_->subject().organization_names.empty());
organization_name_ =
UTF8ToUTF16(certificate_->subject().organization_names[0]);
DCHECK(!certificate_->subject().locality_name.empty());
DCHECK(!certificate_->subject().country_name.empty());
site_details_message_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED,
organization_name_,
UTF8ToUTF16(certificate_->subject().country_name)));
} else {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT;
base::string16 issuer_name(
UTF8ToUTF16(certificate_->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_details_message_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name));
}
if (security_state::IsSHA1InChain(visible_security_state)) {
site_identity_status_ =
SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM;
site_details_message_ +=
UTF8ToUTF16("\n\n") +
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_DEPRECATED_SIGNATURE_ALGORITHM);
}
}
} else {
site_details_message_.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
if (!security_state::IsSchemeCryptographic(visible_security_state.url) ||
!visible_security_state.certificate) {
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
} else {
site_identity_status_ = SITE_IDENTITY_STATUS_ERROR;
}
const base::string16 bullet = UTF8ToUTF16("\n • ");
std::vector<ssl_errors::ErrorInfo> errors;
ssl_errors::ErrorInfo::GetErrorsForCertStatus(
certificate_, visible_security_state.cert_status, url, &errors);
for (size_t i = 0; i < errors.size(); ++i) {
site_details_message_ += bullet;
site_details_message_ += errors[i].short_description();
}
if (visible_security_state.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) {
site_details_message_ += ASCIIToUTF16("\n\n");
site_details_message_ +=
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
}
}
if (visible_security_state.malicious_content_status !=
security_state::MALICIOUS_CONTENT_STATUS_NONE) {
GetSafeBrowsingStatusByMaliciousContentStatus(
visible_security_state.malicious_content_status, &safe_browsing_status_,
&site_details_message_);
#if defined(FULL_SAFE_BROWSING)
bool old_show_change_pw_buttons = show_change_password_buttons_;
#endif
show_change_password_buttons_ =
(visible_security_state.malicious_content_status ==
security_state::MALICIOUS_CONTENT_STATUS_SIGN_IN_PASSWORD_REUSE ||
visible_security_state.malicious_content_status ==
security_state::
MALICIOUS_CONTENT_STATUS_ENTERPRISE_PASSWORD_REUSE);
#if defined(FULL_SAFE_BROWSING)
if (show_change_password_buttons_ && !old_show_change_pw_buttons) {
RecordPasswordReuseEvent();
}
#endif
}
site_connection_status_ = SITE_CONNECTION_STATUS_UNKNOWN;
base::string16 subject_name(GetSimpleSiteName(url));
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
if (!visible_security_state.certificate ||
!security_state::IsSchemeCryptographic(visible_security_state.url)) {
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (!visible_security_state.connection_info_initialized) {
DCHECK_NE(security_level, security_state::NONE);
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
} else {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED;
if (net::ObsoleteSSLStatus(
visible_security_state.connection_status,
visible_security_state.peer_signature_algorithm) ==
net::OBSOLETE_SSL_NONE) {
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT, subject_name));
} else {
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
}
ReportAnyInsecureContent(visible_security_state, &site_connection_status_,
&site_connection_details_);
}
uint16_t cipher_suite = net::SSLConnectionStatusToCipherSuite(
visible_security_state.connection_status);
if (visible_security_state.connection_info_initialized && cipher_suite) {
int ssl_version = net::SSLConnectionStatusToVersion(
visible_security_state.connection_status);
const char* ssl_version_str;
net::SSLVersionToString(&ssl_version_str, ssl_version);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION, ASCIIToUTF16(ssl_version_str));
const char *key_exchange, *cipher, *mac;
bool is_aead, is_tls13;
net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
&is_tls13, cipher_suite);
site_connection_details_ += ASCIIToUTF16("\n\n");
if (is_aead) {
if (is_tls13) {
key_exchange =
SSL_get_curve_name(visible_security_state.key_exchange_group);
if (!key_exchange) {
NOTREACHED();
key_exchange = "";
}
}
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS_AEAD,
ASCIIToUTF16(cipher), ASCIIToUTF16(key_exchange));
} else {
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS, ASCIIToUTF16(cipher),
ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange));
}
}
ChromeSSLHostStateDelegate* delegate =
ChromeSSLHostStateDelegateFactory::GetForProfile(profile_);
DCHECK(delegate);
show_ssl_decision_revoke_button_ =
delegate->HasAllowException(url.host()) &&
visible_security_state.malicious_content_status ==
security_state::MALICIOUS_CONTENT_STATUS_NONE;
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311 | void PageInfo::ComputeUIInputs(
const GURL& url,
security_state::SecurityLevel security_level,
const security_state::VisibleSecurityState& visible_security_state) {
#if !defined(OS_ANDROID)
DCHECK(!url.SchemeIs(content::kChromeUIScheme) &&
!url.SchemeIs(content::kChromeDevToolsScheme) &&
!url.SchemeIs(content::kViewSourceScheme) &&
!url.SchemeIs(content_settings::kExtensionScheme));
#endif
bool is_chrome_ui_native_scheme = false;
#if defined(OS_ANDROID)
is_chrome_ui_native_scheme = url.SchemeIs(chrome::kChromeUINativeScheme);
#endif
security_level_ = security_level;
if (url.SchemeIs(url::kAboutScheme)) {
DCHECK_EQ(url::kAboutBlankURL, url.spec());
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
site_identity_details_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY);
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
site_connection_details_ = l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
UTF8ToUTF16(url.spec()));
return;
}
if (url.SchemeIs(content::kChromeUIScheme) || is_chrome_ui_native_scheme) {
site_identity_status_ = SITE_IDENTITY_STATUS_INTERNAL_PAGE;
site_identity_details_ =
l10n_util::GetStringUTF16(IDS_PAGE_INFO_INTERNAL_PAGE);
site_connection_status_ = SITE_CONNECTION_STATUS_INTERNAL_PAGE;
return;
}
certificate_ = visible_security_state.certificate;
if (visible_security_state.malicious_content_status !=
security_state::MALICIOUS_CONTENT_STATUS_NONE) {
// The site has been flagged by Safe Browsing as dangerous.
GetSiteIdentityByMaliciousContentStatus(
visible_security_state.malicious_content_status, &site_identity_status_,
&site_identity_details_);
#if defined(FULL_SAFE_BROWSING)
bool old_show_change_pw_buttons = show_change_password_buttons_;
#endif
show_change_password_buttons_ =
(visible_security_state.malicious_content_status ==
security_state::MALICIOUS_CONTENT_STATUS_SIGN_IN_PASSWORD_REUSE ||
visible_security_state.malicious_content_status ==
security_state::
MALICIOUS_CONTENT_STATUS_ENTERPRISE_PASSWORD_REUSE);
#if defined(FULL_SAFE_BROWSING)
// Only record password reuse when adding the button, not on updates.
if (show_change_password_buttons_ && !old_show_change_pw_buttons) {
RecordPasswordReuseEvent();
}
#endif
} else if (certificate_ &&
(!net::IsCertStatusError(visible_security_state.cert_status) ||
net::IsCertStatusMinorError(
visible_security_state.cert_status))) {
if (security_level == security_state::SECURE_WITH_POLICY_INSTALLED_CERT) {
#if defined(OS_CHROMEOS)
site_identity_status_ = SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT;
site_identity_details_ = l10n_util::GetStringFUTF16(
IDS_CERT_POLICY_PROVIDED_CERT_MESSAGE, UTF8ToUTF16(url.host()));
#else
DCHECK(false) << "Policy certificates exist only on ChromeOS";
#endif
} else if (net::IsCertStatusMinorError(
visible_security_state.cert_status)) {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN;
base::string16 issuer_name(
UTF8ToUTF16(certificate_->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name));
site_identity_details_ += ASCIIToUTF16("\n\n");
if (visible_security_state.cert_status &
net::CERT_STATUS_UNABLE_TO_CHECK_REVOCATION) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNABLE_TO_CHECK_REVOCATION);
} else if (visible_security_state.cert_status &
net::CERT_STATUS_NO_REVOCATION_MECHANISM) {
site_identity_details_ += l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NO_REVOCATION_MECHANISM);
} else {
NOTREACHED() << "Need to specify string for this warning";
}
} else {
if (visible_security_state.cert_status & net::CERT_STATUS_IS_EV) {
site_identity_status_ = SITE_IDENTITY_STATUS_EV_CERT;
DCHECK(!certificate_->subject().organization_names.empty());
organization_name_ =
UTF8ToUTF16(certificate_->subject().organization_names[0]);
DCHECK(!certificate_->subject().locality_name.empty());
DCHECK(!certificate_->subject().country_name.empty());
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_EV_VERIFIED,
organization_name_,
UTF8ToUTF16(certificate_->subject().country_name)));
} else {
site_identity_status_ = SITE_IDENTITY_STATUS_CERT;
base::string16 issuer_name(
UTF8ToUTF16(certificate_->issuer().GetDisplayName()));
if (issuer_name.empty()) {
issuer_name.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
site_identity_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SECURE_IDENTITY_VERIFIED, issuer_name));
}
if (security_state::IsSHA1InChain(visible_security_state)) {
site_identity_status_ =
SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM;
site_identity_details_ +=
UTF8ToUTF16("\n\n") +
l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_DEPRECATED_SIGNATURE_ALGORITHM);
}
}
} else {
site_identity_details_.assign(l10n_util::GetStringUTF16(
IDS_PAGE_INFO_SECURITY_TAB_INSECURE_IDENTITY));
if (!security_state::IsSchemeCryptographic(visible_security_state.url) ||
!visible_security_state.certificate) {
site_identity_status_ = SITE_IDENTITY_STATUS_NO_CERT;
} else {
site_identity_status_ = SITE_IDENTITY_STATUS_ERROR;
}
const base::string16 bullet = UTF8ToUTF16("\n • ");
std::vector<ssl_errors::ErrorInfo> errors;
ssl_errors::ErrorInfo::GetErrorsForCertStatus(
certificate_, visible_security_state.cert_status, url, &errors);
for (size_t i = 0; i < errors.size(); ++i) {
site_identity_details_ += bullet;
site_identity_details_ += errors[i].short_description();
}
if (visible_security_state.cert_status & net::CERT_STATUS_NON_UNIQUE_NAME) {
site_identity_details_ += ASCIIToUTF16("\n\n");
site_identity_details_ +=
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_NON_UNIQUE_NAME);
}
}
site_connection_status_ = SITE_CONNECTION_STATUS_UNKNOWN;
base::string16 subject_name(GetSimpleSiteName(url));
if (subject_name.empty()) {
subject_name.assign(
l10n_util::GetStringUTF16(IDS_PAGE_INFO_SECURITY_TAB_UNKNOWN_PARTY));
}
if (!visible_security_state.certificate ||
!security_state::IsSchemeCryptographic(visible_security_state.url)) {
site_connection_status_ = SITE_CONNECTION_STATUS_UNENCRYPTED;
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_NOT_ENCRYPTED_CONNECTION_TEXT,
subject_name));
} else if (!visible_security_state.connection_info_initialized) {
DCHECK_NE(security_level, security_state::NONE);
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED_ERROR;
} else {
site_connection_status_ = SITE_CONNECTION_STATUS_ENCRYPTED;
if (net::ObsoleteSSLStatus(
visible_security_state.connection_status,
visible_security_state.peer_signature_algorithm) ==
net::OBSOLETE_SSL_NONE) {
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTED_CONNECTION_TEXT, subject_name));
} else {
site_connection_details_.assign(l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_WEAK_ENCRYPTION_CONNECTION_TEXT,
subject_name));
}
ReportAnyInsecureContent(visible_security_state, &site_connection_status_,
&site_connection_details_);
}
uint16_t cipher_suite = net::SSLConnectionStatusToCipherSuite(
visible_security_state.connection_status);
if (visible_security_state.connection_info_initialized && cipher_suite) {
int ssl_version = net::SSLConnectionStatusToVersion(
visible_security_state.connection_status);
const char* ssl_version_str;
net::SSLVersionToString(&ssl_version_str, ssl_version);
site_connection_details_ += ASCIIToUTF16("\n\n");
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_SSL_VERSION, ASCIIToUTF16(ssl_version_str));
const char *key_exchange, *cipher, *mac;
bool is_aead, is_tls13;
net::SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead,
&is_tls13, cipher_suite);
site_connection_details_ += ASCIIToUTF16("\n\n");
if (is_aead) {
if (is_tls13) {
key_exchange =
SSL_get_curve_name(visible_security_state.key_exchange_group);
if (!key_exchange) {
NOTREACHED();
key_exchange = "";
}
}
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS_AEAD,
ASCIIToUTF16(cipher), ASCIIToUTF16(key_exchange));
} else {
site_connection_details_ += l10n_util::GetStringFUTF16(
IDS_PAGE_INFO_SECURITY_TAB_ENCRYPTION_DETAILS, ASCIIToUTF16(cipher),
ASCIIToUTF16(mac), ASCIIToUTF16(key_exchange));
}
}
ChromeSSLHostStateDelegate* delegate =
ChromeSSLHostStateDelegateFactory::GetForProfile(profile_);
DCHECK(delegate);
// SSL host errors for this host in the past.
show_ssl_decision_revoke_button_ = delegate->HasAllowException(url.host());
}
| 172,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: EncodedJSValue JSC_HOST_CALL jsTestInterfacePrototypeFunctionSupplementalMethod2(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestInterface::s_info))
return throwVMTypeError(exec);
JSTestInterface* castedThis = jsCast<JSTestInterface*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestInterface::s_info);
TestInterface* impl = static_cast<TestInterface*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createTypeError(exec, "Not enough arguments"));
ExceptionCode ec = 0;
ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();
if (!scriptContext)
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(TestSupplemental::supplementalMethod2(impl, scriptContext, strArg, objArg, ec)));
setDOMException(exec, ec);
return JSValue::encode(result);
}
Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=85102
Reviewed by Geoffrey Garen.
In bug 84787, kbr@ requested to avoid hard-coding
createTypeError(exec, "Not enough arguments") here and there.
This patch implements createNotEnoughArgumentsError(exec)
and uses it in JSC bindings.
c.f. a corresponding bug for V8 bindings is bug 85097.
Source/JavaScriptCore:
* runtime/Error.cpp:
(JSC::createNotEnoughArgumentsError):
(JSC):
* runtime/Error.h:
(JSC):
Source/WebCore:
Test: bindings/scripts/test/TestObj.idl
* bindings/scripts/CodeGeneratorJS.pm: Modified as described above.
(GenerateArgumentsCountCheck):
* bindings/js/JSDataViewCustom.cpp: Ditto.
(WebCore::getDataViewMember):
(WebCore::setDataViewMember):
* bindings/js/JSDeprecatedPeerConnectionCustom.cpp:
(WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection):
* bindings/js/JSDirectoryEntryCustom.cpp:
(WebCore::JSDirectoryEntry::getFile):
(WebCore::JSDirectoryEntry::getDirectory):
* bindings/js/JSSharedWorkerCustom.cpp:
(WebCore::JSSharedWorkerConstructor::constructJSSharedWorker):
* bindings/js/JSWebKitMutationObserverCustom.cpp:
(WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver):
(WebCore::JSWebKitMutationObserver::observe):
* bindings/js/JSWorkerCustom.cpp:
(WebCore::JSWorkerConstructor::constructJSWorker):
* bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests.
(WebCore::jsFloat64ArrayPrototypeFunctionFoo):
* bindings/scripts/test/JS/JSTestActiveDOMObject.cpp:
(WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction):
(WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage):
* bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp:
(WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction):
* bindings/scripts/test/JS/JSTestEventTarget.cpp:
(WebCore::jsTestEventTargetPrototypeFunctionItem):
(WebCore::jsTestEventTargetPrototypeFunctionAddEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener):
(WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent):
* bindings/scripts/test/JS/JSTestInterface.cpp:
(WebCore::JSTestInterfaceConstructor::constructJSTestInterface):
(WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2):
* bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp:
(WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod):
* bindings/scripts/test/JS/JSTestNamedConstructor.cpp:
(WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor):
* bindings/scripts/test/JS/JSTestObj.cpp:
(WebCore::JSTestObjConstructor::constructJSTestObj):
(WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg):
(WebCore::jsTestObjPrototypeFunctionMethodReturningSequence):
(WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows):
(WebCore::jsTestObjPrototypeFunctionSerializedValue):
(WebCore::jsTestObjPrototypeFunctionIdbKey):
(WebCore::jsTestObjPrototypeFunctionOptionsObject):
(WebCore::jsTestObjPrototypeFunctionAddEventListener):
(WebCore::jsTestObjPrototypeFunctionRemoveEventListener):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs):
(WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg):
(WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod1):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod2):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod3):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod4):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod5):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod6):
(WebCore::jsTestObjPrototypeFunctionOverloadedMethod7):
(WebCore::jsTestObjConstructorFunctionClassMethod2):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod11):
(WebCore::jsTestObjConstructorFunctionOverloadedMethod12):
(WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray):
(WebCore::jsTestObjPrototypeFunctionConvert1):
(WebCore::jsTestObjPrototypeFunctionConvert2):
(WebCore::jsTestObjPrototypeFunctionConvert3):
(WebCore::jsTestObjPrototypeFunctionConvert4):
(WebCore::jsTestObjPrototypeFunctionConvert5):
(WebCore::jsTestObjPrototypeFunctionStrictFunction):
* bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp:
(WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface):
(WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList):
git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | EncodedJSValue JSC_HOST_CALL jsTestInterfacePrototypeFunctionSupplementalMethod2(ExecState* exec)
{
JSValue thisValue = exec->hostThisValue();
if (!thisValue.inherits(&JSTestInterface::s_info))
return throwVMTypeError(exec);
JSTestInterface* castedThis = jsCast<JSTestInterface*>(asObject(thisValue));
ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestInterface::s_info);
TestInterface* impl = static_cast<TestInterface*>(castedThis->impl());
if (exec->argumentCount() < 2)
return throwVMError(exec, createNotEnoughArgumentsError(exec));
ExceptionCode ec = 0;
ScriptExecutionContext* scriptContext = jsCast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();
if (!scriptContext)
return JSValue::encode(jsUndefined());
const String& strArg(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
TestObj* objArg(toTestObj(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined)));
if (exec->hadException())
return JSValue::encode(jsUndefined());
JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(TestSupplemental::supplementalMethod2(impl, scriptContext, strArg, objArg, ec)));
setDOMException(exec, ec);
return JSValue::encode(result);
}
| 170,575 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "replace",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrReplaceFunction)) {
return 0;
}
return -1;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)) {
return 0;
}
return -1;
}
| 173,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
int len;
u32 max_blocksize = svc_max_payload(rqstp);
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ntohl(*p++);
args->count = ntohl(*p++);
len = args->count = min(args->count, max_blocksize);
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
if (!args->buffer)
args->buffer = page_address(p);
len -= PAGE_SIZE;
}
return xdr_argsize_check(rqstp, p);
}
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 | nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_readdirargs *args)
{
int len;
u32 max_blocksize = svc_max_payload(rqstp);
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->cookie);
args->verf = p; p += 2;
args->dircount = ntohl(*p++);
args->count = ntohl(*p++);
if (!xdr_argsize_check(rqstp, p))
return 0;
len = args->count = min(args->count, max_blocksize);
while (len > 0) {
struct page *p = *(rqstp->rq_next_page++);
if (!args->buffer)
args->buffer = page_address(p);
len -= PAGE_SIZE;
}
return 1;
}
| 168,142 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.x = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.y = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
rect.width = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
rect.height = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189 | PHP_FUNCTION(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.x = Z_LVAL(lval);
} else {
rect.x = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.y = Z_LVAL(lval);
} else {
rect.y = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.width = Z_LVAL(lval);
} else {
rect.width = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
if (Z_TYPE_PP(tmp) != IS_LONG) {
zval lval;
lval = **tmp;
zval_copy_ctor(&lval);
convert_to_long(&lval);
rect.height = Z_LVAL(lval);
} else {
rect.height = Z_LVAL_PP(tmp);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
| 166,427 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfsd_cross_mnt(struct svc_rqst *rqstp, struct dentry **dpp,
struct svc_export **expp)
{
struct svc_export *exp = *expp, *exp2 = NULL;
struct dentry *dentry = *dpp;
struct path path = {.mnt = mntget(exp->ex_path.mnt),
.dentry = dget(dentry)};
int err = 0;
err = follow_down(&path);
if (err < 0)
goto out;
exp2 = rqst_exp_get_by_name(rqstp, &path);
if (IS_ERR(exp2)) {
err = PTR_ERR(exp2);
/*
* We normally allow NFS clients to continue
* "underneath" a mountpoint that is not exported.
* The exception is V4ROOT, where no traversal is ever
* allowed without an explicit export of the new
* directory.
*/
if (err == -ENOENT && !(exp->ex_flags & NFSEXP_V4ROOT))
err = 0;
path_put(&path);
goto out;
}
if (nfsd_v4client(rqstp) ||
(exp->ex_flags & NFSEXP_CROSSMOUNT) || EX_NOHIDE(exp2)) {
/* successfully crossed mount point */
/*
* This is subtle: path.dentry is *not* on path.mnt
* at this point. The only reason we are safe is that
* original mnt is pinned down by exp, so we should
* put path *before* putting exp
*/
*dpp = path.dentry;
path.dentry = dentry;
*expp = exp2;
exp2 = exp;
}
path_put(&path);
exp_put(exp2);
out:
return err;
}
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 | nfsd_cross_mnt(struct svc_rqst *rqstp, struct dentry **dpp,
struct svc_export **expp)
{
struct svc_export *exp = *expp, *exp2 = NULL;
struct dentry *dentry = *dpp;
struct path path = {.mnt = mntget(exp->ex_path.mnt),
.dentry = dget(dentry)};
int err = 0;
err = follow_down(&path);
if (err < 0)
goto out;
if (path.mnt == exp->ex_path.mnt && path.dentry == dentry &&
nfsd_mountpoint(dentry, exp) == 2) {
/* This is only a mountpoint in some other namespace */
path_put(&path);
goto out;
}
exp2 = rqst_exp_get_by_name(rqstp, &path);
if (IS_ERR(exp2)) {
err = PTR_ERR(exp2);
/*
* We normally allow NFS clients to continue
* "underneath" a mountpoint that is not exported.
* The exception is V4ROOT, where no traversal is ever
* allowed without an explicit export of the new
* directory.
*/
if (err == -ENOENT && !(exp->ex_flags & NFSEXP_V4ROOT))
err = 0;
path_put(&path);
goto out;
}
if (nfsd_v4client(rqstp) ||
(exp->ex_flags & NFSEXP_CROSSMOUNT) || EX_NOHIDE(exp2)) {
/* successfully crossed mount point */
/*
* This is subtle: path.dentry is *not* on path.mnt
* at this point. The only reason we are safe is that
* original mnt is pinned down by exp, so we should
* put path *before* putting exp
*/
*dpp = path.dentry;
path.dentry = dentry;
*expp = exp2;
exp2 = exp;
}
path_put(&path);
exp_put(exp2);
out:
return err;
}
| 168,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer");
if (command_buffer_.get()) {
int32 id = command_buffer_->CreateTransferBuffer(size, id_request);
GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams(
reply_message, id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
Commit Message: Sizes going across an IPC should be uint32.
BUG=164946
Review URL: https://chromiumcodereview.appspot.com/11472038
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuCommandBufferStub::OnCreateTransferBuffer(int32 size,
void GpuCommandBufferStub::OnCreateTransferBuffer(uint32 size,
int32 id_request,
IPC::Message* reply_message) {
TRACE_EVENT0("gpu", "GpuCommandBufferStub::OnCreateTransferBuffer");
if (command_buffer_.get()) {
int32 id = command_buffer_->CreateTransferBuffer(size, id_request);
GpuCommandBufferMsg_CreateTransferBuffer::WriteReplyParams(
reply_message, id);
} else {
reply_message->set_reply_error();
}
Send(reply_message);
}
| 171,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
/* If RFC 3476 Section 3.1 defined that a sub-object of the
* GENERALIZED_UNI RSVP object must have the Length field as
* a multiple of 4, instead of the check below it would be
* better to test total_subobj_len only once before the loop.
* So long as it does not define it and this while loop does
* not implement such a requirement, let's accept that within
* each iteration subobj_len may happen to be a multiple of 1
* and test it and total_subobj_len respectively.
*/
if (total_subobj_len < 4)
goto invalid;
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
/* In addition to what is explained above, the same spec does not
* explicitly say that the same Length field includes the 4-octet
* sub-object header, but as long as this while loop implements it
* as it does include, let's keep the check below consistent with
* the rest of the code.
*/
if(subobj_len < 4 || subobj_len > total_subobj_len)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
Commit Message: (for 4.9.3) CVE-2018-14465/RSVP: Add a missing bounds check
In rsvp_obj_print().
This fixes a buffer over-read discovered by Bhargava Shastry.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | rsvp_obj_print(netdissect_options *ndo,
const u_char *pptr, u_int plen, const u_char *tptr,
const char *ident, u_int tlen,
const struct rsvp_common_header *rsvp_com_header)
{
const struct rsvp_object_header *rsvp_obj_header;
const u_char *obj_tptr;
union {
const struct rsvp_obj_integrity_t *rsvp_obj_integrity;
const struct rsvp_obj_frr_t *rsvp_obj_frr;
} obj_ptr;
u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen;
int hexdump,processed,padbytes,error_code,error_value,i,sigcheck;
union {
float f;
uint32_t i;
} bw;
uint8_t namelen;
u_int action, subchannel;
while(tlen>=sizeof(struct rsvp_object_header)) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header));
rsvp_obj_header = (const struct rsvp_object_header *)tptr;
rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length);
rsvp_obj_ctype=rsvp_obj_header->ctype;
if(rsvp_obj_len % 4) {
ND_PRINT((ndo, "%sERROR: object header size %u not a multiple of 4", ident, rsvp_obj_len));
return -1;
}
if(rsvp_obj_len < sizeof(struct rsvp_object_header)) {
ND_PRINT((ndo, "%sERROR: object header too short %u < %lu", ident, rsvp_obj_len,
(unsigned long)sizeof(const struct rsvp_object_header)));
return -1;
}
ND_PRINT((ndo, "%s%s Object (%u) Flags: [%s",
ident,
tok2str(rsvp_obj_values,
"Unknown",
rsvp_obj_header->class_num),
rsvp_obj_header->class_num,
((rsvp_obj_header->class_num) & 0x80) ? "ignore" : "reject"));
if (rsvp_obj_header->class_num > 128)
ND_PRINT((ndo, " %s",
((rsvp_obj_header->class_num) & 0x40) ? "and forward" : "silently"));
ND_PRINT((ndo, " if unknown], Class-Type: %s (%u), length: %u",
tok2str(rsvp_ctype_values,
"Unknown",
((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype),
rsvp_obj_ctype,
rsvp_obj_len));
if(tlen < rsvp_obj_len) {
ND_PRINT((ndo, "%sERROR: object goes past end of objects TLV", ident));
return -1;
}
obj_tptr=tptr+sizeof(struct rsvp_object_header);
obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header);
/* did we capture enough for fully decoding the object ? */
if (!ND_TTEST2(*tptr, rsvp_obj_len))
return -1;
hexdump=FALSE;
switch(rsvp_obj_header->class_num) {
case RSVP_OBJ_SESSION:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return -1;
ND_PRINT((ndo, "%s IPv4 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+5),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return -1;
ND_PRINT((ndo, "%s IPv6 DestAddress: %s, Protocol ID: 0x%02x",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr + sizeof(struct in6_addr))));
ND_PRINT((ndo, "%s Flags: [0x%02x], DestPort %u",
ident,
*(obj_tptr+sizeof(struct in6_addr)+1),
EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 36)
return -1;
ND_PRINT((ndo, "%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ip6addr_string(ndo, obj_tptr + 20)));
obj_tlen-=36;
obj_tptr+=36;
break;
case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */
if (obj_tlen < 26)
return -1;
ND_PRINT((ndo, "%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ip6addr_string(ndo, obj_tptr + 8)));
obj_tlen-=26;
obj_tptr+=26;
break;
case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
case RSVP_CTYPE_UNI_IPV4:
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ipaddr_string(ndo, obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CONFIRM:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Receiver Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return -1;
ND_PRINT((ndo, "%s IPv6 Receiver Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_NOTIFY_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < sizeof(struct in_addr))
return -1;
ND_PRINT((ndo, "%s IPv4 Notify Node Address: %s",
ident,
ipaddr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in_addr);
obj_tptr+=sizeof(struct in_addr);
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < sizeof(struct in6_addr))
return-1;
ND_PRINT((ndo, "%s IPv6 Notify Node Address: %s",
ident,
ip6addr_string(ndo, obj_tptr)));
obj_tlen-=sizeof(struct in6_addr);
obj_tptr+=sizeof(struct in6_addr);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */
case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */
case RSVP_OBJ_RECOVERY_LABEL: /* fall through */
case RSVP_OBJ_LABEL:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Label: %u", ident, EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Generalized Label: %u",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s Waveband ID: %u%s Start Label: %u, Stop Label: %u",
ident,
EXTRACT_32BITS(obj_tptr),
ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_STYLE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Reservation Style: %s, Flags: [0x%02x]",
ident,
tok2str(rsvp_resstyle_values,
"Unknown",
EXTRACT_24BITS(obj_tptr+1)),
*(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SENDER_TEMPLATE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_REQ:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
obj_tlen-=4;
obj_tptr+=4;
}
break;
case RSVP_CTYPE_2:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, ",%s merge capability",((*(obj_tptr + 4)) & 0x80) ? "no" : "" ));
ND_PRINT((ndo, "%s Minimum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+4))&0xfff,
(EXTRACT_16BITS(obj_tptr + 6)) & 0xfff));
ND_PRINT((ndo, "%s Maximum VPI/VCI: %u/%u",
ident,
(EXTRACT_16BITS(obj_tptr+8))&0xfff,
(EXTRACT_16BITS(obj_tptr + 10)) & 0xfff));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 12)
return-1;
ND_PRINT((ndo, "%s L3 Protocol ID: %s",
ident,
tok2str(ethertype_values,
"Unknown Protocol (0x%04x)",
EXTRACT_16BITS(obj_tptr + 2))));
ND_PRINT((ndo, "%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI",
ident,
(EXTRACT_32BITS(obj_tptr+4))&0x7fffff,
(EXTRACT_32BITS(obj_tptr+8))&0x7fffff,
(((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? "10" : "",
(((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? "23" : ""));
obj_tlen-=12;
obj_tptr+=12;
break;
case RSVP_CTYPE_4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s LSP Encoding Type: %s (%u)",
ident,
tok2str(gmpls_encoding_values,
"Unknown",
*obj_tptr),
*obj_tptr));
ND_PRINT((ndo, "%s Switching Type: %s (%u), Payload ID: %s (0x%04x)",
ident,
tok2str(gmpls_switch_cap_values,
"Unknown",
*(obj_tptr+1)),
*(obj_tptr+1),
tok2str(gmpls_payload_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+2)),
EXTRACT_16BITS(obj_tptr + 2)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RRO:
case RSVP_OBJ_ERO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
while(obj_tlen >= 4 ) {
u_char length;
ND_TCHECK2(*obj_tptr, 4);
length = *(obj_tptr + 1);
ND_PRINT((ndo, "%s Subobject Type: %s, length %u",
ident,
tok2str(rsvp_obj_xro_values,
"Unknown %u",
RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)),
length));
if (length == 0) { /* prevent infinite loops */
ND_PRINT((ndo, "%s ERROR: zero length ERO subtype", ident));
break;
}
switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) {
u_char prefix_length;
case RSVP_OBJ_XRO_IPV4:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
prefix_length = *(obj_tptr+6);
if (prefix_length != 32) {
ND_PRINT((ndo, " ERROR: Prefix length %u != 32",
prefix_length));
goto invalid;
}
ND_PRINT((ndo, ", %s, %s/%u, Flags: [%s]",
RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? "Loose" : "Strict",
ipaddr_string(ndo, obj_tptr+2),
*(obj_tptr+6),
bittok2str(rsvp_obj_rro_flag_values,
"none",
*(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */
break;
case RSVP_OBJ_XRO_LABEL:
if (length != 8) {
ND_PRINT((ndo, " ERROR: length != 8"));
goto invalid;
}
ND_TCHECK2(*obj_tptr, 8);
ND_PRINT((ndo, ", Flags: [%s] (%#x), Class-Type: %s (%u), %u",
bittok2str(rsvp_obj_rro_label_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr+2),
tok2str(rsvp_ctype_values,
"Unknown",
*(obj_tptr+3) + 256*RSVP_OBJ_RRO),
*(obj_tptr+3),
EXTRACT_32BITS(obj_tptr + 4)));
}
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_HELLO:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Instance: 0x%08x, Destination Instance: 0x%08x",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RESTART_CAPABILITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Restart Time: %ums, Recovery Time: %ums",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_SESSION_ATTRIBUTE:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 4)
return-1;
namelen = *(obj_tptr+3);
if (obj_tlen < 4+namelen)
return-1;
ND_PRINT((ndo, "%s Session Name: ", ident));
for (i = 0; i < namelen; i++)
safeputchar(ndo, *(obj_tptr + 4 + i));
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)",
ident,
(int)*obj_tptr,
(int)*(obj_tptr+1),
bittok2str(rsvp_session_attribute_flag_values,
"none",
*(obj_tptr+2)),
*(obj_tptr + 2)));
obj_tlen-=4+*(obj_tptr+3);
obj_tptr+=4+*(obj_tptr+3);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_GENERALIZED_UNI:
switch(rsvp_obj_ctype) {
int subobj_type,af,subobj_len,total_subobj_len;
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
/* read variable length subobjects */
total_subobj_len = obj_tlen;
while(total_subobj_len > 0) {
/* If RFC 3476 Section 3.1 defined that a sub-object of the
* GENERALIZED_UNI RSVP object must have the Length field as
* a multiple of 4, instead of the check below it would be
* better to test total_subobj_len only once before the loop.
* So long as it does not define it and this while loop does
* not implement such a requirement, let's accept that within
* each iteration subobj_len may happen to be a multiple of 1
* and test it and total_subobj_len respectively.
*/
if (total_subobj_len < 4)
goto invalid;
subobj_len = EXTRACT_16BITS(obj_tptr);
subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8;
af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF;
ND_PRINT((ndo, "%s Subobject Type: %s (%u), AF: %s (%u), length: %u",
ident,
tok2str(rsvp_obj_generalized_uni_values, "Unknown", subobj_type),
subobj_type,
tok2str(af_values, "Unknown", af), af,
subobj_len));
/* In addition to what is explained above, the same spec does not
* explicitly say that the same Length field includes the 4-octet
* sub-object header, but as long as this while loop implements it
* as it does include, let's keep the check below consistent with
* the rest of the code.
*/
if(subobj_len < 4 || subobj_len > total_subobj_len)
goto invalid;
switch(subobj_type) {
case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS:
case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS:
switch(af) {
case AFNUM_INET:
if (subobj_len < 8)
return -1;
ND_PRINT((ndo, "%s UNI IPv4 TNA address: %s",
ident, ipaddr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_INET6:
if (subobj_len < 20)
return -1;
ND_PRINT((ndo, "%s UNI IPv6 TNA address: %s",
ident, ip6addr_string(ndo, obj_tptr + 4)));
break;
case AFNUM_NSAP:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
}
break;
case RSVP_GEN_UNI_SUBOBJ_DIVERSITY:
if (subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL:
if (subobj_len < 16) {
return -1;
}
ND_PRINT((ndo, "%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u",
ident,
((EXTRACT_32BITS(obj_tptr+4))>>31),
((EXTRACT_32BITS(obj_tptr+4))&0xFF),
EXTRACT_32BITS(obj_tptr+8),
EXTRACT_32BITS(obj_tptr + 12)));
break;
case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL:
if (subobj_len < 8) {
return -1;
}
ND_PRINT((ndo, "%s Service level: %u",
ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24));
break;
default:
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
obj_tptr+=subobj_len;
obj_tlen+=subobj_len;
}
if (total_subobj_len) {
/* unless we have a TLV parser lets just hexdump */
hexdump=TRUE;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_RSVP_HOP:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
if (obj_tlen)
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr + 16)));
obj_tlen-=20;
obj_tptr+=20;
hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_TIME_VALUES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Refresh Period: %ums",
ident,
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
/* those three objects do share the same semantics */
case RSVP_OBJ_SENDER_TSPEC:
case RSVP_OBJ_ADSPEC:
case RSVP_OBJ_FLOWSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_2:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Msg-Version: %u, length: %u",
ident,
(*obj_tptr & 0xf0) >> 4,
EXTRACT_16BITS(obj_tptr + 2) << 2));
obj_tptr+=4; /* get to the start of the service header */
obj_tlen-=4;
while (obj_tlen >= 4) {
intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2;
ND_PRINT((ndo, "%s Service Type: %s (%u), break bit %s set, Service length: %u",
ident,
tok2str(rsvp_intserv_service_type_values,"unknown",*(obj_tptr)),
*(obj_tptr),
(*(obj_tptr+1)&0x80) ? "" : "not",
intserv_serv_tlen));
obj_tptr+=4; /* get to the start of the parameter list */
obj_tlen-=4;
while (intserv_serv_tlen>=4) {
processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen);
if (processed == 0)
break;
obj_tlen-=processed;
intserv_serv_tlen-=processed;
obj_tptr+=processed;
}
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FILTERSPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Source Port: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_3:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, Flow Label: %u",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_24BITS(obj_tptr + 17)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_TUNNEL_IPV6:
if (obj_tlen < 20)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 18)));
obj_tlen-=20;
obj_tptr+=20;
break;
case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */
if (obj_tlen < 40)
return-1;
ND_PRINT((ndo, "%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ip6addr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+18),
ident,
ip6addr_string(ndo, obj_tptr+20),
EXTRACT_16BITS(obj_tptr + 38)));
obj_tlen-=40;
obj_tptr+=40;
break;
case RSVP_CTYPE_TUNNEL_IPV4:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Source Address: %s, LSP-ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr + 6)));
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"
"%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x",
ident,
ipaddr_string(ndo, obj_tptr),
EXTRACT_16BITS(obj_tptr+6),
ident,
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_16BITS(obj_tptr + 12)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_FASTREROUTE:
/* the differences between c-type 1 and 7 are minor */
obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr;
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1: /* new style */
if (obj_tlen < sizeof(struct rsvp_obj_frr_t))
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all)));
obj_tlen-=sizeof(struct rsvp_obj_frr_t);
obj_tptr+=sizeof(struct rsvp_obj_frr_t);
break;
case RSVP_CTYPE_TUNNEL_IPV4: /* old style */
if (obj_tlen < 16)
return-1;
bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth);
ND_PRINT((ndo, "%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps",
ident,
(int)obj_ptr.rsvp_obj_frr->setup_prio,
(int)obj_ptr.rsvp_obj_frr->hold_prio,
(int)obj_ptr.rsvp_obj_frr->hop_limit,
bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Include Colors: 0x%08x, Exclude Colors: 0x%08x",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any),
EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_DETOUR:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_TUNNEL_IPV4:
while(obj_tlen >= 8) {
ND_PRINT((ndo, "%s PLR-ID: %s, Avoid-Node-ID: %s",
ident,
ipaddr_string(ndo, obj_tptr),
ipaddr_string(ndo, obj_tptr + 4)));
obj_tlen-=8;
obj_tptr+=8;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_CLASSTYPE:
case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
ND_TCHECK_32BITS(obj_tptr);
ND_PRINT((ndo, "%s CT: %u",
ident,
EXTRACT_32BITS(obj_tptr) & 0x7));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ERROR_SPEC:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV4:
if (obj_tlen < 8)
return-1;
error_code=*(obj_tptr+5);
error_value=EXTRACT_16BITS(obj_tptr+6);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ipaddr_string(ndo, obj_tptr),
*(obj_tptr+4),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */
case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_diffserv_te_values,"unknown",error_value),
error_value));
break;
default:
ND_PRINT((ndo, ", Unknown Error Value (%u)", error_value));
break;
}
obj_tlen-=8;
obj_tptr+=8;
break;
case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */
case RSVP_CTYPE_IPV6:
if (obj_tlen < 20)
return-1;
error_code=*(obj_tptr+17);
error_value=EXTRACT_16BITS(obj_tptr+18);
ND_PRINT((ndo, "%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)",
ident,
ip6addr_string(ndo, obj_tptr),
*(obj_tptr+16),
ident,
tok2str(rsvp_obj_error_code_values,"unknown",error_code),
error_code));
switch (error_code) {
case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING:
ND_PRINT((ndo, ", Error Value: %s (%u)",
tok2str(rsvp_obj_error_code_routing_values,"unknown",error_value),
error_value));
break;
default:
break;
}
obj_tlen-=20;
obj_tptr+=20;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_PROPERTIES:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
padbytes = EXTRACT_16BITS(obj_tptr+2);
ND_PRINT((ndo, "%s TLV count: %u, padding bytes: %u",
ident,
EXTRACT_16BITS(obj_tptr),
padbytes));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there is anything longer than the TLV header (2) */
while(obj_tlen >= 2 + padbytes) {
ND_PRINT((ndo, "%s %s TLV (0x%02x), length: %u", /* length includes header */
ident,
tok2str(rsvp_obj_prop_tlv_values,"unknown",*obj_tptr),
*obj_tptr,
*(obj_tptr + 1)));
if (obj_tlen < *(obj_tptr+1))
return-1;
if (*(obj_tptr+1) < 2)
return -1;
print_unknown_data(ndo, obj_tptr + 2, "\n\t\t", *(obj_tptr + 1) - 2);
obj_tlen-=*(obj_tptr+1);
obj_tptr+=*(obj_tptr+1);
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_MESSAGE_ID: /* fall through */
case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */
case RSVP_OBJ_MESSAGE_ID_LIST:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
case RSVP_CTYPE_2:
if (obj_tlen < 8)
return-1;
ND_PRINT((ndo, "%s Flags [0x%02x], epoch: %u",
ident,
*obj_tptr,
EXTRACT_24BITS(obj_tptr + 1)));
obj_tlen-=4;
obj_tptr+=4;
/* loop through as long there are no messages left */
while(obj_tlen >= 4) {
ND_PRINT((ndo, "%s Message-ID 0x%08x (%u)",
ident,
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
}
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_INTEGRITY:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < sizeof(struct rsvp_obj_integrity_t))
return-1;
obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr;
ND_PRINT((ndo, "%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]",
ident,
EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4),
bittok2str(rsvp_obj_integrity_flag_values,
"none",
obj_ptr.rsvp_obj_integrity->flags)));
ND_PRINT((ndo, "%s MD5-sum 0x%08x%08x%08x%08x ",
ident,
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8),
EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12)));
sigcheck = signature_verify(ndo, pptr, plen,
obj_ptr.rsvp_obj_integrity->digest,
rsvp_clear_checksum,
rsvp_com_header);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
obj_tlen+=sizeof(struct rsvp_obj_integrity_t);
obj_tptr+=sizeof(struct rsvp_obj_integrity_t);
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_ADMIN_STATUS:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Flags [%s]", ident,
bittok2str(rsvp_obj_admin_status_flag_values, "none",
EXTRACT_32BITS(obj_tptr))));
obj_tlen-=4;
obj_tptr+=4;
break;
default:
hexdump=TRUE;
}
break;
case RSVP_OBJ_LABEL_SET:
switch(rsvp_obj_ctype) {
case RSVP_CTYPE_1:
if (obj_tlen < 4)
return-1;
action = (EXTRACT_16BITS(obj_tptr)>>8);
ND_PRINT((ndo, "%s Action: %s (%u), Label type: %u", ident,
tok2str(rsvp_obj_label_set_action_values, "Unknown", action),
action, ((EXTRACT_32BITS(obj_tptr) & 0x7F))));
switch (action) {
case LABEL_SET_INCLUSIVE_RANGE:
case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */
/* only a couple of subchannels are expected */
if (obj_tlen < 12)
return -1;
ND_PRINT((ndo, "%s Start range: %u, End range: %u", ident,
EXTRACT_32BITS(obj_tptr+4),
EXTRACT_32BITS(obj_tptr + 8)));
obj_tlen-=12;
obj_tptr+=12;
break;
default:
obj_tlen-=4;
obj_tptr+=4;
subchannel = 1;
while(obj_tlen >= 4 ) {
ND_PRINT((ndo, "%s Subchannel #%u: %u", ident, subchannel,
EXTRACT_32BITS(obj_tptr)));
obj_tptr+=4;
obj_tlen-=4;
subchannel++;
}
break;
}
break;
default:
hexdump=TRUE;
}
case RSVP_OBJ_S2L:
switch (rsvp_obj_ctype) {
case RSVP_CTYPE_IPV4:
if (obj_tlen < 4)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ipaddr_string(ndo, obj_tptr)));
obj_tlen-=4;
obj_tptr+=4;
break;
case RSVP_CTYPE_IPV6:
if (obj_tlen < 16)
return-1;
ND_PRINT((ndo, "%s Sub-LSP destination address: %s",
ident, ip6addr_string(ndo, obj_tptr)));
obj_tlen-=16;
obj_tptr+=16;
break;
default:
hexdump=TRUE;
}
/*
* FIXME those are the defined objects that lack a decoder
* you are welcome to contribute code ;-)
*/
case RSVP_OBJ_SCOPE:
case RSVP_OBJ_POLICY_DATA:
case RSVP_OBJ_ACCEPT_LABEL_SET:
case RSVP_OBJ_PROTECTION:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, obj_tptr, "\n\t ", obj_tlen); /* FIXME indentation */
break;
}
/* do we also want to see a hex dump ? */
if (ndo->ndo_vflag > 1 || hexdump == TRUE)
print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), "\n\t ", /* FIXME indentation */
rsvp_obj_len - sizeof(struct rsvp_object_header));
tptr+=rsvp_obj_len;
tlen-=rsvp_obj_len;
}
return 0;
invalid:
ND_PRINT((ndo, "%s", istr));
return -1;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return -1;
}
| 169,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: validate_event(struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu = to_arm_pmu(event->pmu);
struct hw_perf_event fake_event = event->hw;
struct pmu *leader_pmu = event->group_leader->pmu;
if (is_software_event(event))
return 1;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
return armpmu->get_event_idx(hw_events, &fake_event) >= 0;
}
Commit Message: arm64: perf: reject groups spanning multiple HW PMUs
The perf core implicitly rejects events spanning multiple HW PMUs, as in
these cases the event->ctx will differ. However this validation is
performed after pmu::event_init() is called in perf_init_event(), and
thus pmu::event_init() may be called with a group leader from a
different HW PMU.
The ARM64 PMU driver does not take this fact into account, and when
validating groups assumes that it can call to_arm_pmu(event->pmu) for
any HW event. When the event in question is from another HW PMU this is
wrong, and results in dereferencing garbage.
This patch updates the ARM64 PMU driver to first test for and reject
events from other PMUs, moving the to_arm_pmu and related logic after
this test. Fixes a crash triggered by perf_fuzzer on Linux-4.0-rc2, with
a CCI PMU present:
Bad mode in Synchronous Abort handler detected, code 0x86000006 -- IABT (current EL)
CPU: 0 PID: 1371 Comm: perf_fuzzer Not tainted 3.19.0+ #249
Hardware name: V2F-1XV7 Cortex-A53x2 SMM (DT)
task: ffffffc07c73a280 ti: ffffffc07b0a0000 task.ti: ffffffc07b0a0000
PC is at 0x0
LR is at validate_event+0x90/0xa8
pc : [<0000000000000000>] lr : [<ffffffc000090228>] pstate: 00000145
sp : ffffffc07b0a3ba0
[< (null)>] (null)
[<ffffffc0000907d8>] armpmu_event_init+0x174/0x3cc
[<ffffffc00015d870>] perf_try_init_event+0x34/0x70
[<ffffffc000164094>] perf_init_event+0xe0/0x10c
[<ffffffc000164348>] perf_event_alloc+0x288/0x358
[<ffffffc000164c5c>] SyS_perf_event_open+0x464/0x98c
Code: bad PC value
Also cleans up the code to use the arm_pmu only when we know
that we are dealing with an arm pmu event.
Cc: Will Deacon <[email protected]>
Acked-by: Mark Rutland <[email protected]>
Acked-by: Peter Ziljstra (Intel) <[email protected]>
Signed-off-by: Suzuki K. Poulose <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-264 | validate_event(struct pmu_hw_events *hw_events,
validate_event(struct pmu *pmu, struct pmu_hw_events *hw_events,
struct perf_event *event)
{
struct arm_pmu *armpmu;
struct hw_perf_event fake_event = event->hw;
struct pmu *leader_pmu = event->group_leader->pmu;
if (is_software_event(event))
return 1;
/*
* Reject groups spanning multiple HW PMUs (e.g. CPU + CCI). The
* core perf code won't check that the pmu->ctx == leader->ctx
* until after pmu->event_init(event).
*/
if (event->pmu != pmu)
return 0;
if (event->pmu != leader_pmu || event->state < PERF_EVENT_STATE_OFF)
return 1;
if (event->state == PERF_EVENT_STATE_OFF && !event->attr.enable_on_exec)
return 1;
armpmu = to_arm_pmu(event->pmu);
return armpmu->get_event_idx(hw_events, &fake_event) >= 0;
}
| 167,467 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Document::processHttpEquiv(const String& equiv, const String& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
Frame* frame = this->frame();
if (equalIgnoringCase(equiv, "default-style")) {
m_styleSheetCollection->setSelectedStylesheetSetName(content);
m_styleSheetCollection->setPreferredStylesheetSetName(content);
styleResolverChanged(DeferRecalcStyle);
} else if (equalIgnoringCase(equiv, "refresh")) {
double delay;
String url;
if (frame && parseHTTPRefresh(content, true, delay, url)) {
if (url.isEmpty())
url = m_url.string();
else
url = completeURL(url).string();
frame->navigationScheduler()->scheduleRedirect(delay, url);
}
} else if (equalIgnoringCase(equiv, "set-cookie")) {
if (isHTMLDocument()) {
toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
}
} else if (equalIgnoringCase(equiv, "content-language"))
setContentLanguage(content);
else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
parseDNSPrefetchControlHeader(content);
else if (equalIgnoringCase(equiv, "x-frame-options")) {
if (frame) {
FrameLoader* frameLoader = frame->loader();
unsigned long requestIdentifier = 0;
if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader())
requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier();
if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
frameLoader->stopAllLoaders();
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), "data:text/html,<p></p>", String());
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
}
}
} else if (equalIgnoringCase(equiv, "content-security-policy"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
else if (equalIgnoringCase(equiv, "x-webkit-csp"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
}
Commit Message: Unreviewed, rolling out r147402.
http://trac.webkit.org/changeset/147402
https://bugs.webkit.org/show_bug.cgi?id=112903
Source/WebCore:
* dom/Document.cpp:
(WebCore::Document::processHttpEquiv):
* loader/DocumentLoader.cpp:
(WebCore::DocumentLoader::responseReceived):
LayoutTests:
* http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag.html:
* http/tests/security/XFrameOptions/x-frame-options-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny.html:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
* http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny.html:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-in-body-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-deny-meta-tag-parent-same-origin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-multiple-headers-sameorigin-deny-expected.txt:
* platform/chromium/http/tests/security/XFrameOptions/x-frame-options-parent-same-origin-deny-expected.txt:
git-svn-id: svn://svn.chromium.org/blink/trunk@147450 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void Document::processHttpEquiv(const String& equiv, const String& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
Frame* frame = this->frame();
if (equalIgnoringCase(equiv, "default-style")) {
m_styleSheetCollection->setSelectedStylesheetSetName(content);
m_styleSheetCollection->setPreferredStylesheetSetName(content);
styleResolverChanged(DeferRecalcStyle);
} else if (equalIgnoringCase(equiv, "refresh")) {
double delay;
String url;
if (frame && parseHTTPRefresh(content, true, delay, url)) {
if (url.isEmpty())
url = m_url.string();
else
url = completeURL(url).string();
frame->navigationScheduler()->scheduleRedirect(delay, url);
}
} else if (equalIgnoringCase(equiv, "set-cookie")) {
if (isHTMLDocument()) {
toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
}
} else if (equalIgnoringCase(equiv, "content-language"))
setContentLanguage(content);
else if (equalIgnoringCase(equiv, "x-dns-prefetch-control"))
parseDNSPrefetchControlHeader(content);
else if (equalIgnoringCase(equiv, "x-frame-options")) {
if (frame) {
FrameLoader* frameLoader = frame->loader();
unsigned long requestIdentifier = 0;
if (frameLoader->activeDocumentLoader() && frameLoader->activeDocumentLoader()->mainResourceLoader())
requestIdentifier = frameLoader->activeDocumentLoader()->mainResourceLoader()->identifier();
if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
frameLoader->stopAllLoaders();
frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), blankURL(), String());
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
}
}
} else if (equalIgnoringCase(equiv, "content-security-policy"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
else if (equalIgnoringCase(equiv, "x-webkit-csp"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
}
| 170,817 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *M_fs_path_tmpdir(M_fs_system_t sys_type)
{
char *d = NULL;
char *out = NULL;
M_fs_error_t res;
#ifdef _WIN32
size_t len = M_fs_path_get_path_max(M_FS_SYSTEM_WINDOWS)+1;
d = M_malloc_zero(len);
/* Return is length without NULL. */
if (GetTempPath((DWORD)len, d) >= len) {
M_free(d);
d = NULL;
}
#elif defined(__APPLE__)
d = M_fs_path_mac_tmpdir();
#else
const char *const_temp;
/* Try Unix env var. */
# ifdef HAVE_SECURE_GETENV
const_temp = secure_getenv("TMPDIR");
# else
const_temp = getenv("TMPDIR");
# endif
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
/* Fallback to some "standard" system paths. */
if (d == NULL) {
const_temp = "/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
if (d == NULL) {
const_temp = "/var/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
#endif
if (d != NULL) {
res = M_fs_path_norm(&out, d, M_FS_PATH_NORM_ABSOLUTE, sys_type);
if (res != M_FS_ERROR_SUCCESS) {
out = NULL;
}
}
M_free(d);
return out;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732 | char *M_fs_path_tmpdir(M_fs_system_t sys_type)
{
char *d = NULL;
char *out = NULL;
M_fs_error_t res;
#ifdef _WIN32
size_t len = M_fs_path_get_path_max(M_FS_SYSTEM_WINDOWS)+1;
d = M_malloc_zero(len);
/* Return is length without NULL. */
if (GetTempPath((DWORD)len, d) >= len) {
M_free(d);
d = NULL;
}
#elif defined(__APPLE__)
d = M_fs_path_mac_tmpdir();
#else
const char *const_temp;
/* Unix doens't have a fancy function to get the standard
* temporary directory an application can use. Instead there
* is a convoluted set of possible paths that could be used.
*
* We're going to go though each one in a priority order and
* verify if we can read and write the directory. If so then
* that's the one that will be used. We are fine using access
* here because it doesn't matter if the path ends up being
* changed out from underneath us later on. When it's used
* at that time it will fail. Right now we just want to get
* a path that can be tried. */
/* Try Unix env vars.
*
* This is not ideal but a valid way to set the temporary directory
* for a user. Per Single Unix Specification 4 and probably other things.
*/
# ifdef HAVE_SECURE_GETENV
const_temp = secure_getenv("TMPDIR");
# else
const_temp = getenv("TMPDIR");
# endif
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
/* Fallback to some "standard" system paths. */
if (d == NULL) {
const_temp = "/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
if (d == NULL) {
const_temp = "/var/tmp";
if (!M_str_isempty(const_temp) && M_fs_perms_can_access(const_temp, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_WRITE) == M_FS_ERROR_SUCCESS) {
d = M_strdup(const_temp);
}
}
#endif
if (d != NULL) {
res = M_fs_path_norm(&out, d, M_FS_PATH_NORM_ABSOLUTE, sys_type);
if (res != M_FS_ERROR_SUCCESS) {
out = NULL;
}
}
M_free(d);
return out;
}
| 169,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BlobStorageContext::BlobFlattener::BlobFlattener(
const BlobDataBuilder& input_builder,
BlobEntry* output_blob,
BlobStorageRegistry* registry) {
const std::string& uuid = input_builder.uuid_;
std::set<std::string> dependent_blob_uuids;
size_t num_files_with_unknown_size = 0;
size_t num_building_dependent_blobs = 0;
bool found_memory_transport = false;
bool found_file_transport = false;
base::CheckedNumeric<uint64_t> checked_total_size = 0;
base::CheckedNumeric<uint64_t> checked_total_memory_size = 0;
base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0;
base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0;
for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
const DataElement& input_element = input_item->data_element();
DataElement::Type type = input_element.type();
uint64_t length = input_element.length();
RecordBlobItemSizeStats(input_element);
if (IsBytes(type)) {
DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
found_memory_transport = true;
if (found_file_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items |=
(type == DataElement::TYPE_BYTES_DESCRIPTION);
checked_transport_quota_needed += length;
checked_total_size += length;
scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
output_blob->AppendSharedBlobItem(std::move(item));
continue;
}
if (type == DataElement::TYPE_BLOB) {
BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
if (!ref_entry || input_element.blob_uuid() == uuid) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (BlobStatusIsError(ref_entry->status())) {
status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
return;
}
if (ref_entry->total_size() == DataElement::kUnknownSize) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
dependent_blob_uuids.end()) {
dependent_blobs.push_back(
std::make_pair(input_element.blob_uuid(), ref_entry));
dependent_blob_uuids.insert(input_element.blob_uuid());
if (BlobStatusIsPending(ref_entry->status())) {
num_building_dependent_blobs++;
}
}
length = length == DataElement::kUnknownSize ? ref_entry->total_size()
: input_element.length();
checked_total_size += length;
if (input_element.offset() == 0 && length == ref_entry->total_size()) {
for (const auto& shareable_item : ref_entry->items()) {
output_blob->AppendSharedBlobItem(shareable_item);
}
continue;
}
if (input_element.offset() + length > ref_entry->total_size()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
BlobSlice slice(*ref_entry, input_element.offset(), length);
if (!slice.copying_memory_size.IsValid() ||
!slice.total_memory_size.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
checked_total_memory_size += slice.total_memory_size;
if (slice.first_source_item) {
copies.push_back(ItemCopyEntry(slice.first_source_item,
slice.first_item_slice_offset,
slice.dest_items.front()));
pending_copy_items.push_back(slice.dest_items.front());
}
if (slice.last_source_item) {
copies.push_back(
ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
pending_copy_items.push_back(slice.dest_items.back());
}
checked_copy_quota_needed += slice.copying_memory_size;
for (auto& shareable_item : slice.dest_items) {
output_blob->AppendSharedBlobItem(std::move(shareable_item));
}
continue;
}
scoped_refptr<ShareableBlobDataItem> item;
if (BlobDataBuilder::IsFutureFileItem(input_element)) {
found_file_transport = true;
if (found_memory_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items = true;
item = new ShareableBlobDataItem(std::move(input_item),
ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
checked_transport_quota_needed += length;
} else {
item = new ShareableBlobDataItem(
std::move(input_item),
ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
}
if (length == DataElement::kUnknownSize)
num_files_with_unknown_size++;
checked_total_size += length;
output_blob->AppendSharedBlobItem(std::move(item));
}
if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() ||
!checked_transport_quota_needed.IsValid() ||
!checked_copy_quota_needed.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
total_size = checked_total_size.ValueOrDie();
total_memory_size = checked_total_memory_size.ValueOrDie();
transport_quota_needed = checked_transport_quota_needed.ValueOrDie();
copy_quota_needed = checked_copy_quota_needed.ValueOrDie();
transport_quota_type = found_file_transport ? TransportQuotaType::FILE
: TransportQuotaType::MEMORY;
if (transport_quota_needed) {
status = BlobStatus::PENDING_QUOTA;
} else {
status = BlobStatus::PENDING_INTERNALS;
}
}
Commit Message: [BlobStorage] Fixing potential overflow
Bug: 779314
Change-Id: I74612639d20544e4c12230569c7b88fbe669ec03
Reviewed-on: https://chromium-review.googlesource.com/747725
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#512977}
CWE ID: CWE-119 | BlobStorageContext::BlobFlattener::BlobFlattener(
const BlobDataBuilder& input_builder,
BlobEntry* output_blob,
BlobStorageRegistry* registry) {
const std::string& uuid = input_builder.uuid_;
std::set<std::string> dependent_blob_uuids;
size_t num_files_with_unknown_size = 0;
size_t num_building_dependent_blobs = 0;
bool found_memory_transport = false;
bool found_file_transport = false;
base::CheckedNumeric<uint64_t> checked_total_size = 0;
base::CheckedNumeric<uint64_t> checked_total_memory_size = 0;
base::CheckedNumeric<uint64_t> checked_transport_quota_needed = 0;
base::CheckedNumeric<uint64_t> checked_copy_quota_needed = 0;
for (scoped_refptr<BlobDataItem> input_item : input_builder.items_) {
const DataElement& input_element = input_item->data_element();
DataElement::Type type = input_element.type();
uint64_t length = input_element.length();
RecordBlobItemSizeStats(input_element);
if (IsBytes(type)) {
DCHECK_NE(0 + DataElement::kUnknownSize, input_element.length());
found_memory_transport = true;
if (found_file_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items |=
(type == DataElement::TYPE_BYTES_DESCRIPTION);
checked_transport_quota_needed += length;
checked_total_size += length;
scoped_refptr<ShareableBlobDataItem> item = new ShareableBlobDataItem(
std::move(input_item), ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
output_blob->AppendSharedBlobItem(std::move(item));
continue;
}
if (type == DataElement::TYPE_BLOB) {
BlobEntry* ref_entry = registry->GetEntry(input_element.blob_uuid());
if (!ref_entry || input_element.blob_uuid() == uuid) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (BlobStatusIsError(ref_entry->status())) {
status = BlobStatus::ERR_REFERENCED_BLOB_BROKEN;
return;
}
if (ref_entry->total_size() == DataElement::kUnknownSize) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (dependent_blob_uuids.find(input_element.blob_uuid()) ==
dependent_blob_uuids.end()) {
dependent_blobs.push_back(
std::make_pair(input_element.blob_uuid(), ref_entry));
dependent_blob_uuids.insert(input_element.blob_uuid());
if (BlobStatusIsPending(ref_entry->status())) {
num_building_dependent_blobs++;
}
}
length = length == DataElement::kUnknownSize ? ref_entry->total_size()
: input_element.length();
checked_total_size += length;
if (input_element.offset() == 0 && length == ref_entry->total_size()) {
for (const auto& shareable_item : ref_entry->items()) {
output_blob->AppendSharedBlobItem(shareable_item);
}
continue;
}
uint64_t end_byte;
if (!base::CheckAdd(input_element.offset(), length)
.AssignIfValid(&end_byte) ||
end_byte > ref_entry->total_size()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
BlobSlice slice(*ref_entry, input_element.offset(), length);
if (!slice.copying_memory_size.IsValid() ||
!slice.total_memory_size.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
checked_total_memory_size += slice.total_memory_size;
if (slice.first_source_item) {
copies.push_back(ItemCopyEntry(slice.first_source_item,
slice.first_item_slice_offset,
slice.dest_items.front()));
pending_copy_items.push_back(slice.dest_items.front());
}
if (slice.last_source_item) {
copies.push_back(
ItemCopyEntry(slice.last_source_item, 0, slice.dest_items.back()));
pending_copy_items.push_back(slice.dest_items.back());
}
checked_copy_quota_needed += slice.copying_memory_size;
for (auto& shareable_item : slice.dest_items) {
output_blob->AppendSharedBlobItem(std::move(shareable_item));
}
continue;
}
scoped_refptr<ShareableBlobDataItem> item;
if (BlobDataBuilder::IsFutureFileItem(input_element)) {
found_file_transport = true;
if (found_memory_transport) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
contains_unpopulated_transport_items = true;
item = new ShareableBlobDataItem(std::move(input_item),
ShareableBlobDataItem::QUOTA_NEEDED);
pending_transport_items.push_back(item);
transport_items.push_back(item.get());
checked_transport_quota_needed += length;
} else {
item = new ShareableBlobDataItem(
std::move(input_item),
ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA);
}
if (length == DataElement::kUnknownSize)
num_files_with_unknown_size++;
checked_total_size += length;
output_blob->AppendSharedBlobItem(std::move(item));
}
if (num_files_with_unknown_size > 1 && input_builder.items_.size() > 1) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
if (!checked_total_size.IsValid() || !checked_total_memory_size.IsValid() ||
!checked_transport_quota_needed.IsValid() ||
!checked_copy_quota_needed.IsValid()) {
status = BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS;
return;
}
total_size = checked_total_size.ValueOrDie();
total_memory_size = checked_total_memory_size.ValueOrDie();
transport_quota_needed = checked_transport_quota_needed.ValueOrDie();
copy_quota_needed = checked_copy_quota_needed.ValueOrDie();
transport_quota_type = found_file_transport ? TransportQuotaType::FILE
: TransportQuotaType::MEMORY;
if (transport_quota_needed) {
status = BlobStatus::PENDING_QUOTA;
} else {
status = BlobStatus::PENDING_INTERNALS;
}
}
| 172,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */
int i;
if (heap->count+1 > heap->max_size) {
/* we need to allocate more memory */
heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size)));
heap->max_size *= 2;
}
heap->ctor(elem TSRMLS_CC);
/* sifting up */
for(i = heap->count++; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) {
heap->elements[i] = heap->elements[(i-1)/2];
}
if (EG(exception)) {
/* exception thrown during comparison */
}
heap->elements[i] = elem;
}
/* }}} */
Commit Message:
CWE ID: | static void spl_ptr_heap_insert(spl_ptr_heap *heap, spl_ptr_heap_element elem, void *cmp_userdata TSRMLS_DC) { /* {{{ */
int i;
if (heap->count+1 > heap->max_size) {
/* we need to allocate more memory */
heap->elements = (void **) safe_erealloc(heap->elements, sizeof(spl_ptr_heap_element), (heap->max_size), (sizeof(spl_ptr_heap_element) * (heap->max_size)));
heap->max_size *= 2;
}
heap->ctor(elem TSRMLS_CC);
/* sifting up */
for(i = heap->count; i > 0 && heap->cmp(heap->elements[(i-1)/2], elem, cmp_userdata TSRMLS_CC) < 0; i = (i-1)/2) {
heap->elements[i] = heap->elements[(i-1)/2];
}
heap->count++;
if (EG(exception)) {
/* exception thrown during comparison */
}
heap->elements[i] = elem;
}
/* }}} */
| 165,307 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height)
{
if (!webkitWebViewBase->priv->inspectorView)
return;
if (webkitWebViewBase->priv->inspectorViewHeight == height)
return;
webkitWebViewBase->priv->inspectorViewHeight = height;
gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase));
}
Commit Message: [GTK] Inspector should set a default attached height before being attached
https://bugs.webkit.org/show_bug.cgi?id=90767
Reviewed by Xan Lopez.
We are currently using the minimum attached height in
WebKitWebViewBase as the default height for the inspector when
attached. It would be easier for WebKitWebViewBase and embedders
implementing attach() if the inspector already had an attached
height set when it's being attached.
* UIProcess/API/gtk/WebKitWebViewBase.cpp:
(webkitWebViewBaseContainerAdd): Don't initialize
inspectorViewHeight.
(webkitWebViewBaseSetInspectorViewHeight): Allow to set the
inspector view height before having an inpector view, but only
queue a resize when the view already has an inspector view.
* UIProcess/API/gtk/tests/TestInspector.cpp:
(testInspectorDefault):
(testInspectorManualAttachDetach):
* UIProcess/gtk/WebInspectorProxyGtk.cpp:
(WebKit::WebInspectorProxy::platformAttach): Set the default
attached height before attach the inspector view.
git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void webkitWebViewBaseSetInspectorViewHeight(WebKitWebViewBase* webkitWebViewBase, unsigned height)
{
if (webkitWebViewBase->priv->inspectorViewHeight == height)
return;
webkitWebViewBase->priv->inspectorViewHeight = height;
if (webkitWebViewBase->priv->inspectorView)
gtk_widget_queue_resize_no_redraw(GTK_WIDGET(webkitWebViewBase));
}
| 171,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
{
return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
pm->current_encoding->gamma == pm->current_gamma;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm)
modifier_color_encoding_is_sRGB(const png_modifier *pm)
{
return pm->current_encoding != 0 && pm->current_encoding == pm->encodings &&
pm->current_encoding->gamma == pm->current_gamma;
}
| 173,667 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void exit_sem(struct task_struct *tsk)
{
struct sem_undo_list *ulp;
ulp = tsk->sysvsem.undo_list;
if (!ulp)
return;
tsk->sysvsem.undo_list = NULL;
if (!atomic_dec_and_test(&ulp->refcnt))
return;
for (;;) {
struct sem_array *sma;
struct sem_undo *un;
struct list_head tasks;
int semid;
int i;
rcu_read_lock();
un = list_entry_rcu(ulp->list_proc.next,
struct sem_undo, list_proc);
if (&un->list_proc == &ulp->list_proc)
semid = -1;
else
semid = un->semid;
rcu_read_unlock();
if (semid == -1)
break;
sma = sem_lock_check(tsk->nsproxy->ipc_ns, un->semid);
/* exit_sem raced with IPC_RMID, nothing to do */
if (IS_ERR(sma))
continue;
un = __lookup_undo(ulp, semid);
if (un == NULL) {
/* exit_sem raced with IPC_RMID+semget() that created
* exactly the same semid. Nothing to do.
*/
sem_unlock(sma);
continue;
}
/* remove un from the linked lists */
assert_spin_locked(&sma->sem_perm.lock);
list_del(&un->list_id);
spin_lock(&ulp->lock);
list_del_rcu(&un->list_proc);
spin_unlock(&ulp->lock);
/* perform adjustments registered in un */
for (i = 0; i < sma->sem_nsems; i++) {
struct sem * semaphore = &sma->sem_base[i];
if (un->semadj[i]) {
semaphore->semval += un->semadj[i];
/*
* Range checks of the new semaphore value,
* not defined by sus:
* - Some unices ignore the undo entirely
* (e.g. HP UX 11i 11.22, Tru64 V5.1)
* - some cap the value (e.g. FreeBSD caps
* at 0, but doesn't enforce SEMVMX)
*
* Linux caps the semaphore value, both at 0
* and at SEMVMX.
*
* Manfred <[email protected]>
*/
if (semaphore->semval < 0)
semaphore->semval = 0;
if (semaphore->semval > SEMVMX)
semaphore->semval = SEMVMX;
semaphore->sempid = task_tgid_vnr(current);
}
}
/* maybe some queued-up processes were waiting for this */
INIT_LIST_HEAD(&tasks);
do_smart_update(sma, NULL, 0, 1, &tasks);
sem_unlock(sma);
wake_up_sem_queue_do(&tasks);
kfree_rcu(un, rcu);
}
kfree(ulp);
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | void exit_sem(struct task_struct *tsk)
{
struct sem_undo_list *ulp;
ulp = tsk->sysvsem.undo_list;
if (!ulp)
return;
tsk->sysvsem.undo_list = NULL;
if (!atomic_dec_and_test(&ulp->refcnt))
return;
for (;;) {
struct sem_array *sma;
struct sem_undo *un;
struct list_head tasks;
int semid, i;
rcu_read_lock();
un = list_entry_rcu(ulp->list_proc.next,
struct sem_undo, list_proc);
if (&un->list_proc == &ulp->list_proc)
semid = -1;
else
semid = un->semid;
if (semid == -1) {
rcu_read_unlock();
break;
}
sma = sem_obtain_object_check(tsk->nsproxy->ipc_ns, un->semid);
/* exit_sem raced with IPC_RMID, nothing to do */
if (IS_ERR(sma)) {
rcu_read_unlock();
continue;
}
sem_lock(sma, NULL, -1);
un = __lookup_undo(ulp, semid);
if (un == NULL) {
/* exit_sem raced with IPC_RMID+semget() that created
* exactly the same semid. Nothing to do.
*/
sem_unlock(sma, -1);
continue;
}
/* remove un from the linked lists */
assert_spin_locked(&sma->sem_perm.lock);
list_del(&un->list_id);
spin_lock(&ulp->lock);
list_del_rcu(&un->list_proc);
spin_unlock(&ulp->lock);
/* perform adjustments registered in un */
for (i = 0; i < sma->sem_nsems; i++) {
struct sem * semaphore = &sma->sem_base[i];
if (un->semadj[i]) {
semaphore->semval += un->semadj[i];
/*
* Range checks of the new semaphore value,
* not defined by sus:
* - Some unices ignore the undo entirely
* (e.g. HP UX 11i 11.22, Tru64 V5.1)
* - some cap the value (e.g. FreeBSD caps
* at 0, but doesn't enforce SEMVMX)
*
* Linux caps the semaphore value, both at 0
* and at SEMVMX.
*
* Manfred <[email protected]>
*/
if (semaphore->semval < 0)
semaphore->semval = 0;
if (semaphore->semval > SEMVMX)
semaphore->semval = SEMVMX;
semaphore->sempid = task_tgid_vnr(current);
}
}
/* maybe some queued-up processes were waiting for this */
INIT_LIST_HEAD(&tasks);
do_smart_update(sma, NULL, 0, 1, &tasks);
sem_unlock(sma, -1);
wake_up_sem_queue_do(&tasks);
kfree_rcu(un, rcu);
}
kfree(ulp);
}
| 165,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
return 0;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = numrows * numcols;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
}
Commit Message: Fixed a problem with a null pointer dereference in the BMP decoder.
CWE ID: CWE-476 | jas_matrix_t *jas_matrix_create(int numrows, int numcols)
{
jas_matrix_t *matrix;
int i;
if (numrows < 0 || numcols < 0) {
return 0;
}
if (!(matrix = jas_malloc(sizeof(jas_matrix_t)))) {
return 0;
}
matrix->flags_ = 0;
matrix->numrows_ = numrows;
matrix->numcols_ = numcols;
matrix->rows_ = 0;
matrix->maxrows_ = numrows;
matrix->data_ = 0;
matrix->datasize_ = numrows * numcols;
if (matrix->maxrows_ > 0) {
if (!(matrix->rows_ = jas_alloc2(matrix->maxrows_,
sizeof(jas_seqent_t *)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
if (matrix->datasize_ > 0) {
if (!(matrix->data_ = jas_alloc2(matrix->datasize_,
sizeof(jas_seqent_t)))) {
jas_matrix_destroy(matrix);
return 0;
}
}
for (i = 0; i < numrows; ++i) {
matrix->rows_[i] = &matrix->data_[i * matrix->numcols_];
}
for (i = 0; i < matrix->datasize_; ++i) {
matrix->data_[i] = 0;
}
matrix->xstart_ = 0;
matrix->ystart_ = 0;
matrix->xend_ = matrix->numcols_;
matrix->yend_ = matrix->numrows_;
return matrix;
}
| 168,755 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
: mMem(mem),
mIsBackup(is_backup),
mPortIndex(portIndex) {
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | BufferMeta(const sp<IMemory> &mem, OMX_U32 portIndex, bool is_backup = false)
BufferMeta(
const sp<IMemory> &mem, OMX_U32 portIndex, bool copyToOmx,
bool copyFromOmx, OMX_U8 *backup)
: mMem(mem),
mCopyFromOmx(copyFromOmx),
mCopyToOmx(copyToOmx),
mPortIndex(portIndex),
mBackup(backup) {
}
| 174,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)
{
struct map_struct *buf;
OFF_T i, len = st_p->st_size;
md_context m;
int32 remainder;
int fd;
memset(sum, 0, MAX_DIGEST_LEN);
fd = do_open(fname, O_RDONLY, 0);
if (fd == -1)
return;
buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);
switch (checksum_type) {
case CSUM_MD5:
md5_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK),
CSUM_CHUNK);
}
remainder = (int32)(len - i);
if (remainder > 0)
md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
md5_result(&m, (uchar *)sum);
break;
case CSUM_MD4:
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
mdfour_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
}
/* Prior to version 27 an incorrect MD4 checksum was computed
* by failing to call mdfour_tail() for block sizes that
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
remainder = (int32)(len - i);
if (remainder > 0 || checksum_type != CSUM_MD4_BUSTED)
mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
mdfour_result(&m, (uchar *)sum);
rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type);
exit_cleanup(RERR_UNSUPPORTED);
}
close(fd);
unmap_file(buf);
}
Commit Message:
CWE ID: CWE-354 | void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum)
{
struct map_struct *buf;
OFF_T i, len = st_p->st_size;
md_context m;
int32 remainder;
int fd;
memset(sum, 0, MAX_DIGEST_LEN);
fd = do_open(fname, O_RDONLY, 0);
if (fd == -1)
return;
buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK);
switch (checksum_type) {
case CSUM_MD5:
md5_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK),
CSUM_CHUNK);
}
remainder = (int32)(len - i);
if (remainder > 0)
md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
md5_result(&m, (uchar *)sum);
break;
case CSUM_MD4:
case CSUM_MD4:
case CSUM_MD4_OLD:
case CSUM_MD4_BUSTED:
case CSUM_MD4_ARCHAIC:
mdfour_begin(&m);
for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) {
}
/* Prior to version 27 an incorrect MD4 checksum was computed
* by failing to call mdfour_tail() for block sizes that
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
* are multiples of 64. This is fixed by calling mdfour_update()
* even when there are no more bytes. */
remainder = (int32)(len - i);
if (remainder > 0 || checksum_type > CSUM_MD4_BUSTED)
mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder);
mdfour_result(&m, (uchar *)sum);
rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type);
exit_cleanup(RERR_UNSUPPORTED);
}
close(fd);
unmap_file(buf);
}
| 164,643 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
(void) ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
(void) count;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: ...
CWE ID: CWE-125 | static Image *ReadSGIImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
SGIInfo
iris_info;
size_t
bytes_per_pixel,
quantum;
ssize_t
count,
y,
z;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SGI raster header.
*/
iris_info.magic=ReadBlobMSBShort(image);
do
{
/*
Verify SGI identifier.
*/
if (iris_info.magic != 0x01DA)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.storage=(unsigned char) ReadBlobByte(image);
switch (iris_info.storage)
{
case 0x00: image->compression=NoCompression; break;
case 0x01: image->compression=RLECompression; break;
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
iris_info.bytes_per_pixel=(unsigned char) ReadBlobByte(image);
if ((iris_info.bytes_per_pixel == 0) || (iris_info.bytes_per_pixel > 2))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.dimension=ReadBlobMSBShort(image);
iris_info.columns=ReadBlobMSBShort(image);
iris_info.rows=ReadBlobMSBShort(image);
iris_info.depth=ReadBlobMSBShort(image);
if ((iris_info.depth == 0) || (iris_info.depth > 4))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.minimum_value=ReadBlobMSBLong(image);
iris_info.maximum_value=ReadBlobMSBLong(image);
iris_info.sans=ReadBlobMSBLong(image);
count=ReadBlob(image,sizeof(iris_info.name),(unsigned char *)
iris_info.name);
if (count != sizeof(iris_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
iris_info.name[sizeof(iris_info.name)-1]='\0';
if (*iris_info.name != '\0')
(void) SetImageProperty(image,"label",iris_info.name,exception);
iris_info.pixel_format=ReadBlobMSBLong(image);
if (iris_info.pixel_format != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,sizeof(iris_info.filler),iris_info.filler);
if (count != sizeof(iris_info.filler))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=iris_info.columns;
image->rows=iris_info.rows;
image->depth=(size_t) MagickMin(iris_info.depth,MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.pixel_format == 0)
image->depth=(size_t) MagickMin((size_t) 8*iris_info.bytes_per_pixel,
MAGICKCORE_QUANTUM_DEPTH);
if (iris_info.depth < 3)
{
image->storage_class=PseudoClass;
image->colors=iris_info.bytes_per_pixel > 1 ? 65535 : 256;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Allocate SGI pixels.
*/
bytes_per_pixel=(size_t) iris_info.bytes_per_pixel;
number_pixels=(MagickSizeType) iris_info.columns*iris_info.rows;
if ((4*bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t)
(4*bytes_per_pixel*number_pixels)))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(iris_info.columns,iris_info.rows*4*
bytes_per_pixel*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((int) iris_info.storage != 0x01)
{
unsigned char
*scanline;
/*
Read standard image format.
*/
scanline=(unsigned char *) AcquireQuantumMemory(iris_info.columns,
bytes_per_pixel*sizeof(*scanline));
if (scanline == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels+bytes_per_pixel*z;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
count=ReadBlob(image,bytes_per_pixel*iris_info.columns,scanline);
if (EOFBlob(image) != MagickFalse)
break;
if (bytes_per_pixel == 2)
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[2*x];
*(p+1)=scanline[2*x+1];
p+=8;
}
else
for (x=0; x < (ssize_t) iris_info.columns; x++)
{
*p=scanline[x];
p+=4;
}
}
}
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
}
else
{
MemoryInfo
*packet_info;
size_t
*runlength;
ssize_t
offset,
*offsets;
unsigned char
*packets;
unsigned int
data_order;
/*
Read runlength-encoded image format.
*/
offsets=(ssize_t *) AcquireQuantumMemory((size_t) iris_info.rows,
iris_info.depth*sizeof(*offsets));
runlength=(size_t *) AcquireQuantumMemory(iris_info.rows,
iris_info.depth*sizeof(*runlength));
packet_info=AcquireVirtualMemory((size_t) iris_info.columns+10UL,4UL*
sizeof(*packets));
if ((offsets == (ssize_t *) NULL) ||
(runlength == (size_t *) NULL) ||
(packet_info == (MemoryInfo *) NULL))
{
if (offsets == (ssize_t *) NULL)
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
if (runlength == (size_t *) NULL)
runlength=(size_t *) RelinquishMagickMemory(runlength);
if (packet_info == (MemoryInfo *) NULL)
packet_info=RelinquishVirtualMemory(packet_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
packets=(unsigned char *) GetVirtualMemoryBlob(packet_info);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
offsets[i]=ReadBlobMSBSignedLong(image);
for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++)
{
runlength[i]=ReadBlobMSBLong(image);
if (runlength[i] > (4*(size_t) iris_info.columns+10))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Check data order.
*/
offset=0;
data_order=0;
for (y=0; ((y < (ssize_t) iris_info.rows) && (data_order == 0)); y++)
for (z=0; ((z < (ssize_t) iris_info.depth) && (data_order == 0)); z++)
{
if (offsets[y+z*iris_info.rows] < offset)
data_order=1;
offset=offsets[y+z*iris_info.rows];
}
offset=(ssize_t) TellBlob(image);
if (data_order == 1)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
p+=(iris_info.columns*4*bytes_per_pixel);
}
}
}
else
{
MagickOffsetType
position;
position=TellBlob(image);
p=pixels;
for (y=0; y < (ssize_t) iris_info.rows; y++)
{
for (z=0; z < (ssize_t) iris_info.depth; z++)
{
if (offset != offsets[y+z*iris_info.rows])
{
offset=offsets[y+z*iris_info.rows];
offset=(ssize_t) SeekBlob(image,(ssize_t) offset,SEEK_SET);
}
count=ReadBlob(image,(size_t) runlength[y+z*iris_info.rows],
packets);
if (EOFBlob(image) != MagickFalse)
break;
offset+=(ssize_t) runlength[y+z*iris_info.rows];
status=SGIDecode(bytes_per_pixel,(ssize_t)
(runlength[y+z*iris_info.rows]/bytes_per_pixel),packets,
1L*iris_info.columns,p+bytes_per_pixel*z);
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
p+=(iris_info.columns*4*bytes_per_pixel);
}
offset=(ssize_t) SeekBlob(image,position,SEEK_SET);
}
packet_info=RelinquishVirtualMemory(packet_info);
runlength=(size_t *) RelinquishMagickMemory(runlength);
offsets=(ssize_t *) RelinquishMagickMemory(offsets);
}
/*
Initialize image structure.
*/
image->alpha_trait=iris_info.depth == 4 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=iris_info.columns;
image->rows=iris_info.rows;
/*
Convert SGI raster image to pixel packets.
*/
if (image->storage_class == DirectClass)
{
/*
Convert SGI image to DirectClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleShortToQuantum((unsigned short)
((*(p+0) << 8) | (*(p+1)))),q);
SetPixelGreen(image,ScaleShortToQuantum((unsigned short)
((*(p+2) << 8) | (*(p+3)))),q);
SetPixelBlue(image,ScaleShortToQuantum((unsigned short)
((*(p+4) << 8) | (*(p+5)))),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleShortToQuantum((unsigned short)
((*(p+6) << 8) | (*(p+7)))),q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
SetPixelGreen(image,ScaleCharToQuantum(*(p+1)),q);
SetPixelBlue(image,ScaleCharToQuantum(*(p+2)),q);
SetPixelAlpha(image,OpaqueAlpha,q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*(p+3)),q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create grayscale map.
*/
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert SGI image to PseudoClass pixel packets.
*/
if (bytes_per_pixel == 2)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*8*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
quantum=(*p << 8);
quantum|=(*(p+1));
SetPixelIndex(image,(Quantum) quantum,q);
p+=8;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
else
for (y=0; y < (ssize_t) image->rows; y++)
{
p=pixels+(image->rows-y-1)*4*image->columns;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p,q);
p+=4;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image,exception);
}
pixel_info=RelinquishVirtualMemory(pixel_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
iris_info.magic=ReadBlobMSBShort(image);
if (iris_info.magic == 0x01DA)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (iris_info.magic == 0x01DA);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 170,119 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void update_rate_histogram(struct rate_hist *hist,
const vpx_codec_enc_cfg_t *cfg,
const vpx_codec_cx_pkt_t *pkt) {
int i;
int64_t then = 0;
int64_t avg_bitrate = 0;
int64_t sum_sz = 0;
const int64_t now = pkt->data.frame.pts * 1000 *
(uint64_t)cfg->g_timebase.num /
(uint64_t)cfg->g_timebase.den;
int idx = hist->frames++ % hist->samples;
hist->pts[idx] = now;
hist->sz[idx] = (int)pkt->data.frame.sz;
if (now < cfg->rc_buf_initial_sz)
return;
then = now;
/* Sum the size over the past rc_buf_sz ms */
for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
const int i_idx = (i - 1) % hist->samples;
then = hist->pts[i_idx];
if (now - then > cfg->rc_buf_sz)
break;
sum_sz += hist->sz[i_idx];
}
if (now == then)
return;
avg_bitrate = sum_sz * 8 * 1000 / (now - then);
idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
if (idx < 0)
idx = 0;
if (idx > RATE_BINS - 1)
idx = RATE_BINS - 1;
if (hist->bucket[idx].low > avg_bitrate)
hist->bucket[idx].low = (int)avg_bitrate;
if (hist->bucket[idx].high < avg_bitrate)
hist->bucket[idx].high = (int)avg_bitrate;
hist->bucket[idx].count++;
hist->total++;
}
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 update_rate_histogram(struct rate_hist *hist,
const vpx_codec_enc_cfg_t *cfg,
const vpx_codec_cx_pkt_t *pkt) {
int i;
int64_t then = 0;
int64_t avg_bitrate = 0;
int64_t sum_sz = 0;
const int64_t now = pkt->data.frame.pts * 1000 *
(uint64_t)cfg->g_timebase.num /
(uint64_t)cfg->g_timebase.den;
int idx = hist->frames++ % hist->samples;
hist->pts[idx] = now;
hist->sz[idx] = (int)pkt->data.frame.sz;
if (now < cfg->rc_buf_initial_sz)
return;
if (!cfg->rc_target_bitrate)
return;
then = now;
/* Sum the size over the past rc_buf_sz ms */
for (i = hist->frames; i > 0 && hist->frames - i < hist->samples; i--) {
const int i_idx = (i - 1) % hist->samples;
then = hist->pts[i_idx];
if (now - then > cfg->rc_buf_sz)
break;
sum_sz += hist->sz[i_idx];
}
if (now == then)
return;
avg_bitrate = sum_sz * 8 * 1000 / (now - then);
idx = (int)(avg_bitrate * (RATE_BINS / 2) / (cfg->rc_target_bitrate * 1000));
if (idx < 0)
idx = 0;
if (idx > RATE_BINS - 1)
idx = RATE_BINS - 1;
if (hist->bucket[idx].low > avg_bitrate)
hist->bucket[idx].low = (int)avg_bitrate;
if (hist->bucket[idx].high < avg_bitrate)
hist->bucket[idx].high = (int)avg_bitrate;
hist->bucket[idx].count++;
hist->total++;
}
| 174,500 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XpmCreateDataFromXpmImage(
char ***data_return,
XpmImage *image,
XpmInfo *info)
{
/* calculation variables */
int ErrorStatus;
char buf[BUFSIZ];
char **header = NULL, **data, **sptr, **sptr2, *s;
unsigned int header_size, header_nlines;
unsigned int data_size, data_nlines;
unsigned int extensions = 0, ext_size = 0, ext_nlines = 0;
unsigned int offset, l, n;
*data_return = NULL;
extensions = info && (info->valuemask & XpmExtensions)
&& info->nextensions;
/* compute the number of extensions lines and size */
if (extensions)
CountExtensions(info->extensions, info->nextensions,
&ext_size, &ext_nlines);
/*
* alloc a temporary array of char pointer for the header section which
*/
header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */
/* 2nd check superfluous if we do not need header_nlines any further */
if(header_nlines <= image->ncolors ||
header_nlines >= UINT_MAX / sizeof(char *))
return(XpmNoMemory);
header_size = sizeof(char *) * header_nlines;
if (header_size >= UINT_MAX / sizeof(char *))
return (XpmNoMemory);
header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */
if (!header)
return (XpmNoMemory);
/* print the hints line */
s = buf;
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, "%d %d %d %d", image->width, image->height,
image->ncolors, image->cpp);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
if (info && (info->valuemask & XpmHotspot)) {
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, " %d %d", info->x_hotspot, info->y_hotspot);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
}
if (extensions) {
strcpy(s, " XPMEXT");
s += 7;
}
l = s - buf + 1;
*header = (char *) XpmMalloc(l);
if (!*header)
RETURN(XpmNoMemory);
header_size += l;
strcpy(*header, buf);
/* print colors */
ErrorStatus = CreateColors(header + 1, &header_size,
image->colorTable, image->ncolors, image->cpp);
if (ErrorStatus != XpmSuccess)
RETURN(ErrorStatus);
/* now we know the size needed, alloc the data and copy the header lines */
offset = image->width * image->cpp + 1;
if(offset <= image->width || offset <= image->cpp)
if(offset <= image->width || offset <= image->cpp)
RETURN(XpmNoMemory);
if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *))
RETURN(XpmNoMemory);
data_size = (image->height + ext_nlines) * sizeof(char *);
RETURN(XpmNoMemory);
data_size += image->height * offset;
RETURN(XpmNoMemory);
data_size += image->height * offset;
if( (header_size + ext_size) >= (UINT_MAX - data_size) )
RETURN(XpmNoMemory);
data_size += header_size + ext_size;
data_nlines = header_nlines + image->height + ext_nlines;
*data = (char *) (data + data_nlines);
/* can header have less elements then n suggests? */
n = image->ncolors;
for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) {
strcpy(*sptr, *sptr2);
*(sptr + 1) = *sptr + strlen(*sptr2) + 1;
}
/* print pixels */
data[header_nlines] = (char *) data + header_size
+ (image->height + ext_nlines) * sizeof(char *);
CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height,
image->cpp, image->data, image->colorTable);
/* print extensions */
if (extensions)
CreateExtensions(data + header_nlines + image->height - 1,
data_size - header_nlines - image->height + 1, offset,
info->extensions, info->nextensions,
ext_nlines);
*data_return = data;
ErrorStatus = XpmSuccess;
/* exit point, free only locally allocated variables */
exit:
if (header) {
for (l = 0; l < header_nlines; l++)
if (header[l])
XpmFree(header[l]);
XpmFree(header);
}
return(ErrorStatus);
}
Commit Message:
CWE ID: CWE-787 | XpmCreateDataFromXpmImage(
char ***data_return,
XpmImage *image,
XpmInfo *info)
{
/* calculation variables */
int ErrorStatus;
char buf[BUFSIZ];
char **header = NULL, **data, **sptr, **sptr2, *s;
unsigned int header_size, header_nlines;
unsigned int data_size, data_nlines;
unsigned int extensions = 0, ext_size = 0, ext_nlines = 0;
unsigned int offset, l, n;
*data_return = NULL;
extensions = info && (info->valuemask & XpmExtensions)
&& info->nextensions;
/* compute the number of extensions lines and size */
if (extensions)
if (CountExtensions(info->extensions, info->nextensions,
&ext_size, &ext_nlines))
return(XpmNoMemory);
/*
* alloc a temporary array of char pointer for the header section which
*/
header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */
/* 2nd check superfluous if we do not need header_nlines any further */
if(header_nlines <= image->ncolors ||
header_nlines >= UINT_MAX / sizeof(char *))
return(XpmNoMemory);
header_size = sizeof(char *) * header_nlines;
if (header_size >= UINT_MAX / sizeof(char *))
return (XpmNoMemory);
header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */
if (!header)
return (XpmNoMemory);
/* print the hints line */
s = buf;
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, "%d %d %d %d", image->width, image->height,
image->ncolors, image->cpp);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
if (info && (info->valuemask & XpmHotspot)) {
#ifndef VOID_SPRINTF
s +=
#endif
sprintf(s, " %d %d", info->x_hotspot, info->y_hotspot);
#ifdef VOID_SPRINTF
s += strlen(s);
#endif
}
if (extensions) {
strcpy(s, " XPMEXT");
s += 7;
}
l = s - buf + 1;
*header = (char *) XpmMalloc(l);
if (!*header)
RETURN(XpmNoMemory);
header_size += l;
strcpy(*header, buf);
/* print colors */
ErrorStatus = CreateColors(header + 1, &header_size,
image->colorTable, image->ncolors, image->cpp);
if (ErrorStatus != XpmSuccess)
RETURN(ErrorStatus);
/* now we know the size needed, alloc the data and copy the header lines */
offset = image->width * image->cpp + 1;
if(offset <= image->width || offset <= image->cpp)
if(offset <= image->width || offset <= image->cpp)
RETURN(XpmNoMemory);
if (image->height > UINT_MAX - ext_nlines ||
image->height + ext_nlines >= UINT_MAX / sizeof(char *))
RETURN(XpmNoMemory);
data_size = (image->height + ext_nlines) * sizeof(char *);
RETURN(XpmNoMemory);
data_size += image->height * offset;
RETURN(XpmNoMemory);
data_size += image->height * offset;
if (header_size > UINT_MAX - ext_size ||
header_size + ext_size >= (UINT_MAX - data_size) )
RETURN(XpmNoMemory);
data_size += header_size + ext_size;
data_nlines = header_nlines + image->height + ext_nlines;
*data = (char *) (data + data_nlines);
/* can header have less elements then n suggests? */
n = image->ncolors;
for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) {
strcpy(*sptr, *sptr2);
*(sptr + 1) = *sptr + strlen(*sptr2) + 1;
}
/* print pixels */
data[header_nlines] = (char *) data + header_size
+ (image->height + ext_nlines) * sizeof(char *);
CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height,
image->cpp, image->data, image->colorTable);
/* print extensions */
if (extensions)
CreateExtensions(data + header_nlines + image->height - 1,
data_size - header_nlines - image->height + 1, offset,
info->extensions, info->nextensions,
ext_nlines);
*data_return = data;
ErrorStatus = XpmSuccess;
/* exit point, free only locally allocated variables */
exit:
if (header) {
for (l = 0; l < header_nlines; l++)
if (header[l])
XpmFree(header[l]);
XpmFree(header);
}
return(ErrorStatus);
}
| 165,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool CSPSource::schemeMatches(const KURL& url) const
{
if (m_scheme.isEmpty())
return m_policy->protocolMatchesSelf(url);
return equalIgnoringCase(url.protocol(), m_scheme);
}
Commit Message: CSP: Source expressions can no longer lock sites into insecurity.
CSP's matching algorithm has been updated to make clever folks like Yan
slightly less able to gather data on user's behavior based on CSP
reports[1]. This matches Firefox's existing behavior (they apparently
changed this behavior a few months ago, via a happy accident[2]), and
mitigates the CSP-variant of Sniffly[3].
On the dashboard at https://www.chromestatus.com/feature/6653486812889088.
[1]: https://github.com/w3c/webappsec-csp/commit/0e81d81b64c42ca3c81c048161162b9697ff7b60
[2]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218524#c2
[3]: https://bugzilla.mozilla.org/show_bug.cgi?id=1218778#c7
BUG=544765,558232
Review URL: https://codereview.chromium.org/1455973003
Cr-Commit-Position: refs/heads/master@{#360562}
CWE ID: CWE-200 | bool CSPSource::schemeMatches(const KURL& url) const
{
if (m_scheme.isEmpty())
return m_policy->protocolMatchesSelf(url);
if (equalIgnoringCase(m_scheme, "http"))
return equalIgnoringCase(url.protocol(), "http") || equalIgnoringCase(url.protocol(), "https");
if (equalIgnoringCase(m_scheme, "ws"))
return equalIgnoringCase(url.protocol(), "ws") || equalIgnoringCase(url.protocol(), "wss");
return equalIgnoringCase(url.protocol(), m_scheme);
}
| 172,237 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "w");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
Commit Message: ccpp: open file for dump_fd_info with O_EXCL
To avoid possible races.
Related: #1211835
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-59 | static bool dump_fd_info(const char *dest_filename, char *source_filename, int source_base_ofs, uid_t uid, gid_t gid)
{
FILE *fp = fopen(dest_filename, "wx");
if (!fp)
return false;
unsigned fd = 0;
while (fd <= 99999) /* paranoia check */
{
sprintf(source_filename + source_base_ofs, "fd/%u", fd);
char *name = malloc_readlink(source_filename);
if (!name)
break;
fprintf(fp, "%u:%s\n", fd, name);
free(name);
sprintf(source_filename + source_base_ofs, "fdinfo/%u", fd);
fd++;
FILE *in = fopen(source_filename, "r");
if (!in)
continue;
char buf[128];
while (fgets(buf, sizeof(buf)-1, in))
{
/* in case the line is not terminated, terminate it */
char *eol = strchrnul(buf, '\n');
eol[0] = '\n';
eol[1] = '\0';
fputs(buf, fp);
}
fclose(in);
}
const int dest_fd = fileno(fp);
if (fchown(dest_fd, uid, gid) < 0)
{
perror_msg("Can't change '%s' ownership to %lu:%lu", dest_filename, (long)uid, (long)gid);
fclose(fp);
unlink(dest_filename);
return false;
}
fclose(fp);
return true;
}
| 170,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintRenderFrameHelper::CopyMetafileDataToSharedMem(
const PdfMetafileSkia& metafile,
base::SharedMemoryHandle* shared_mem_handle) {
uint32_t buf_size = metafile.GetDataSize();
if (buf_size == 0)
return false;
std::unique_ptr<base::SharedMemory> shared_buf(
content::RenderThread::Get()->HostAllocateSharedMemoryBuffer(buf_size));
if (!shared_buf)
return false;
if (!shared_buf->Map(buf_size))
return false;
if (!metafile.GetData(shared_buf->memory(), buf_size))
return false;
*shared_mem_handle =
base::SharedMemory::DuplicateHandle(shared_buf->handle());
return true;
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | bool PrintRenderFrameHelper::CopyMetafileDataToSharedMem(
bool PrintRenderFrameHelper::CopyMetafileDataToReadOnlySharedMem(
const PdfMetafileSkia& metafile,
base::SharedMemoryHandle* shared_mem_handle) {
uint32_t buf_size = metafile.GetDataSize();
if (buf_size == 0)
return false;
mojo::ScopedSharedBufferHandle buffer =
mojo::SharedBufferHandle::Create(buf_size);
if (!buffer.is_valid())
return false;
mojo::ScopedSharedBufferMapping mapping = buffer->Map(buf_size);
if (!mapping)
return false;
if (!metafile.GetData(mapping.get(), buf_size))
return false;
MojoResult result = mojo::UnwrapSharedMemoryHandle(
buffer->Clone(mojo::SharedBufferHandle::AccessMode::READ_ONLY),
shared_mem_handle, nullptr, nullptr);
DCHECK_EQ(MOJO_RESULT_OK, result);
return true;
}
| 172,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyStereo24(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyStereo24(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
*dst++ = src[1][i] >> 8;
}
}
| 174,022 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: media::mojom::VideoFrameDataPtr MakeVideoFrameData(
const scoped_refptr<media::VideoFrame>& input) {
if (input->metadata()->IsTrue(media::VideoFrameMetadata::END_OF_STREAM)) {
return media::mojom::VideoFrameData::NewEosData(
media::mojom::EosVideoFrameData::New());
}
if (input->storage_type() == media::VideoFrame::STORAGE_MOJO_SHARED_BUFFER) {
media::MojoSharedBufferVideoFrame* mojo_frame =
static_cast<media::MojoSharedBufferVideoFrame*>(input.get());
mojo::ScopedSharedBufferHandle dup = mojo_frame->Handle().Clone(
mojo::SharedBufferHandle::AccessMode::READ_ONLY);
DCHECK(dup.is_valid());
return media::mojom::VideoFrameData::NewSharedBufferData(
media::mojom::SharedBufferVideoFrameData::New(
std::move(dup), mojo_frame->MappedSize(),
mojo_frame->stride(media::VideoFrame::kYPlane),
mojo_frame->stride(media::VideoFrame::kUPlane),
mojo_frame->stride(media::VideoFrame::kVPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kYPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kUPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kVPlane)));
}
if (input->HasTextures()) {
std::vector<gpu::MailboxHolder> mailbox_holder(
media::VideoFrame::kMaxPlanes);
size_t num_planes = media::VideoFrame::NumPlanes(input->format());
for (size_t i = 0; i < num_planes; i++)
mailbox_holder[i] = input->mailbox_holder(i);
return media::mojom::VideoFrameData::NewMailboxData(
media::mojom::MailboxVideoFrameData::New(std::move(mailbox_holder)));
}
NOTREACHED() << "Unsupported VideoFrame conversion";
return nullptr;
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | media::mojom::VideoFrameDataPtr MakeVideoFrameData(
const scoped_refptr<media::VideoFrame>& input) {
if (input->metadata()->IsTrue(media::VideoFrameMetadata::END_OF_STREAM)) {
return media::mojom::VideoFrameData::NewEosData(
media::mojom::EosVideoFrameData::New());
}
if (input->storage_type() == media::VideoFrame::STORAGE_MOJO_SHARED_BUFFER) {
media::MojoSharedBufferVideoFrame* mojo_frame =
static_cast<media::MojoSharedBufferVideoFrame*>(input.get());
// TODO(https://crbug.com/803136): This should duplicate as READ_ONLY, but
// can't because there is no guarantee that the input handle is sharable as
// read-only.
mojo::ScopedSharedBufferHandle dup = mojo_frame->Handle().Clone(
mojo::SharedBufferHandle::AccessMode::READ_WRITE);
DCHECK(dup.is_valid());
return media::mojom::VideoFrameData::NewSharedBufferData(
media::mojom::SharedBufferVideoFrameData::New(
std::move(dup), mojo_frame->MappedSize(),
mojo_frame->stride(media::VideoFrame::kYPlane),
mojo_frame->stride(media::VideoFrame::kUPlane),
mojo_frame->stride(media::VideoFrame::kVPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kYPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kUPlane),
mojo_frame->PlaneOffset(media::VideoFrame::kVPlane)));
}
if (input->HasTextures()) {
std::vector<gpu::MailboxHolder> mailbox_holder(
media::VideoFrame::kMaxPlanes);
size_t num_planes = media::VideoFrame::NumPlanes(input->format());
for (size_t i = 0; i < num_planes; i++)
mailbox_holder[i] = input->mailbox_holder(i);
return media::mojom::VideoFrameData::NewMailboxData(
media::mojom::MailboxVideoFrameData::New(std::move(mailbox_holder)));
}
NOTREACHED() << "Unsupported VideoFrame conversion";
return nullptr;
}
| 172,876 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigationController::RendererDidNavigate(
const ViewHostMsg_FrameNavigate_Params& params,
int extra_invalidate_flags,
LoadCommittedDetails* details) {
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->url();
details->previous_entry_index = last_committed_entry_index();
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
if (pending_entry_index_ >= 0 && !pending_entry_->site_instance()) {
DCHECK(pending_entry_->restore_type() != NavigationEntry::RESTORE_NONE);
pending_entry_->set_site_instance(tab_contents_->GetSiteInstance());
pending_entry_->set_restore_type(NavigationEntry::RESTORE_NONE);
}
details->is_in_page = IsURLInPageNavigation(params.url);
details->type = ClassifyNavigation(params);
switch (details->type) {
case NavigationType::NEW_PAGE:
RendererDidNavigateToNewPage(params, &(details->did_replace_entry));
break;
case NavigationType::EXISTING_PAGE:
RendererDidNavigateToExistingPage(params);
break;
case NavigationType::SAME_PAGE:
RendererDidNavigateToSamePage(params);
break;
case NavigationType::IN_PAGE:
RendererDidNavigateInPage(params, &(details->did_replace_entry));
break;
case NavigationType::NEW_SUBFRAME:
RendererDidNavigateNewSubframe(params);
break;
case NavigationType::AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(params))
return false;
break;
case NavigationType::NAV_IGNORE:
return false;
default:
NOTREACHED();
}
DCHECK(!params.content_state.empty());
NavigationEntry* active_entry = GetActiveEntry();
active_entry->set_content_state(params.content_state);
DCHECK(active_entry->site_instance() == tab_contents_->GetSiteInstance());
details->is_auto = (PageTransition::IsRedirect(params.transition) &&
!pending_entry()) ||
params.gesture == NavigationGestureAuto;
details->entry = active_entry;
details->is_main_frame = PageTransition::IsMainFrame(params.transition);
details->serialized_security_info = params.security_info;
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details, extra_invalidate_flags);
return true;
}
Commit Message: Ensure URL is updated after a cross-site navigation is pre-empted by
an "ignored" navigation.
BUG=77507
TEST=NavigationControllerTest.LoadURL_IgnorePreemptsPending
Review URL: http://codereview.chromium.org/6826015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@81307 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool NavigationController::RendererDidNavigate(
const ViewHostMsg_FrameNavigate_Params& params,
int extra_invalidate_flags,
LoadCommittedDetails* details) {
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->url();
details->previous_entry_index = last_committed_entry_index();
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
if (pending_entry_index_ >= 0 && !pending_entry_->site_instance()) {
DCHECK(pending_entry_->restore_type() != NavigationEntry::RESTORE_NONE);
pending_entry_->set_site_instance(tab_contents_->GetSiteInstance());
pending_entry_->set_restore_type(NavigationEntry::RESTORE_NONE);
}
details->is_in_page = IsURLInPageNavigation(params.url);
details->type = ClassifyNavigation(params);
switch (details->type) {
case NavigationType::NEW_PAGE:
RendererDidNavigateToNewPage(params, &(details->did_replace_entry));
break;
case NavigationType::EXISTING_PAGE:
RendererDidNavigateToExistingPage(params);
break;
case NavigationType::SAME_PAGE:
RendererDidNavigateToSamePage(params);
break;
case NavigationType::IN_PAGE:
RendererDidNavigateInPage(params, &(details->did_replace_entry));
break;
case NavigationType::NEW_SUBFRAME:
RendererDidNavigateNewSubframe(params);
break;
case NavigationType::AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(params))
return false;
break;
case NavigationType::NAV_IGNORE:
// If a pending navigation was in progress, this canceled it. We should
// discard it and make sure it is removed from the URL bar. After that,
// there is nothing we can do with this navigation, so we just return to
if (pending_entry_) {
DiscardNonCommittedEntries();
extra_invalidate_flags |= TabContents::INVALIDATE_URL;
tab_contents_->NotifyNavigationStateChanged(extra_invalidate_flags);
}
return false;
default:
NOTREACHED();
}
DCHECK(!params.content_state.empty());
NavigationEntry* active_entry = GetActiveEntry();
active_entry->set_content_state(params.content_state);
DCHECK(active_entry->site_instance() == tab_contents_->GetSiteInstance());
details->is_auto = (PageTransition::IsRedirect(params.transition) &&
!pending_entry()) ||
params.gesture == NavigationGestureAuto;
details->entry = active_entry;
details->is_main_frame = PageTransition::IsMainFrame(params.transition);
details->serialized_security_info = params.security_info;
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details, extra_invalidate_flags);
return true;
}
| 170,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[])
{
time_t timep;
struct tm *timeptr;
char *now;
if (argc < 3) {
send_error(1);
return -1;
} else if (argc > 3) {
send_error(5);
return -1;
}
build_needs_escape();
if (argv[2] == NULL)
index_directory(argv[1], argv[1]);
else
index_directory(argv[1], argv[2]);
time(&timep);
#ifdef USE_LOCALTIME
timeptr = localtime(&timep);
#else
timeptr = gmtime(&timep);
#endif
now = strdup(asctime(timeptr));
now[strlen(now) - 1] = '\0';
#ifdef USE_LOCALTIME
printf("</table>\n<hr noshade>\nIndex generated %s %s\n"
"<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n"
"</body>\n</html>\n", now, TIMEZONE(timeptr));
#else
printf("</table>\n<hr noshade>\nIndex generated %s UTC\n"
"<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n"
"</body>\n</html>\n", now);
#endif
return 0;
}
Commit Message: misc oom and possible memory leak fix
CWE ID: | int main(int argc, char *argv[])
{
time_t timep;
struct tm *timeptr;
char *now;
if (argc < 3) {
send_error(1);
return -1;
} else if (argc > 3) {
send_error(5);
return -1;
}
build_needs_escape();
if (argv[2] == NULL)
index_directory(argv[1], argv[1]);
else
index_directory(argv[1], argv[2]);
time(&timep);
#ifdef USE_LOCALTIME
timeptr = localtime(&timep);
#else
timeptr = gmtime(&timep);
#endif
now = strdup(asctime(timeptr));
if (!now) {
return -1;
}
now[strlen(now) - 1] = '\0';
#ifdef USE_LOCALTIME
printf("</table>\n<hr noshade>\nIndex generated %s %s\n"
"<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n"
"</body>\n</html>\n", now, TIMEZONE(timeptr));
#else
printf("</table>\n<hr noshade>\nIndex generated %s UTC\n"
"<!-- This program is part of the Boa Webserver Copyright (C) 1991-2002 http://www.boa.org -->\n"
"</body>\n</html>\n", now);
#endif
free(now);
return 0;
}
| 169,756 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.