instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_siocgstamp(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timeval ktv;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv);
set_fs(old_fs);
if (!err)
err = compat_put_timeval(up, &ktv);
return err;
}
Commit Message: Fix order of arguments to compat_put_time[spec|val]
Commit 644595f89620 ("compat: Handle COMPAT_USE_64BIT_TIME in
net/socket.c") introduced a bug where the helper functions to take
either a 64-bit or compat time[spec|val] got the arguments in the wrong
order, passing the kernel stack pointer off as a user pointer (and vice
versa).
Because of the user address range check, that in turn then causes an
EFAULT due to the user pointer range checking failing for the kernel
address. Incorrectly resuling in a failed system call for 32-bit
processes with a 64-bit kernel.
On odder architectures like HP-PA (with separate user/kernel address
spaces), it can be used read kernel memory.
Signed-off-by: Mikulas Patocka <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static int do_siocgstamp(struct net *net, struct socket *sock,
unsigned int cmd, void __user *up)
{
mm_segment_t old_fs = get_fs();
struct timeval ktv;
int err;
set_fs(KERNEL_DS);
err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv);
set_fs(old_fs);
if (!err)
err = compat_put_timeval(&ktv, up);
return err;
}
| 165,536 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool on_accept(private_stroke_socket_t *this, stream_t *stream)
{
stroke_msg_t *msg;
uint16_t len;
FILE *out;
/* read length */
if (!stream->read_all(stream, &len, sizeof(len)))
{
if (errno != EWOULDBLOCK)
{
DBG1(DBG_CFG, "reading length of stroke message failed: %s",
strerror(errno));
}
return FALSE;
}
/* read message (we need an additional byte to terminate the buffer) */
msg = malloc(len + 1);
DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno));
}
Commit Message:
CWE ID: CWE-787 | static bool on_accept(private_stroke_socket_t *this, stream_t *stream)
{
stroke_msg_t *msg;
uint16_t len;
FILE *out;
/* read length */
if (!stream->read_all(stream, &len, sizeof(len)))
{
if (errno != EWOULDBLOCK)
{
DBG1(DBG_CFG, "reading length of stroke message failed: %s",
strerror(errno));
}
return FALSE;
}
if (len < offsetof(stroke_msg_t, buffer))
{
DBG1(DBG_CFG, "invalid stroke message length %d", len);
return FALSE;
}
/* read message (we need an additional byte to terminate the buffer) */
msg = malloc(len + 1);
DBG1(DBG_CFG, "reading stroke message failed: %s", strerror(errno));
}
| 165,152 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssh_session(void)
{
int type;
int interactive = 0;
int have_tty = 0;
struct winsize ws;
char *cp;
const char *display;
/* Enable compression if requested. */
if (options.compression) {
options.compression_level);
if (options.compression_level < 1 ||
options.compression_level > 9)
fatal("Compression level must be from 1 (fast) to "
"9 (slow, best).");
/* Send the request. */
packet_start(SSH_CMSG_REQUEST_COMPRESSION);
packet_put_int(options.compression_level);
packet_send();
packet_write_wait();
type = packet_read();
if (type == SSH_SMSG_SUCCESS)
packet_start_compression(options.compression_level);
else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host refused compression.");
else
packet_disconnect("Protocol error waiting for "
"compression response.");
}
/* Allocate a pseudo tty if appropriate. */
if (tty_flag) {
debug("Requesting pty.");
/* Start the packet. */
packet_start(SSH_CMSG_REQUEST_PTY);
/* Store TERM in the packet. There is no limit on the
length of the string. */
cp = getenv("TERM");
if (!cp)
cp = "";
packet_put_cstring(cp);
/* Store window size in the packet. */
if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
memset(&ws, 0, sizeof(ws));
packet_put_int((u_int)ws.ws_row);
packet_put_int((u_int)ws.ws_col);
packet_put_int((u_int)ws.ws_xpixel);
packet_put_int((u_int)ws.ws_ypixel);
/* Store tty modes in the packet. */
tty_make_modes(fileno(stdin), NULL);
/* Send the packet, and wait for it to leave. */
packet_send();
packet_write_wait();
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
have_tty = 1;
} else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host failed or refused to "
"allocate a pseudo tty.");
else
packet_disconnect("Protocol error waiting for pty "
"request response.");
}
/* Request X11 forwarding if enabled and DISPLAY is set. */
display = getenv("DISPLAY");
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
if (options.forward_x11 && display != NULL) {
char *proto, *data;
/* Get reasonable local authentication information. */
client_x11_get_proto(display, options.xauth_location,
options.forward_x11_trusted,
options.forward_x11_timeout,
&proto, &data);
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
x11_request_forwarding_with_spoofing(0, display, proto,
data, 0);
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
} else if (type == SSH_SMSG_FAILURE) {
logit("Warning: Remote host denied X11 forwarding.");
} else {
packet_disconnect("Protocol error waiting for X11 "
"forwarding");
}
}
/* Tell the packet module whether this is an interactive session. */
packet_set_interactive(interactive,
options.ip_qos_interactive, options.ip_qos_bulk);
/* Request authentication agent forwarding if appropriate. */
check_agent_present();
if (options.forward_agent) {
debug("Requesting authentication agent forwarding.");
auth_request_forwarding();
/* Read response from the server. */
type = packet_read();
packet_check_eom();
if (type != SSH_SMSG_SUCCESS)
logit("Warning: Remote host denied authentication agent forwarding.");
}
/* Initiate port forwardings. */
ssh_init_stdio_forwarding();
ssh_init_forwarding();
/* Execute a local command */
if (options.local_command != NULL &&
options.permit_local_command)
ssh_local_cmd(options.local_command);
/*
* If requested and we are not interested in replies to remote
* forwarding requests, then let ssh continue in the background.
*/
if (fork_after_authentication_flag) {
if (options.exit_on_forward_failure &&
options.num_remote_forwards > 0) {
debug("deferring postauth fork until remote forward "
"confirmation received");
} else
fork_postauth();
}
/*
* If a command was specified on the command line, execute the
* command now. Otherwise request the server to start a shell.
*/
if (buffer_len(&command) > 0) {
int len = buffer_len(&command);
if (len > 900)
len = 900;
debug("Sending command: %.*s", len,
(u_char *)buffer_ptr(&command));
packet_start(SSH_CMSG_EXEC_CMD);
packet_put_string(buffer_ptr(&command), buffer_len(&command));
packet_send();
packet_write_wait();
} else {
debug("Requesting shell.");
packet_start(SSH_CMSG_EXEC_SHELL);
packet_send();
packet_write_wait();
}
/* Enter the interactive session. */
return client_loop(have_tty, tty_flag ?
options.escape_char : SSH_ESCAPECHAR_NONE, 0);
}
Commit Message:
CWE ID: CWE-254 | ssh_session(void)
{
int type;
int interactive = 0;
int have_tty = 0;
struct winsize ws;
char *cp;
const char *display;
char *proto = NULL, *data = NULL;
/* Enable compression if requested. */
if (options.compression) {
options.compression_level);
if (options.compression_level < 1 ||
options.compression_level > 9)
fatal("Compression level must be from 1 (fast) to "
"9 (slow, best).");
/* Send the request. */
packet_start(SSH_CMSG_REQUEST_COMPRESSION);
packet_put_int(options.compression_level);
packet_send();
packet_write_wait();
type = packet_read();
if (type == SSH_SMSG_SUCCESS)
packet_start_compression(options.compression_level);
else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host refused compression.");
else
packet_disconnect("Protocol error waiting for "
"compression response.");
}
/* Allocate a pseudo tty if appropriate. */
if (tty_flag) {
debug("Requesting pty.");
/* Start the packet. */
packet_start(SSH_CMSG_REQUEST_PTY);
/* Store TERM in the packet. There is no limit on the
length of the string. */
cp = getenv("TERM");
if (!cp)
cp = "";
packet_put_cstring(cp);
/* Store window size in the packet. */
if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
memset(&ws, 0, sizeof(ws));
packet_put_int((u_int)ws.ws_row);
packet_put_int((u_int)ws.ws_col);
packet_put_int((u_int)ws.ws_xpixel);
packet_put_int((u_int)ws.ws_ypixel);
/* Store tty modes in the packet. */
tty_make_modes(fileno(stdin), NULL);
/* Send the packet, and wait for it to leave. */
packet_send();
packet_write_wait();
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
have_tty = 1;
} else if (type == SSH_SMSG_FAILURE)
logit("Warning: Remote host failed or refused to "
"allocate a pseudo tty.");
else
packet_disconnect("Protocol error waiting for pty "
"request response.");
}
/* Request X11 forwarding if enabled and DISPLAY is set. */
display = getenv("DISPLAY");
display = getenv("DISPLAY");
if (display == NULL && options.forward_x11)
debug("X11 forwarding requested but DISPLAY not set");
if (options.forward_x11 && client_x11_get_proto(display,
options.xauth_location, options.forward_x11_trusted,
options.forward_x11_timeout, &proto, &data) == 0) {
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
/* Request forwarding with authentication spoofing. */
debug("Requesting X11 forwarding with authentication "
"spoofing.");
x11_request_forwarding_with_spoofing(0, display, proto,
data, 0);
/* Read response from the server. */
type = packet_read();
if (type == SSH_SMSG_SUCCESS) {
interactive = 1;
} else if (type == SSH_SMSG_FAILURE) {
logit("Warning: Remote host denied X11 forwarding.");
} else {
packet_disconnect("Protocol error waiting for X11 "
"forwarding");
}
}
/* Tell the packet module whether this is an interactive session. */
packet_set_interactive(interactive,
options.ip_qos_interactive, options.ip_qos_bulk);
/* Request authentication agent forwarding if appropriate. */
check_agent_present();
if (options.forward_agent) {
debug("Requesting authentication agent forwarding.");
auth_request_forwarding();
/* Read response from the server. */
type = packet_read();
packet_check_eom();
if (type != SSH_SMSG_SUCCESS)
logit("Warning: Remote host denied authentication agent forwarding.");
}
/* Initiate port forwardings. */
ssh_init_stdio_forwarding();
ssh_init_forwarding();
/* Execute a local command */
if (options.local_command != NULL &&
options.permit_local_command)
ssh_local_cmd(options.local_command);
/*
* If requested and we are not interested in replies to remote
* forwarding requests, then let ssh continue in the background.
*/
if (fork_after_authentication_flag) {
if (options.exit_on_forward_failure &&
options.num_remote_forwards > 0) {
debug("deferring postauth fork until remote forward "
"confirmation received");
} else
fork_postauth();
}
/*
* If a command was specified on the command line, execute the
* command now. Otherwise request the server to start a shell.
*/
if (buffer_len(&command) > 0) {
int len = buffer_len(&command);
if (len > 900)
len = 900;
debug("Sending command: %.*s", len,
(u_char *)buffer_ptr(&command));
packet_start(SSH_CMSG_EXEC_CMD);
packet_put_string(buffer_ptr(&command), buffer_len(&command));
packet_send();
packet_write_wait();
} else {
debug("Requesting shell.");
packet_start(SSH_CMSG_EXEC_SHELL);
packet_send();
packet_write_wait();
}
/* Enter the interactive session. */
return client_loop(have_tty, tty_flag ?
options.escape_char : SSH_ESCAPECHAR_NONE, 0);
}
| 165,353 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
Commit Message: Fix crash in anal.avr
CWE ID: CWE-125 | INST_HANDLER (lds) { // LDS Rd, k
if (len < 4) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
| 169,234 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_MAXSIZE_GEN];
#endif
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
ForceZero(buf, ECC_MAXSIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return err;
}
Commit Message: Change ECDSA signing to use blinding.
CWE ID: CWE-200 | static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order)
{
int err;
#ifdef WOLFSSL_SMALL_STACK
byte* buf;
#else
byte buf[ECC_MAXSIZE_GEN];
#endif
#ifdef WOLFSSL_SMALL_STACK
buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER);
if (buf == NULL)
return MEMORY_E;
#endif
/*generate 8 extra bytes to mitigate bias from the modulo operation below*/
/*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/
size += 8;
/* make up random string */
err = wc_RNG_GenerateBlock(rng, buf, size);
/* load random buffer data into k */
if (err == 0)
err = mp_read_unsigned_bin(k, (byte*)buf, size);
/* the key should be smaller than the order of base point */
if (err == MP_OKAY) {
if (mp_cmp(k, order) != MP_LT) {
err = mp_mod(k, order, k);
}
}
/* quick sanity check to make sure we're not dealing with a 0 key */
if (err == MP_OKAY) {
if (mp_iszero(k) == MP_YES)
err = MP_ZERO_E;
}
ForceZero(buf, ECC_MAXSIZE);
#ifdef WOLFSSL_SMALL_STACK
XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER);
#endif
return err;
}
| 169,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC)
{
size_t retlen;
char *ret;
enum entity_charset charset;
const entity_ht *inverse_map = NULL;
size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen);
if (all) {
charset = determine_charset(hint_charset TSRMLS_CC);
} else {
charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
}
/* don't use LIMIT_ALL! */
if (oldlen > new_size) {
/* overflow, refuse to do anything */
ret = estrndup((char*)old, oldlen);
retlen = oldlen;
goto empty_source;
}
ret = emalloc(new_size);
*ret = '\0';
retlen = oldlen;
if (retlen == 0) {
goto empty_source;
}
inverse_map = unescape_inverse_map(all, flags);
/* replace numeric entities */
traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset);
empty_source:
*newlen = retlen;
return ret;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_t *newlen, int all, int flags, char *hint_charset TSRMLS_DC)
{
size_t retlen;
char *ret;
enum entity_charset charset;
const entity_ht *inverse_map = NULL;
size_t new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen);
if (all) {
charset = determine_charset(hint_charset TSRMLS_CC);
} else {
charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
}
/* don't use LIMIT_ALL! */
if (oldlen > new_size) {
/* overflow, refuse to do anything */
ret = estrndup((char*)old, oldlen);
retlen = oldlen;
goto empty_source;
}
ret = emalloc(new_size);
*ret = '\0';
retlen = oldlen;
if (retlen == 0) {
goto empty_source;
}
inverse_map = unescape_inverse_map(all, flags);
/* replace numeric entities */
traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset);
empty_source:
*newlen = retlen;
return ret;
}
| 167,176 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ScrollAnchor::ExamineResult ScrollAnchor::Examine(
const LayoutObject* candidate) const {
if (candidate == ScrollerLayoutBox(scroller_))
return ExamineResult(kContinue);
if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone)
return ExamineResult(kSkip);
if (candidate->IsLayoutInline())
return ExamineResult(kContinue);
if (candidate->IsAnonymous())
return ExamineResult(kContinue);
if (!candidate->IsText() && !candidate->IsBox())
return ExamineResult(kSkip);
if (!CandidateMayMoveWithScroller(candidate, scroller_))
return ExamineResult(kSkip);
LayoutRect candidate_rect = RelativeBounds(candidate, scroller_);
LayoutRect visible_rect =
ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint());
bool occupies_space =
candidate_rect.Width() > 0 && candidate_rect.Height() > 0;
if (occupies_space && visible_rect.Intersects(candidate_rect)) {
return ExamineResult(
visible_rect.Contains(candidate_rect) ? kReturn : kConstrain,
CornerToAnchor(scroller_));
} else {
return ExamineResult(kSkip);
}
}
Commit Message: Consider scroll-padding when determining scroll anchor node
Scroll anchoring should not anchor to a node that is behind scroll
padding.
Bug: 1010002
Change-Id: Icbd89fb85ea2c97a6de635930a9896f6a87b8f07
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1887745
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Nick Burris <[email protected]>
Cr-Commit-Position: refs/heads/master@{#711020}
CWE ID: | ScrollAnchor::ExamineResult ScrollAnchor::Examine(
const LayoutObject* candidate) const {
if (candidate == ScrollerLayoutBox(scroller_))
return ExamineResult(kContinue);
if (candidate->StyleRef().OverflowAnchor() == EOverflowAnchor::kNone)
return ExamineResult(kSkip);
if (candidate->IsLayoutInline())
return ExamineResult(kContinue);
if (candidate->IsAnonymous())
return ExamineResult(kContinue);
if (!candidate->IsText() && !candidate->IsBox())
return ExamineResult(kSkip);
if (!CandidateMayMoveWithScroller(candidate, scroller_))
return ExamineResult(kSkip);
LayoutRect candidate_rect = RelativeBounds(candidate, scroller_);
LayoutRect visible_rect =
ScrollerLayoutBox(scroller_)->OverflowClipRect(LayoutPoint());
const ComputedStyle* style = ScrollerLayoutBox(scroller_)->Style();
LayoutRectOutsets scroll_padding(
MinimumValueForLength(style->ScrollPaddingTop(), visible_rect.Height()),
MinimumValueForLength(style->ScrollPaddingRight(), visible_rect.Width()),
MinimumValueForLength(style->ScrollPaddingBottom(),
visible_rect.Height()),
MinimumValueForLength(style->ScrollPaddingLeft(), visible_rect.Width()));
visible_rect.Contract(scroll_padding);
bool occupies_space =
candidate_rect.Width() > 0 && candidate_rect.Height() > 0;
if (occupies_space && visible_rect.Intersects(candidate_rect)) {
return ExamineResult(
visible_rect.Contains(candidate_rect) ? kReturn : kConstrain,
CornerToAnchor(scroller_));
} else {
return ExamineResult(kSkip);
}
}
| 172,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
(void)cid_parser_to_fixed_array( parser, 6, temp, 3 );
temp_scale = FT_ABS( temp[3] );
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
Commit Message:
CWE ID: CWE-20 | cid_parse_font_matrix( CID_Face face,
CID_Parser* parser )
{
CID_FaceDict dict;
FT_Face root = (FT_Face)&face->root;
FT_Fixed temp[6];
FT_Fixed temp_scale;
if ( parser->num_dict >= 0 && parser->num_dict < face->cid.num_dicts )
{
FT_Matrix* matrix;
FT_Vector* offset;
FT_Int result;
dict = face->cid.font_dicts + parser->num_dict;
matrix = &dict->font_matrix;
offset = &dict->font_offset;
result = cid_parser_to_fixed_array( parser, 6, temp, 3 );
if ( result < 6 )
return FT_THROW( Invalid_File_Format );
temp_scale = FT_ABS( temp[3] );
if ( temp_scale == 0 )
{
FT_ERROR(( "cid_parse_font_matrix: invalid font matrix\n" ));
return FT_THROW( Invalid_File_Format );
}
/* Set Units per EM based on FontMatrix values. We set the value to */
/* 1000 / temp_scale, because temp_scale was already multiplied by */
/* 1000 (in t1_tofixed, from psobjs.c). */
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = 0x10000L;
}
matrix->xx = temp[0];
matrix->yx = temp[1];
matrix->xy = temp[2];
matrix->yy = temp[3];
temp[2] = FT_DivFix( temp[2], temp_scale );
temp[4] = FT_DivFix( temp[4], temp_scale );
temp[5] = FT_DivFix( temp[5], temp_scale );
temp[3] = temp[3] < 0 ? -0x10000L : 0x10000L;
}
| 165,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadSCTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[2];
Image
*image;
MagickBooleanType
status;
MagickRealType
height,
width;
Quantum
pixel;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
y;
unsigned char
buffer[768];
size_t
separations,
separations_mask,
units;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read control block.
*/
count=ReadBlob(image,80,buffer);
(void) count;
count=ReadBlob(image,2,(unsigned char *) magick);
if ((LocaleNCompare((char *) magick,"CT",2) != 0) &&
(LocaleNCompare((char *) magick,"LW",2) != 0) &&
(LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"PG",2) != 0) &&
(LocaleNCompare((char *) magick,"TX",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((LocaleNCompare((char *) magick,"LW",2) == 0) ||
(LocaleNCompare((char *) magick,"BM",2) == 0) ||
(LocaleNCompare((char *) magick,"PG",2) == 0) ||
(LocaleNCompare((char *) magick,"TX",2) == 0))
ThrowReaderException(CoderError,"OnlyContinuousTonePictureSupported");
count=ReadBlob(image,174,buffer);
count=ReadBlob(image,768,buffer);
/*
Read paramter block.
*/
units=1UL*ReadBlobByte(image);
if (units == 0)
image->units=PixelsPerCentimeterResolution;
separations=1UL*ReadBlobByte(image);
separations_mask=ReadBlobMSBShort(image);
count=ReadBlob(image,14,buffer);
buffer[14]='\0';
height=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,14,buffer);
width=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,12,buffer);
buffer[12]='\0';
image->rows=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,12,buffer);
image->columns=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,200,buffer);
count=ReadBlob(image,768,buffer);
if (separations_mask == 0x0f)
SetImageColorspace(image,CMYKColorspace);
image->x_resolution=1.0*image->columns/width;
image->y_resolution=1.0*image->rows/height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Convert SCT raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
for (i=0; i < (ssize_t) separations; i++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
if (image->colorspace == CMYKColorspace)
pixel=(Quantum) (QuantumRange-pixel);
switch (i)
{
case 0:
{
SetPixelRed(q,pixel);
SetPixelGreen(q,pixel);
SetPixelBlue(q,pixel);
break;
}
case 1:
{
SetPixelGreen(q,pixel);
break;
}
case 2:
{
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(indexes+x,pixel);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if ((image->columns % 2) != 0)
(void) ReadBlobByte(image); /* pad */
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadSCTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
magick[2];
Image
*image;
MagickBooleanType
status;
MagickRealType
height,
width;
Quantum
pixel;
register IndexPacket
*indexes;
register ssize_t
i,
x;
register PixelPacket
*q;
ssize_t
count,
y;
unsigned char
buffer[768];
size_t
separations,
separations_mask,
units;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read control block.
*/
count=ReadBlob(image,80,buffer);
(void) count;
count=ReadBlob(image,2,(unsigned char *) magick);
if ((LocaleNCompare((char *) magick,"CT",2) != 0) &&
(LocaleNCompare((char *) magick,"LW",2) != 0) &&
(LocaleNCompare((char *) magick,"BM",2) != 0) &&
(LocaleNCompare((char *) magick,"PG",2) != 0) &&
(LocaleNCompare((char *) magick,"TX",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((LocaleNCompare((char *) magick,"LW",2) == 0) ||
(LocaleNCompare((char *) magick,"BM",2) == 0) ||
(LocaleNCompare((char *) magick,"PG",2) == 0) ||
(LocaleNCompare((char *) magick,"TX",2) == 0))
ThrowReaderException(CoderError,"OnlyContinuousTonePictureSupported");
count=ReadBlob(image,174,buffer);
count=ReadBlob(image,768,buffer);
/*
Read paramter block.
*/
units=1UL*ReadBlobByte(image);
if (units == 0)
image->units=PixelsPerCentimeterResolution;
separations=1UL*ReadBlobByte(image);
separations_mask=ReadBlobMSBShort(image);
count=ReadBlob(image,14,buffer);
buffer[14]='\0';
height=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,14,buffer);
width=StringToDouble((char *) buffer,(char **) NULL);
count=ReadBlob(image,12,buffer);
buffer[12]='\0';
image->rows=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,12,buffer);
image->columns=StringToUnsignedLong((char *) buffer);
count=ReadBlob(image,200,buffer);
count=ReadBlob(image,768,buffer);
if (separations_mask == 0x0f)
SetImageColorspace(image,CMYKColorspace);
image->x_resolution=1.0*image->columns/width;
image->y_resolution=1.0*image->rows/height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Convert SCT raster image to pixel packets.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
for (i=0; i < (ssize_t) separations; i++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
pixel=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
if (image->colorspace == CMYKColorspace)
pixel=(Quantum) (QuantumRange-pixel);
switch (i)
{
case 0:
{
SetPixelRed(q,pixel);
SetPixelGreen(q,pixel);
SetPixelBlue(q,pixel);
break;
}
case 1:
{
SetPixelGreen(q,pixel);
break;
}
case 2:
{
SetPixelBlue(q,pixel);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(indexes+x,pixel);
break;
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if ((image->columns % 2) != 0)
(void) ReadBlobByte(image); /* pad */
}
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
usb_conv_info_t *usb_conv_info;
usb_ms_conv_info_t *usb_ms_conv_info;
proto_tree *tree;
proto_item *ti;
guint32 signature=0;
int offset=0;
gboolean is_request;
itl_nexus_t *itl;
itlq_nexus_t *itlq;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
/* verify that we do have a usb_ms_conv_info */
usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data;
if(!usb_ms_conv_info){
usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t);
usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope());
usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data=usb_ms_conv_info;
}
is_request=(pinfo->srcport==NO_ENDPOINT);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage");
tree = proto_item_add_subtree(ti, ett_usb_ms);
signature=tvb_get_letohl(tvb, offset);
/*
* SCSI CDB inside CBW
*/
if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){
tvbuff_t *cdb_tvb;
int cdbrlen, cdblen;
guint8 lun, flags;
guint32 datalen;
/* dCBWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWDataTransferLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN);
datalen=tvb_get_letohl(tvb, offset);
offset+=4;
/* dCBWFlags */
proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN);
flags=tvb_get_guint8(tvb, offset);
offset+=1;
/* dCBWLUN */
proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN);
lun=tvb_get_guint8(tvb, offset)&0x0f;
offset+=1;
/* make sure we have a ITL structure for this LUN */
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun);
if(!itl){
itl=wmem_new(wmem_file_scope(), itl_nexus_t);
itl->cmdset=0xff;
itl->conversation=NULL;
wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl);
}
/* make sure we have an ITLQ structure for this LUN/transaction */
itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
itlq=wmem_new(wmem_file_scope(), itlq_nexus_t);
itlq->lun=lun;
itlq->scsi_opcode=0xffff;
itlq->task_flags=0;
if(datalen){
if(flags&0x80){
itlq->task_flags|=SCSI_DATA_READ;
} else {
itlq->task_flags|=SCSI_DATA_WRITE;
}
}
itlq->data_length=datalen;
itlq->bidir_data_length=0;
itlq->fc_time=pinfo->abs_ts;
itlq->first_exchange_frame=pinfo->num;
itlq->last_exchange_frame=0;
itlq->flags=0;
itlq->alloc_len=0;
itlq->extra_data=NULL;
wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq);
}
/* dCBWCBLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
cdbrlen=tvb_get_guint8(tvb, offset)&0x1f;
offset+=1;
cdblen=cdbrlen;
if(cdblen>tvb_captured_length_remaining(tvb, offset)){
cdblen=tvb_captured_length_remaining(tvb, offset);
}
if(cdblen){
cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen);
dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl);
}
return tvb_captured_length(tvb);
}
/*
* SCSI RESPONSE inside CSW
*/
if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){
guint8 status;
/* dCSWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWDataResidue */
proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWStatus */
proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN);
status=tvb_get_guint8(tvb, offset);
/*offset+=1;*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itlq->last_exchange_frame=pinfo->num;
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
if(!status){
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0);
} else {
/* just send "check condition" */
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02);
}
return tvb_captured_length(tvb);
}
/*
* Ok it was neither CDB not STATUS so just assume it is either data in/out
*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0);
return tvb_captured_length(tvb);
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476 | dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
usb_conv_info_t *usb_conv_info;
usb_ms_conv_info_t *usb_ms_conv_info;
proto_tree *tree;
proto_item *ti;
guint32 signature=0;
int offset=0;
gboolean is_request;
itl_nexus_t *itl;
itlq_nexus_t *itlq;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
/* verify that we do have a usb_ms_conv_info */
usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data;
if(!usb_ms_conv_info){
usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t);
usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope());
usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data=usb_ms_conv_info;
usb_conv_info->class_data_type = USB_CONV_MASS_STORAGE;
} else if (usb_conv_info->class_data_type != USB_CONV_MASS_STORAGE) {
/* Don't dissect if another USB type is in the conversation */
return 0;
}
is_request=(pinfo->srcport==NO_ENDPOINT);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage");
tree = proto_item_add_subtree(ti, ett_usb_ms);
signature=tvb_get_letohl(tvb, offset);
/*
* SCSI CDB inside CBW
*/
if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){
tvbuff_t *cdb_tvb;
int cdbrlen, cdblen;
guint8 lun, flags;
guint32 datalen;
/* dCBWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWDataTransferLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN);
datalen=tvb_get_letohl(tvb, offset);
offset+=4;
/* dCBWFlags */
proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN);
flags=tvb_get_guint8(tvb, offset);
offset+=1;
/* dCBWLUN */
proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN);
lun=tvb_get_guint8(tvb, offset)&0x0f;
offset+=1;
/* make sure we have a ITL structure for this LUN */
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun);
if(!itl){
itl=wmem_new(wmem_file_scope(), itl_nexus_t);
itl->cmdset=0xff;
itl->conversation=NULL;
wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl);
}
/* make sure we have an ITLQ structure for this LUN/transaction */
itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
itlq=wmem_new(wmem_file_scope(), itlq_nexus_t);
itlq->lun=lun;
itlq->scsi_opcode=0xffff;
itlq->task_flags=0;
if(datalen){
if(flags&0x80){
itlq->task_flags|=SCSI_DATA_READ;
} else {
itlq->task_flags|=SCSI_DATA_WRITE;
}
}
itlq->data_length=datalen;
itlq->bidir_data_length=0;
itlq->fc_time=pinfo->abs_ts;
itlq->first_exchange_frame=pinfo->num;
itlq->last_exchange_frame=0;
itlq->flags=0;
itlq->alloc_len=0;
itlq->extra_data=NULL;
wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq);
}
/* dCBWCBLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
cdbrlen=tvb_get_guint8(tvb, offset)&0x1f;
offset+=1;
cdblen=cdbrlen;
if(cdblen>tvb_captured_length_remaining(tvb, offset)){
cdblen=tvb_captured_length_remaining(tvb, offset);
}
if(cdblen){
cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen);
dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl);
}
return tvb_captured_length(tvb);
}
/*
* SCSI RESPONSE inside CSW
*/
if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){
guint8 status;
/* dCSWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWDataResidue */
proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWStatus */
proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN);
status=tvb_get_guint8(tvb, offset);
/*offset+=1;*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itlq->last_exchange_frame=pinfo->num;
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
if(!status){
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0);
} else {
/* just send "check condition" */
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02);
}
return tvb_captured_length(tvb);
}
/*
* Ok it was neither CDB not STATUS so just assume it is either data in/out
*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0);
return tvb_captured_length(tvb);
}
| 167,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
Nor can they impersonate a kill(), which adds source info. */
if (info->si_code >= 0)
return -EPERM;
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
Commit Message: Prevent rt_sigqueueinfo and rt_tgsigqueueinfo from spoofing the signal code
Userland should be able to trust the pid and uid of the sender of a
signal if the si_code is SI_TKILL.
Unfortunately, the kernel has historically allowed sigqueueinfo() to
send any si_code at all (as long as it was negative - to distinguish it
from kernel-generated signals like SIGILL etc), so it could spoof a
SI_TKILL with incorrect siginfo values.
Happily, it looks like glibc has always set si_code to the appropriate
SI_QUEUE, so there are probably no actual user code that ever uses
anything but the appropriate SI_QUEUE flag.
So just tighten the check for si_code (we used to allow any negative
value), and add a (one-time) warning in case there are binaries out
there that might depend on using other si_code values.
Signed-off-by: Julien Tinnes <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
* Nor can they impersonate a kill()/tgkill(), which adds source info.
*/
if (info->si_code != SI_QUEUE) {
/* We used to allow any < 0 si_code */
WARN_ON_ONCE(info->si_code < 0);
return -EPERM;
}
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
| 166,232 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserPolicyConnector::SetDeviceCredentials(
const std::string& owner_email,
const std::string& token,
TokenType token_type) {
#if defined(OS_CHROMEOS)
if (device_data_store_.get()) {
device_data_store_->set_user_name(owner_email);
switch (token_type) {
case TOKEN_TYPE_OAUTH:
device_data_store_->SetOAuthToken(token);
break;
case TOKEN_TYPE_GAIA:
device_data_store_->SetGaiaToken(token);
break;
default:
NOTREACHED() << "Invalid token type " << token_type;
}
}
#endif
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void BrowserPolicyConnector::SetDeviceCredentials(
void BrowserPolicyConnector::RegisterForDevicePolicy(
const std::string& owner_email,
const std::string& token,
TokenType token_type) {
#if defined(OS_CHROMEOS)
if (device_data_store_.get()) {
device_data_store_->set_user_name(owner_email);
switch (token_type) {
case TOKEN_TYPE_OAUTH:
device_data_store_->SetOAuthToken(token);
break;
case TOKEN_TYPE_GAIA:
device_data_store_->SetGaiaToken(token);
break;
default:
NOTREACHED() << "Invalid token type " << token_type;
}
}
#endif
}
| 170,280 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmElementEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && r < count) {
if (!(ptr = R_NEW0 (RBinWasmElementEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
free (ptr);
return ret;
}
if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
free (ptr);
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) {
free (ptr);
return ret;
}
ut32 j = 0;
while (i < len && j < ptr->num_elem ) {
ut32 e;
if (!(consume_u32 (buf + i, buf + len, &e, &i))) {
free (ptr);
return ret;
}
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
CWE ID: CWE-125 | static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmElementEntry *ptr = NULL;
if (!(ret = r_list_newf ((RListFree)free))) {
return NULL;
}
ut8* buf = bin->buf->buf + (ut32)sec->payload_data;
int buflen = bin->buf->length - (ut32)sec->payload_data;
ut32 len = sec->payload_len;
ut32 count = sec->count;
ut32 i = 0, r = 0;
while (i < len && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmElementEntry))) {
return ret;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) {
goto beach;
}
if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) {
goto beach;
}
ut32 j = 0;
while (i < len && j < ptr->num_elem) {
ut32 e;
if (!(consume_u32 (buf + i, buf + len, &e, &i))) {
free (ptr);
return ret;
}
}
r_list_append (ret, ptr);
r += 1;
}
return ret;
beach:
free (ptr);
return ret;
}
| 168,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionWebContentsObserver::RenderViewCreated(
content::RenderViewHost* render_view_host) {
const Extension* extension = GetExtension(render_view_host);
if (!extension)
return;
content::RenderProcessHost* process = render_view_host->GetProcess();
if (type == Manifest::TYPE_EXTENSION ||
type == Manifest::TYPE_LEGACY_PACKAGED_APP ||
(type == Manifest::TYPE_PLATFORM_APP &&
extension->location() == Manifest::COMPONENT)) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
process->GetID(), content::kChromeUIScheme);
}
if (type == Manifest::TYPE_EXTENSION ||
type == Manifest::TYPE_LEGACY_PACKAGED_APP) {
ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context_);
if (prefs->AllowFileAccess(extension->id())) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
process->GetID(), url::kFileScheme);
}
}
render_view_host->Send(new ExtensionMsg_ActivateExtension(extension->id()));
}
Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs.
BUG=528505,226927
Review URL: https://codereview.chromium.org/1362433002
Cr-Commit-Position: refs/heads/master@{#351705}
CWE ID: CWE-264 | void ExtensionWebContentsObserver::RenderViewCreated(
content::RenderViewHost* render_view_host) {
const Extension* extension = GetExtension(render_view_host);
if (!extension)
return;
if (type == Manifest::TYPE_EXTENSION ||
type == Manifest::TYPE_LEGACY_PACKAGED_APP) {
ExtensionPrefs* prefs = ExtensionPrefs::Get(browser_context_);
if (prefs->AllowFileAccess(extension->id())) {
content::ChildProcessSecurityPolicy::GetInstance()->GrantScheme(
render_view_host->GetProcess()->GetID(), url::kFileScheme);
}
}
render_view_host->Send(new ExtensionMsg_ActivateExtension(extension->id()));
}
| 171,776 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_msgtype_print(netdissect_options *ndo, const u_char *dat)
{
const uint16_t *ptr = (const uint16_t *)dat;
ND_PRINT((ndo, "%s", tok2str(l2tp_msgtype2str, "MSGTYPE-#%u",
EXTRACT_16BITS(ptr))));
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l2tp_msgtype_print(netdissect_options *ndo, const u_char *dat)
l2tp_msgtype_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint16_t *ptr = (const uint16_t *)dat;
if (length < 2) {
ND_PRINT((ndo, "AVP too short"));
return;
}
ND_PRINT((ndo, "%s", tok2str(l2tp_msgtype2str, "MSGTYPE-#%u",
EXTRACT_16BITS(ptr))));
}
| 167,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VRDisplay::OnVSync(device::mojom::blink::VRPosePtr pose,
mojo::common::mojom::blink::TimeDeltaPtr time,
int16_t frame_id,
device::mojom::blink::VRVSyncProvider::Status error) {
v_sync_connection_failed_ = false;
switch (error) {
case device::mojom::blink::VRVSyncProvider::Status::SUCCESS:
break;
case device::mojom::blink::VRVSyncProvider::Status::CLOSING:
return;
}
pending_vsync_ = false;
WTF::TimeDelta time_delta =
WTF::TimeDelta::FromMicroseconds(time->microseconds);
if (timebase_ < 0) {
timebase_ = WTF::MonotonicallyIncreasingTime() - time_delta.InSecondsF();
}
frame_pose_ = std::move(pose);
vr_frame_id_ = frame_id;
Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE,
WTF::Bind(&VRDisplay::ProcessScheduledAnimations,
WrapWeakPersistent(this), timebase_ + time_delta.InSecondsF()));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnVSync(device::mojom::blink::VRPosePtr pose,
mojo::common::mojom::blink::TimeDeltaPtr time,
int16_t frame_id,
device::mojom::blink::VRVSyncProvider::Status error) {
DVLOG(2) << __FUNCTION__;
v_sync_connection_failed_ = false;
switch (error) {
case device::mojom::blink::VRVSyncProvider::Status::SUCCESS:
break;
case device::mojom::blink::VRVSyncProvider::Status::CLOSING:
return;
}
pending_vsync_ = false;
WTF::TimeDelta time_delta =
WTF::TimeDelta::FromMicroseconds(time->microseconds);
if (timebase_ < 0) {
timebase_ = WTF::MonotonicallyIncreasingTime() - time_delta.InSecondsF();
}
frame_pose_ = std::move(pose);
vr_frame_id_ = frame_id;
Platform::Current()->CurrentThread()->GetWebTaskRunner()->PostTask(
BLINK_FROM_HERE,
WTF::Bind(&VRDisplay::ProcessScheduledAnimations,
WrapWeakPersistent(this), timebase_ + time_delta.InSecondsF()));
}
| 171,997 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int i, pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
dev_dbg(dev, "Checking memory size\n");
i = 0x12345678;
catc_write_mem(catc, 0x7a80, &i, 4);
i = 0x87654321;
catc_write_mem(catc, 0xfa80, &i, 4);
catc_read_mem(catc, 0x7a80, &i, 4);
switch (i) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
Commit Message: catc: Use heap buffer for memory size test
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int catc_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct device *dev = &intf->dev;
struct usb_device *usbdev = interface_to_usbdev(intf);
struct net_device *netdev;
struct catc *catc;
u8 broadcast[ETH_ALEN];
int pktsz, ret;
if (usb_set_interface(usbdev,
intf->altsetting->desc.bInterfaceNumber, 1)) {
dev_err(dev, "Can't set altsetting 1.\n");
return -EIO;
}
netdev = alloc_etherdev(sizeof(struct catc));
if (!netdev)
return -ENOMEM;
catc = netdev_priv(netdev);
netdev->netdev_ops = &catc_netdev_ops;
netdev->watchdog_timeo = TX_TIMEOUT;
netdev->ethtool_ops = &ops;
catc->usbdev = usbdev;
catc->netdev = netdev;
spin_lock_init(&catc->tx_lock);
spin_lock_init(&catc->ctrl_lock);
init_timer(&catc->timer);
catc->timer.data = (long) catc;
catc->timer.function = catc_stats_timer;
catc->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
catc->irq_urb = usb_alloc_urb(0, GFP_KERNEL);
if ((!catc->ctrl_urb) || (!catc->tx_urb) ||
(!catc->rx_urb) || (!catc->irq_urb)) {
dev_err(&intf->dev, "No free urbs available.\n");
ret = -ENOMEM;
goto fail_free;
}
/* The F5U011 has the same vendor/product as the netmate but a device version of 0x130 */
if (le16_to_cpu(usbdev->descriptor.idVendor) == 0x0423 &&
le16_to_cpu(usbdev->descriptor.idProduct) == 0xa &&
le16_to_cpu(catc->usbdev->descriptor.bcdDevice) == 0x0130) {
dev_dbg(dev, "Testing for f5u011\n");
catc->is_f5u011 = 1;
atomic_set(&catc->recq_sz, 0);
pktsz = RX_PKT_SZ;
} else {
pktsz = RX_MAX_BURST * (PKT_SZ + 2);
}
usb_fill_control_urb(catc->ctrl_urb, usbdev, usb_sndctrlpipe(usbdev, 0),
NULL, NULL, 0, catc_ctrl_done, catc);
usb_fill_bulk_urb(catc->tx_urb, usbdev, usb_sndbulkpipe(usbdev, 1),
NULL, 0, catc_tx_done, catc);
usb_fill_bulk_urb(catc->rx_urb, usbdev, usb_rcvbulkpipe(usbdev, 1),
catc->rx_buf, pktsz, catc_rx_done, catc);
usb_fill_int_urb(catc->irq_urb, usbdev, usb_rcvintpipe(usbdev, 2),
catc->irq_buf, 2, catc_irq_done, catc, 1);
if (!catc->is_f5u011) {
u32 *buf;
int i;
dev_dbg(dev, "Checking memory size\n");
buf = kmalloc(4, GFP_KERNEL);
if (!buf) {
ret = -ENOMEM;
goto fail_free;
}
*buf = 0x12345678;
catc_write_mem(catc, 0x7a80, buf, 4);
*buf = 0x87654321;
catc_write_mem(catc, 0xfa80, buf, 4);
catc_read_mem(catc, 0x7a80, buf, 4);
switch (*buf) {
case 0x12345678:
catc_set_reg(catc, TxBufCount, 8);
catc_set_reg(catc, RxBufCount, 32);
dev_dbg(dev, "64k Memory\n");
break;
default:
dev_warn(&intf->dev,
"Couldn't detect memory size, assuming 32k\n");
case 0x87654321:
catc_set_reg(catc, TxBufCount, 4);
catc_set_reg(catc, RxBufCount, 16);
dev_dbg(dev, "32k Memory\n");
break;
}
kfree(buf);
dev_dbg(dev, "Getting MAC from SEEROM.\n");
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting MAC into registers.\n");
for (i = 0; i < 6; i++)
catc_set_reg(catc, StationAddr0 - i, netdev->dev_addr[i]);
dev_dbg(dev, "Filling the multicast list.\n");
eth_broadcast_addr(broadcast);
catc_multicast(broadcast, catc->multicast);
catc_multicast(netdev->dev_addr, catc->multicast);
catc_write_mem(catc, 0xfa80, catc->multicast, 64);
dev_dbg(dev, "Clearing error counters.\n");
for (i = 0; i < 8; i++)
catc_set_reg(catc, EthStats + i, 0);
catc->last_stats = jiffies;
dev_dbg(dev, "Enabling.\n");
catc_set_reg(catc, MaxBurst, RX_MAX_BURST);
catc_set_reg(catc, OpModes, OpTxMerge | OpRxMerge | OpLenInclude | Op3MemWaits);
catc_set_reg(catc, LEDCtrl, LEDLink);
catc_set_reg(catc, RxUnit, RxEnable | RxPolarity | RxMultiCast);
} else {
dev_dbg(dev, "Performing reset\n");
catc_reset(catc);
catc_get_mac(catc, netdev->dev_addr);
dev_dbg(dev, "Setting RX Mode\n");
catc->rxmode[0] = RxEnable | RxPolarity | RxMultiCast;
catc->rxmode[1] = 0;
f5u011_rxmode(catc, catc->rxmode);
}
dev_dbg(dev, "Init done.\n");
printk(KERN_INFO "%s: %s USB Ethernet at usb-%s-%s, %pM.\n",
netdev->name, (catc->is_f5u011) ? "Belkin F5U011" : "CATC EL1210A NetMate",
usbdev->bus->bus_name, usbdev->devpath, netdev->dev_addr);
usb_set_intfdata(intf, catc);
SET_NETDEV_DEV(netdev, &intf->dev);
ret = register_netdev(netdev);
if (ret)
goto fail_clear_intfdata;
return 0;
fail_clear_intfdata:
usb_set_intfdata(intf, NULL);
fail_free:
usb_free_urb(catc->ctrl_urb);
usb_free_urb(catc->tx_urb);
usb_free_urb(catc->rx_urb);
usb_free_urb(catc->irq_urb);
free_netdev(netdev);
return ret;
}
| 168,213 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
Commit Message: fix error from commit 13585f15c7f7dc28bbbba1661efb280d530d114c
CWE ID: CWE-476 | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !rem_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
}
| 170,216 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.xxpStatus = ppresXxpIncomplete;
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
}
return res;
}
Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | ProcessTCPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize)
{
ULONG tcpipDataAt;
tTcpIpPacketParsingResult res = _res;
tcpipDataAt = ipHeaderSize + sizeof(TCPHeader);
res.TcpUdp = ppresIsTCP;
if (len >= tcpipDataAt)
{
TCPHeader *pTcpHeader = (TCPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize);
res.xxpStatus = ppresXxpKnown;
res.xxpFull = TRUE;
tcpipDataAt = ipHeaderSize + TCP_HEADER_LENGTH(pTcpHeader);
res.XxpIpHeaderSize = tcpipDataAt;
}
else
{
DPrintf(2, ("tcp: %d < min headers %d\n", len, tcpipDataAt));
res.xxpFull = FALSE;
res.xxpStatus = ppresXxpIncomplete;
}
return res;
}
| 168,889 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400 | static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
n->mounts += n->pending_mounts;
n->pending_mounts = 0;
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
| 167,008 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (nfs_write_pageuptodate(page, inode) && (inode->i_flock == NULL ||
(inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK)))
return 1;
return 0;
}
Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page
We should always make sure the cached page is up-to-date when we're
determining whether we can extend a write to cover the full page -- even
if we've received a write delegation from the server.
Commit c7559663 added logic to skip this check if we have a write
delegation, which can lead to data corruption such as the following
scenario if client B receives a write delegation from the NFS server:
Client A:
# echo 123456789 > /mnt/file
Client B:
# echo abcdefghi >> /mnt/file
# cat /mnt/file
0�D0�abcdefghi
Just because we hold a write delegation doesn't mean that we've read in
the entire page contents.
Cc: <[email protected]> # v3.11+
Signed-off-by: Scott Mayhew <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-20 | static int nfs_can_extend_write(struct file *file, struct page *page, struct inode *inode)
{
if (file->f_flags & O_DSYNC)
return 0;
if (!nfs_write_pageuptodate(page, inode))
return 0;
if (NFS_PROTO(inode)->have_delegation(inode, FMODE_WRITE))
return 1;
if (inode->i_flock == NULL || (inode->i_flock->fl_start == 0 &&
inode->i_flock->fl_end == OFFSET_MAX &&
inode->i_flock->fl_type != F_RDLCK))
return 1;
return 0;
}
| 166,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] << 8;
}
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
static void copyMultiCh8(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels)
{
for (unsigned i = 0; i < nSamples; ++i) {
for (unsigned c = 0; c < nChannels; ++c) {
*dst++ = src[c][i] << 8;
}
}
}
| 174,020 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL);
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length)
{
int ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
if (errno == EINTR)
{
/* retry again */
ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL));
if (ret < 0)
{
ERROR("ack failed (%s)", strerror(errno));
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
else
{
skt_disconnect(common->ctrl_fd);
common->ctrl_fd = AUDIO_SKT_DISCONNECTED;
return -1;
}
}
return ret;
}
| 173,423 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Ins_IUP( INS_ARG )
{
IUP_WorkerRec V;
FT_Byte mask;
FT_UInt first_point; /* first point of contour */
FT_UInt end_point; /* end point (last+1) of contour */
FT_UInt first_touched; /* first touched point in contour */
FT_UInt cur_touched; /* current touched point in contour */
FT_UInt point; /* current point */
FT_Short contour; /* current contour */
FT_UNUSED_ARG;
/* ignore empty outlines */
if ( CUR.pts.n_contours == 0 )
return;
if ( CUR.opcode & 1 )
{
mask = FT_CURVE_TAG_TOUCH_X;
V.orgs = CUR.pts.org;
V.curs = CUR.pts.cur;
V.orus = CUR.pts.orus;
}
else
{
mask = FT_CURVE_TAG_TOUCH_Y;
V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 );
V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 );
V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 );
}
V.max_points = CUR.pts.n_points;
contour = 0;
point = 0;
do
{
end_point = CUR.pts.contours[contour] - CUR.pts.first_point;
first_point = point;
if ( CUR.pts.n_points <= end_point )
end_point = CUR.pts.n_points;
while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 )
point++;
if ( point <= end_point )
{
first_touched = point;
cur_touched = point;
point++;
while ( point <= end_point )
{
if ( ( CUR.pts.tags[point] & mask ) != 0 )
{
if ( point > 0 )
_iup_worker_interpolate( &V,
cur_touched + 1,
point - 1,
cur_touched,
point );
cur_touched = point;
}
point++;
}
if ( cur_touched == first_touched )
_iup_worker_shift( &V, first_point, end_point, cur_touched );
else
{
_iup_worker_interpolate( &V,
(FT_UShort)( cur_touched + 1 ),
end_point,
cur_touched,
first_touched );
if ( first_touched > 0 )
_iup_worker_interpolate( &V,
first_point,
first_touched - 1,
cur_touched,
first_touched );
}
}
contour++;
} while ( contour < CUR.pts.n_contours );
}
Commit Message:
CWE ID: CWE-119 | Ins_IUP( INS_ARG )
{
IUP_WorkerRec V;
FT_Byte mask;
FT_UInt first_point; /* first point of contour */
FT_UInt end_point; /* end point (last+1) of contour */
FT_UInt first_touched; /* first touched point in contour */
FT_UInt cur_touched; /* current touched point in contour */
FT_UInt point; /* current point */
FT_Short contour; /* current contour */
FT_UNUSED_ARG;
/* ignore empty outlines */
if ( CUR.pts.n_contours == 0 )
return;
if ( CUR.opcode & 1 )
{
mask = FT_CURVE_TAG_TOUCH_X;
V.orgs = CUR.pts.org;
V.curs = CUR.pts.cur;
V.orus = CUR.pts.orus;
}
else
{
mask = FT_CURVE_TAG_TOUCH_Y;
V.orgs = (FT_Vector*)( (FT_Pos*)CUR.pts.org + 1 );
V.curs = (FT_Vector*)( (FT_Pos*)CUR.pts.cur + 1 );
V.orus = (FT_Vector*)( (FT_Pos*)CUR.pts.orus + 1 );
}
V.max_points = CUR.pts.n_points;
contour = 0;
point = 0;
do
{
end_point = CUR.pts.contours[contour] - CUR.pts.first_point;
first_point = point;
if ( BOUNDS ( end_point, CUR.pts.n_points ) )
end_point = CUR.pts.n_points - 1;
while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 )
point++;
if ( point <= end_point )
{
first_touched = point;
cur_touched = point;
point++;
while ( point <= end_point )
{
if ( ( CUR.pts.tags[point] & mask ) != 0 )
{
if ( point > 0 )
_iup_worker_interpolate( &V,
cur_touched + 1,
point - 1,
cur_touched,
point );
cur_touched = point;
}
point++;
}
if ( cur_touched == first_touched )
_iup_worker_shift( &V, first_point, end_point, cur_touched );
else
{
_iup_worker_interpolate( &V,
(FT_UShort)( cur_touched + 1 ),
end_point,
cur_touched,
first_touched );
if ( first_touched > 0 )
_iup_worker_interpolate( &V,
first_point,
first_touched - 1,
cur_touched,
first_touched );
}
}
contour++;
} while ( contour < CUR.pts.n_contours );
}
| 165,002 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int digi_startup(struct usb_serial *serial)
{
struct digi_serial *serial_priv;
int ret;
serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL);
if (!serial_priv)
return -ENOMEM;
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
ret = digi_port_init(serial_priv->ds_oob_port,
serial_priv->ds_oob_port_num);
if (ret) {
kfree(serial_priv);
return ret;
}
usb_set_serial_data(serial, serial_priv);
return 0;
}
Commit Message: USB: digi_acceleport: do sanity checking for the number of ports
The driver can be crashed with devices that expose crafted descriptors
with too few endpoints.
See: http://seclists.org/bugtraq/2016/Mar/61
Signed-off-by: Oliver Neukum <[email protected]>
[johan: fix OOB endpoint check and add error messages ]
Cc: stable <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int digi_startup(struct usb_serial *serial)
{
struct device *dev = &serial->interface->dev;
struct digi_serial *serial_priv;
int ret;
int i;
/* check whether the device has the expected number of endpoints */
if (serial->num_port_pointers < serial->type->num_ports + 1) {
dev_err(dev, "OOB endpoints missing\n");
return -ENODEV;
}
for (i = 0; i < serial->type->num_ports + 1 ; i++) {
if (!serial->port[i]->read_urb) {
dev_err(dev, "bulk-in endpoint missing\n");
return -ENODEV;
}
if (!serial->port[i]->write_urb) {
dev_err(dev, "bulk-out endpoint missing\n");
return -ENODEV;
}
}
serial_priv = kzalloc(sizeof(*serial_priv), GFP_KERNEL);
if (!serial_priv)
return -ENOMEM;
spin_lock_init(&serial_priv->ds_serial_lock);
serial_priv->ds_oob_port_num = serial->type->num_ports;
serial_priv->ds_oob_port = serial->port[serial_priv->ds_oob_port_num];
ret = digi_port_init(serial_priv->ds_oob_port,
serial_priv->ds_oob_port_num);
if (ret) {
kfree(serial_priv);
return ret;
}
usb_set_serial_data(serial, serial_priv);
return 0;
}
| 167,357 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PushMessagingServiceImpl::DidHandleMessage(
const std::string& app_id,
const base::Closure& message_handled_closure) {
auto in_flight_iterator = in_flight_message_deliveries_.find(app_id);
DCHECK(in_flight_iterator != in_flight_message_deliveries_.end());
in_flight_message_deliveries_.erase(in_flight_iterator);
#if BUILDFLAG(ENABLE_BACKGROUND)
if (in_flight_message_deliveries_.empty())
in_flight_keep_alive_.reset();
#endif
message_handled_closure.Run();
if (push_messaging_service_observer_)
push_messaging_service_observer_->OnMessageHandled();
}
Commit Message: Remove some senseless indirection from the Push API code
Four files to call one Java function. Let's just call it directly.
BUG=
Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6
Reviewed-on: https://chromium-review.googlesource.com/749147
Reviewed-by: Anita Woodruff <[email protected]>
Commit-Queue: Peter Beverloo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513464}
CWE ID: CWE-119 | void PushMessagingServiceImpl::DidHandleMessage(
const std::string& app_id,
const base::Closure& message_handled_closure) {
auto in_flight_iterator = in_flight_message_deliveries_.find(app_id);
DCHECK(in_flight_iterator != in_flight_message_deliveries_.end());
in_flight_message_deliveries_.erase(in_flight_iterator);
#if BUILDFLAG(ENABLE_BACKGROUND)
if (in_flight_message_deliveries_.empty())
in_flight_keep_alive_.reset();
#endif
message_handled_closure.Run();
#if defined(OS_ANDROID)
chrome::android::Java_PushMessagingServiceObserver_onMessageHandled(
base::android::AttachCurrentThread());
#endif
}
| 172,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw = ROUND_UP_TO(context->width, 8);
BYTE shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
BYTE* bmpdata = context->BitmapData;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | static void nsc_decode(NSC_CONTEXT* context)
static BOOL nsc_decode(NSC_CONTEXT* context)
{
UINT16 x;
UINT16 y;
UINT16 rw;
BYTE shift;
BYTE* bmpdata;
size_t pos = 0;
if (!context)
return FALSE;
rw = ROUND_UP_TO(context->width, 8);
shift = context->ColorLossLevel - 1; /* colorloss recovery + YCoCg shift */
bmpdata = context->BitmapData;
if (!bmpdata)
return FALSE;
for (y = 0; y < context->height; y++)
{
const BYTE* yplane;
const BYTE* coplane;
const BYTE* cgplane;
const BYTE* aplane = context->priv->PlaneBuffers[3] + y * context->width; /* A */
if (context->ChromaSubsamplingLevel)
{
yplane = context->priv->PlaneBuffers[0] + y * rw; /* Y */
coplane = context->priv->PlaneBuffers[1] + (y >> 1) * (rw >>
1); /* Co, supersampled */
cgplane = context->priv->PlaneBuffers[2] + (y >> 1) * (rw >>
1); /* Cg, supersampled */
}
else
{
yplane = context->priv->PlaneBuffers[0] + y * context->width; /* Y */
coplane = context->priv->PlaneBuffers[1] + y * context->width; /* Co */
cgplane = context->priv->PlaneBuffers[2] + y * context->width; /* Cg */
}
for (x = 0; x < context->width; x++)
{
INT16 y_val = (INT16) * yplane;
INT16 co_val = (INT16)(INT8)(*coplane << shift);
INT16 cg_val = (INT16)(INT8)(*cgplane << shift);
INT16 r_val = y_val + co_val - cg_val;
INT16 g_val = y_val + cg_val;
INT16 b_val = y_val - co_val - cg_val;
if (pos + 4 > context->BitmapDataLength)
return FALSE;
pos += 4;
*bmpdata++ = MINMAX(b_val, 0, 0xFF);
*bmpdata++ = MINMAX(g_val, 0, 0xFF);
*bmpdata++ = MINMAX(r_val, 0, 0xFF);
*bmpdata++ = *aplane;
yplane++;
coplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
cgplane += (context->ChromaSubsamplingLevel ? x % 2 : 1);
aplane++;
}
}
return TRUE;
}
| 169,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
: host_(RenderWidgetHostImpl::From(host)),
ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))),
in_shutdown_(false),
is_fullscreen_(false),
popup_parent_host_view_(NULL),
popup_child_host_view_(NULL),
is_loading_(false),
text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
can_compose_inline_(true),
has_composition_text_(false),
device_scale_factor_(1.0f),
current_surface_(0),
current_surface_is_protected_(true),
current_surface_in_use_by_compositor_(true),
protection_state_id_(0),
surface_route_id_(0),
paint_canvas_(NULL),
synthetic_move_sent_(false),
accelerated_compositing_state_changed_(false),
can_lock_compositor_(YES) {
host_->SetView(this);
window_observer_.reset(new WindowObserver(this));
window_->AddObserver(window_observer_.get());
aura::client::SetTooltipText(window_, &tooltip_);
aura::client::SetActivationDelegate(window_, this);
gfx::Screen::GetScreenFor(window_)->AddObserver(this);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host)
: host_(RenderWidgetHostImpl::From(host)),
ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))),
in_shutdown_(false),
is_fullscreen_(false),
popup_parent_host_view_(NULL),
popup_child_host_view_(NULL),
is_loading_(false),
text_input_type_(ui::TEXT_INPUT_TYPE_NONE),
can_compose_inline_(true),
has_composition_text_(false),
device_scale_factor_(1.0f),
current_surface_(0),
paint_canvas_(NULL),
synthetic_move_sent_(false),
accelerated_compositing_state_changed_(false),
can_lock_compositor_(YES) {
host_->SetView(this);
window_observer_.reset(new WindowObserver(this));
window_->AddObserver(window_observer_.get());
aura::client::SetTooltipText(window_, &tooltip_);
aura::client::SetActivationDelegate(window_, this);
gfx::Screen::GetScreenFor(window_)->AddObserver(this);
}
| 171,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(get_html_translation_table)
{
long all = HTML_SPECIALCHARS,
flags = ENT_COMPAT;
int doctype;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
char *charset_hint = NULL;
int charset_hint_len;
enum entity_charset charset;
/* in this function we have to jump through some loops because we're
* getting the translated table from data structures that are optimized for
* random access, not traversal */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls",
&all, &flags, &charset_hint, &charset_hint_len) == FAILURE) {
return;
}
charset = determine_charset(charset_hint TSRMLS_CC);
doctype = flags & ENT_HTML_DOC_TYPE_MASK;
LIMIT_ALL(all, doctype, charset);
array_init(return_value);
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
const entity_stage1_row *ms_table = entity_table.ms_table;
if (CHARSET_UNICODE_COMPAT(charset)) {
unsigned i, j, k,
max_i, max_j, max_k;
/* no mapping to unicode required */
if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
max_i = 1; max_j = 4; max_k = 64;
} else {
max_i = 0x1E; max_j = 64; max_k = 64;
}
for (i = 0; i < max_i; i++) {
if (ms_table[i] == empty_stage2_table)
continue;
for (j = 0; j < max_j; j++) {
if (ms_table[i][j] == empty_stage3_table)
continue;
for (k = 0; k < max_k; k++) {
const entity_stage3_row *r = &ms_table[i][j][k];
unsigned code;
if (r->data.ent.entity == NULL)
continue;
code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
write_s3row_data(r, code, charset, return_value);
}
}
}
} else {
/* we have to iterate through the set of code points for this
* encoding and map them to unicode code points */
unsigned i;
for (i = 0; i <= 0xFF; i++) {
const entity_stage3_row *r;
unsigned uni_cp;
/* can be done before mapping, they're invariant */
if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
map_to_unicode(i, to_uni_table, &uni_cp);
r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
if (r->data.ent.entity == NULL)
continue;
write_s3row_data(r, i, charset, return_value);
}
}
} else {
/* we could use sizeof(stage3_table_be_apos_00000) as well */
unsigned j,
numelems = sizeof(stage3_table_be_noapos_00000) /
sizeof(*stage3_table_be_noapos_00000);
for (j = 0; j < numelems; j++) {
const entity_stage3_row *r = &entity_table.table[j];
if (r->data.ent.entity == NULL)
continue;
if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
/* charset is indifferent, used cs_8859_1 for efficiency */
write_s3row_data(r, j, cs_8859_1, return_value);
}
}
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | PHP_FUNCTION(get_html_translation_table)
{
long all = HTML_SPECIALCHARS,
flags = ENT_COMPAT;
int doctype;
entity_table_opt entity_table;
const enc_to_uni *to_uni_table = NULL;
char *charset_hint = NULL;
int charset_hint_len;
enum entity_charset charset;
/* in this function we have to jump through some loops because we're
* getting the translated table from data structures that are optimized for
* random access, not traversal */
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lls",
&all, &flags, &charset_hint, &charset_hint_len) == FAILURE) {
return;
}
charset = determine_charset(charset_hint TSRMLS_CC);
doctype = flags & ENT_HTML_DOC_TYPE_MASK;
LIMIT_ALL(all, doctype, charset);
array_init(return_value);
entity_table = determine_entity_table(all, doctype);
if (all && !CHARSET_UNICODE_COMPAT(charset)) {
to_uni_table = enc_to_uni_index[charset];
}
if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
const entity_stage1_row *ms_table = entity_table.ms_table;
if (CHARSET_UNICODE_COMPAT(charset)) {
unsigned i, j, k,
max_i, max_j, max_k;
/* no mapping to unicode required */
if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
max_i = 1; max_j = 4; max_k = 64;
} else {
max_i = 0x1E; max_j = 64; max_k = 64;
}
for (i = 0; i < max_i; i++) {
if (ms_table[i] == empty_stage2_table)
continue;
for (j = 0; j < max_j; j++) {
if (ms_table[i][j] == empty_stage3_table)
continue;
for (k = 0; k < max_k; k++) {
const entity_stage3_row *r = &ms_table[i][j][k];
unsigned code;
if (r->data.ent.entity == NULL)
continue;
code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
write_s3row_data(r, code, charset, return_value);
}
}
}
} else {
/* we have to iterate through the set of code points for this
* encoding and map them to unicode code points */
unsigned i;
for (i = 0; i <= 0xFF; i++) {
const entity_stage3_row *r;
unsigned uni_cp;
/* can be done before mapping, they're invariant */
if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
map_to_unicode(i, to_uni_table, &uni_cp);
r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
if (r->data.ent.entity == NULL)
continue;
write_s3row_data(r, i, charset, return_value);
}
}
} else {
/* we could use sizeof(stage3_table_be_apos_00000) as well */
unsigned j,
numelems = sizeof(stage3_table_be_noapos_00000) /
sizeof(*stage3_table_be_noapos_00000);
for (j = 0; j < numelems; j++) {
const entity_stage3_row *r = &entity_table.table[j];
if (r->data.ent.entity == NULL)
continue;
if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
(j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
continue;
/* charset is indifferent, used cs_8859_1 for efficiency */
write_s3row_data(r, j, cs_8859_1, return_value);
}
}
}
| 167,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
vmcs_writel(HOST_CR4, read_cr4()); /* 22.2.3, 22.2.5 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry
CR4 isn't constant; at least the TSD and PCE bits can vary.
TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks
like it's correct.
This adds a branch and a read from cr4 to each vm entry. Because it is
extremely likely that consecutive entries into the same vcpu will have
the same host cr4 value, this fixes up the vmcs instead of restoring cr4
after the fact. A subsequent patch will add a kernel-wide cr4 shadow,
reducing the overhead in the common case to just two memory reads and a
branch.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: Paolo Bonzini <[email protected]>
Cc: [email protected]
Cc: Petr Matousek <[email protected]>
Cc: Gleb Natapov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399 | static void vmx_set_constant_host_state(struct vcpu_vmx *vmx)
{
u32 low32, high32;
unsigned long tmpl;
struct desc_ptr dt;
unsigned long cr4;
vmcs_writel(HOST_CR0, read_cr0() & ~X86_CR0_TS); /* 22.2.3 */
vmcs_writel(HOST_CR3, read_cr3()); /* 22.2.3 FIXME: shadow tables */
/* Save the most likely value for this task's CR4 in the VMCS. */
cr4 = read_cr4();
vmcs_writel(HOST_CR4, cr4); /* 22.2.3, 22.2.5 */
vmx->host_state.vmcs_host_cr4 = cr4;
vmcs_write16(HOST_CS_SELECTOR, __KERNEL_CS); /* 22.2.4 */
#ifdef CONFIG_X86_64
/*
* Load null selectors, so we can avoid reloading them in
* __vmx_load_host_state(), in case userspace uses the null selectors
* too (the expected case).
*/
vmcs_write16(HOST_DS_SELECTOR, 0);
vmcs_write16(HOST_ES_SELECTOR, 0);
#else
vmcs_write16(HOST_DS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_ES_SELECTOR, __KERNEL_DS); /* 22.2.4 */
#endif
vmcs_write16(HOST_SS_SELECTOR, __KERNEL_DS); /* 22.2.4 */
vmcs_write16(HOST_TR_SELECTOR, GDT_ENTRY_TSS*8); /* 22.2.4 */
native_store_idt(&dt);
vmcs_writel(HOST_IDTR_BASE, dt.address); /* 22.2.4 */
vmx->host_idt_base = dt.address;
vmcs_writel(HOST_RIP, vmx_return); /* 22.2.5 */
rdmsr(MSR_IA32_SYSENTER_CS, low32, high32);
vmcs_write32(HOST_IA32_SYSENTER_CS, low32);
rdmsrl(MSR_IA32_SYSENTER_EIP, tmpl);
vmcs_writel(HOST_IA32_SYSENTER_EIP, tmpl); /* 22.2.3 */
if (vmcs_config.vmexit_ctrl & VM_EXIT_LOAD_IA32_PAT) {
rdmsr(MSR_IA32_CR_PAT, low32, high32);
vmcs_write64(HOST_IA32_PAT, low32 | ((u64) high32 << 32));
}
}
| 166,328 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __net_init sctp_net_init(struct net *net)
{
int status;
/*
* 14. Suggested SCTP Protocol Parameter Values
*/
/* The following protocol parameters are RECOMMENDED: */
/* RTO.Initial - 3 seconds */
net->sctp.rto_initial = SCTP_RTO_INITIAL;
/* RTO.Min - 1 second */
net->sctp.rto_min = SCTP_RTO_MIN;
/* RTO.Max - 60 seconds */
net->sctp.rto_max = SCTP_RTO_MAX;
/* RTO.Alpha - 1/8 */
net->sctp.rto_alpha = SCTP_RTO_ALPHA;
/* RTO.Beta - 1/4 */
net->sctp.rto_beta = SCTP_RTO_BETA;
/* Valid.Cookie.Life - 60 seconds */
net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE;
/* Whether Cookie Preservative is enabled(1) or not(0) */
net->sctp.cookie_preserve_enable = 1;
/* Default sctp sockets to use md5 as their hmac alg */
#if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)
net->sctp.sctp_hmac_alg = "md5";
#elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)
net->sctp.sctp_hmac_alg = "sha1";
#else
net->sctp.sctp_hmac_alg = NULL;
#endif
/* Max.Burst - 4 */
net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST;
/* Association.Max.Retrans - 10 attempts
* Path.Max.Retrans - 5 attempts (per destination address)
* Max.Init.Retransmits - 8 attempts
*/
net->sctp.max_retrans_association = 10;
net->sctp.max_retrans_path = 5;
net->sctp.max_retrans_init = 8;
/* Sendbuffer growth - do per-socket accounting */
net->sctp.sndbuf_policy = 0;
/* Rcvbuffer growth - do per-socket accounting */
net->sctp.rcvbuf_policy = 0;
/* HB.interval - 30 seconds */
net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT;
/* delayed SACK timeout */
net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK;
/* Disable ADDIP by default. */
net->sctp.addip_enable = 0;
net->sctp.addip_noauth = 0;
net->sctp.default_auto_asconf = 0;
/* Enable PR-SCTP by default. */
net->sctp.prsctp_enable = 1;
/* Disable AUTH by default. */
net->sctp.auth_enable = 0;
/* Set SCOPE policy to enabled */
net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;
/* Set the default rwnd update threshold */
net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;
/* Initialize maximum autoclose timeout. */
net->sctp.max_autoclose = INT_MAX / HZ;
status = sctp_sysctl_net_register(net);
if (status)
goto err_sysctl_register;
/* Allocate and initialise sctp mibs. */
status = init_sctp_mibs(net);
if (status)
goto err_init_mibs;
/* Initialize proc fs directory. */
status = sctp_proc_init(net);
if (status)
goto err_init_proc;
sctp_dbg_objcnt_init(net);
/* Initialize the control inode/socket for handling OOTB packets. */
if ((status = sctp_ctl_sock_init(net))) {
pr_err("Failed to initialize the SCTP control sock\n");
goto err_ctl_sock_init;
}
/* Initialize the local address list. */
INIT_LIST_HEAD(&net->sctp.local_addr_list);
spin_lock_init(&net->sctp.local_addr_lock);
sctp_get_local_addr_list(net);
/* Initialize the address event list */
INIT_LIST_HEAD(&net->sctp.addr_waitq);
INIT_LIST_HEAD(&net->sctp.auto_asconf_splist);
spin_lock_init(&net->sctp.addr_wq_lock);
net->sctp.addr_wq_timer.expires = 0;
setup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler,
(unsigned long)net);
return 0;
err_ctl_sock_init:
sctp_dbg_objcnt_exit(net);
sctp_proc_exit(net);
err_init_proc:
cleanup_sctp_mibs(net);
err_init_mibs:
sctp_sysctl_net_unregister(net);
err_sysctl_register:
return status;
}
Commit Message: sctp: fix race on protocol/netns initialization
Consider sctp module is unloaded and is being requested because an user
is creating a sctp socket.
During initialization, sctp will add the new protocol type and then
initialize pernet subsys:
status = sctp_v4_protosw_init();
if (status)
goto err_protosw_init;
status = sctp_v6_protosw_init();
if (status)
goto err_v6_protosw_init;
status = register_pernet_subsys(&sctp_net_ops);
The problem is that after those calls to sctp_v{4,6}_protosw_init(), it
is possible for userspace to create SCTP sockets like if the module is
already fully loaded. If that happens, one of the possible effects is
that we will have readers for net->sctp.local_addr_list list earlier
than expected and sctp_net_init() does not take precautions while
dealing with that list, leading to a potential panic but not limited to
that, as sctp_sock_init() will copy a bunch of blank/partially
initialized values from net->sctp.
The race happens like this:
CPU 0 | CPU 1
socket() |
__sock_create | socket()
inet_create | __sock_create
list_for_each_entry_rcu( |
answer, &inetsw[sock->type], |
list) { | inet_create
/* no hits */ |
if (unlikely(err)) { |
... |
request_module() |
/* socket creation is blocked |
* the module is fully loaded |
*/ |
sctp_init |
sctp_v4_protosw_init |
inet_register_protosw |
list_add_rcu(&p->list, |
last_perm); |
| list_for_each_entry_rcu(
| answer, &inetsw[sock->type],
sctp_v6_protosw_init | list) {
| /* hit, so assumes protocol
| * is already loaded
| */
| /* socket creation continues
| * before netns is initialized
| */
register_pernet_subsys |
Simply inverting the initialization order between
register_pernet_subsys() and sctp_v4_protosw_init() is not possible
because register_pernet_subsys() will create a control sctp socket, so
the protocol must be already visible by then. Deferring the socket
creation to a work-queue is not good specially because we loose the
ability to handle its errors.
So, as suggested by Vlad, the fix is to split netns initialization in
two moments: defaults and control socket, so that the defaults are
already loaded by when we register the protocol, while control socket
initialization is kept at the same moment it is today.
Fixes: 4db67e808640 ("sctp: Make the address lists per network namespace")
Signed-off-by: Vlad Yasevich <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int __net_init sctp_net_init(struct net *net)
static int __net_init sctp_defaults_init(struct net *net)
{
int status;
/*
* 14. Suggested SCTP Protocol Parameter Values
*/
/* The following protocol parameters are RECOMMENDED: */
/* RTO.Initial - 3 seconds */
net->sctp.rto_initial = SCTP_RTO_INITIAL;
/* RTO.Min - 1 second */
net->sctp.rto_min = SCTP_RTO_MIN;
/* RTO.Max - 60 seconds */
net->sctp.rto_max = SCTP_RTO_MAX;
/* RTO.Alpha - 1/8 */
net->sctp.rto_alpha = SCTP_RTO_ALPHA;
/* RTO.Beta - 1/4 */
net->sctp.rto_beta = SCTP_RTO_BETA;
/* Valid.Cookie.Life - 60 seconds */
net->sctp.valid_cookie_life = SCTP_DEFAULT_COOKIE_LIFE;
/* Whether Cookie Preservative is enabled(1) or not(0) */
net->sctp.cookie_preserve_enable = 1;
/* Default sctp sockets to use md5 as their hmac alg */
#if defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_MD5)
net->sctp.sctp_hmac_alg = "md5";
#elif defined (CONFIG_SCTP_DEFAULT_COOKIE_HMAC_SHA1)
net->sctp.sctp_hmac_alg = "sha1";
#else
net->sctp.sctp_hmac_alg = NULL;
#endif
/* Max.Burst - 4 */
net->sctp.max_burst = SCTP_DEFAULT_MAX_BURST;
/* Association.Max.Retrans - 10 attempts
* Path.Max.Retrans - 5 attempts (per destination address)
* Max.Init.Retransmits - 8 attempts
*/
net->sctp.max_retrans_association = 10;
net->sctp.max_retrans_path = 5;
net->sctp.max_retrans_init = 8;
/* Sendbuffer growth - do per-socket accounting */
net->sctp.sndbuf_policy = 0;
/* Rcvbuffer growth - do per-socket accounting */
net->sctp.rcvbuf_policy = 0;
/* HB.interval - 30 seconds */
net->sctp.hb_interval = SCTP_DEFAULT_TIMEOUT_HEARTBEAT;
/* delayed SACK timeout */
net->sctp.sack_timeout = SCTP_DEFAULT_TIMEOUT_SACK;
/* Disable ADDIP by default. */
net->sctp.addip_enable = 0;
net->sctp.addip_noauth = 0;
net->sctp.default_auto_asconf = 0;
/* Enable PR-SCTP by default. */
net->sctp.prsctp_enable = 1;
/* Disable AUTH by default. */
net->sctp.auth_enable = 0;
/* Set SCOPE policy to enabled */
net->sctp.scope_policy = SCTP_SCOPE_POLICY_ENABLE;
/* Set the default rwnd update threshold */
net->sctp.rwnd_upd_shift = SCTP_DEFAULT_RWND_SHIFT;
/* Initialize maximum autoclose timeout. */
net->sctp.max_autoclose = INT_MAX / HZ;
status = sctp_sysctl_net_register(net);
if (status)
goto err_sysctl_register;
/* Allocate and initialise sctp mibs. */
status = init_sctp_mibs(net);
if (status)
goto err_init_mibs;
/* Initialize proc fs directory. */
status = sctp_proc_init(net);
if (status)
goto err_init_proc;
sctp_dbg_objcnt_init(net);
/* Initialize the local address list. */
INIT_LIST_HEAD(&net->sctp.local_addr_list);
spin_lock_init(&net->sctp.local_addr_lock);
sctp_get_local_addr_list(net);
/* Initialize the address event list */
INIT_LIST_HEAD(&net->sctp.addr_waitq);
INIT_LIST_HEAD(&net->sctp.auto_asconf_splist);
spin_lock_init(&net->sctp.addr_wq_lock);
net->sctp.addr_wq_timer.expires = 0;
setup_timer(&net->sctp.addr_wq_timer, sctp_addr_wq_timeout_handler,
(unsigned long)net);
return 0;
err_init_proc:
cleanup_sctp_mibs(net);
err_init_mibs:
sctp_sysctl_net_unregister(net);
err_sysctl_register:
return status;
}
| 166,608 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) {
if (!process_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) {
if (!storage_partition_)
return Response::InternalError();
GURL origin_url(origin);
if (!origin_url.is_valid())
return Response::InvalidParams(origin + " is not a valid URL");
GetIndexedDBObserver()->TaskRunner()->PostTask(
FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread,
base::Unretained(GetIndexedDBObserver()),
url::Origin::Create(origin_url)));
return Response::OK();
}
| 172,777 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int sh_num, int *flags,
uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags, notecount);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
| 166,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void willRemoveChildren(ContainerNode* container)
{
NodeVector children;
getChildNodes(container, children);
container->document().nodeChildrenWillBeRemoved(container);
ChildListMutationScope mutation(container);
for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
Node* child = it->get();
mutation.willRemoveChild(child);
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
}
Commit Message: Notify nodes removal to Range/Selection after dispatching blur and mutation event
This patch changes notifying nodes removal to Range/Selection after dispatching blur and mutation event. In willRemoveChildren(), like willRemoveChild(); r115686 did same change, although it didn't change willRemoveChildren().
The issue 295010, use-after-free, is caused by setting removed node to Selection in mutation event handler.
BUG=295010
TEST=LayoutTests/fast/dom/Range/range-created-during-remove-children.html, LayoutTests/editing/selection/selection-change-in-mutation-event-by-remove-children.html, LayoutTests/editing/selection/selection-change-in-blur-event-by-remove-children.html
[email protected]
Review URL: https://codereview.chromium.org/25389004
git-svn-id: svn://svn.chromium.org/blink/trunk@159007 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void willRemoveChildren(ContainerNode* container)
{
NodeVector children;
getChildNodes(container, children);
ChildListMutationScope mutation(container);
for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
Node* child = it->get();
mutation.willRemoveChild(child);
child->notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
}
| 171,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GraphicsContext::clipPath(const Path&, WindRule)
{
notImplemented();
}
Commit Message: Reviewed by Kevin Ollivier.
[wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support.
https://bugs.webkit.org/show_bug.cgi?id=60847
git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void GraphicsContext::clipPath(const Path&, WindRule)
void GraphicsContext::clipPath(const Path& path, WindRule clipRule)
{
if (paintingDisabled())
return;
if (path.isEmpty())
return;
wxGraphicsContext* gc = m_data->context->GetGraphicsContext();
#if __WXMAC__
CGContextRef context = (CGContextRef)gc->GetNativeContext();
CGPathRef nativePath = (CGPathRef)path.platformPath()->GetNativePath();
CGContextBeginPath(context);
CGContextAddPath(context, nativePath);
if (clipRule == RULE_EVENODD)
CGContextEOClip(context);
else
CGContextClip(context);
#elif __WXMSW__
Gdiplus::Graphics* g = (Gdiplus::Graphics*)gc->GetNativeContext();
Gdiplus::GraphicsPath* nativePath = (Gdiplus::GraphicsPath*)path.platformPath()->GetNativePath();
if (clipRule == RULE_EVENODD)
nativePath->SetFillMode(Gdiplus::FillModeAlternate);
else
nativePath->SetFillMode(Gdiplus::FillModeWinding);
g->SetClip(nativePath);
#endif
}
| 170,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int dtls1_process_buffered_records(SSL *s)
{
pitem *item;
SSL3_BUFFER *rb;
item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
if (item) {
/* Check if epoch is current. */
if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
return (1); /* Nothing to do. */
rb = RECORD_LAYER_get_rbuf(&s->rlayer);
*/
return 1;
}
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
if (!dtls1_process_record(s))
return (0);
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
if (!dtls1_process_record(s))
return (0);
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
SSL3_RECORD_get_seq_num(s->rlayer.rrec)) <
0)
return -1;
}
}
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
return (1);
}
Commit Message:
CWE ID: CWE-189 | int dtls1_process_buffered_records(SSL *s)
{
pitem *item;
SSL3_BUFFER *rb;
SSL3_RECORD *rr;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
int replayok = 1;
item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
if (item) {
/* Check if epoch is current. */
if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
return 1; /* Nothing to do. */
rr = RECORD_LAYER_get_rrec(&s->rlayer);
rb = RECORD_LAYER_get_rbuf(&s->rlayer);
*/
return 1;
}
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
if (!dtls1_process_record(s))
return (0);
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
/* Process all the records. */
while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
dtls1_get_unprocessed_record(s);
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if (bitmap == NULL) {
/*
* Should not happen. This will only ever be NULL when the
* current record is from a different epoch. But that cannot
* be the case because we already checked the epoch above
*/
SSLerr(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS,
ERR_R_INTERNAL_ERROR);
return 0;
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
#endif
{
/*
* Check whether this is a repeat, or aged record. We did this
* check once already when we first received the record - but
* we might have updated the window since then due to
* records we subsequently processed.
*/
replayok = dtls1_record_replay_check(s, bitmap);
}
if (!replayok || !dtls1_process_record(s, bitmap)) {
/* dump this record */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
continue;
}
if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0)
return 0;
}
}
* here, anything else is handled by higher layers
* Application data protocol
* none of our business
*/
s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
return 1;
}
| 165,194 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(GlobIterator, count)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) {
RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL));
} else {
/* should not happen */
php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state");
}
}
| 167,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg)
{
int nid;
long ret;
nid = OBJ_obj2nid(p7->type);
switch (cmd) {
case PKCS7_OP_SET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
ret = p7->detached = (int)larg;
ASN1_OCTET_STRING *os;
os = p7->d.sign->contents->d.data;
ASN1_OCTET_STRING_free(os);
p7->d.sign->contents->d.data = NULL;
}
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
case PKCS7_OP_GET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
if (!p7->d.sign || !p7->d.sign->contents->d.ptr)
ret = 1;
else
ret = 0;
p7->detached = ret;
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION);
ret = 0;
}
Commit Message:
CWE ID: | long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg)
{
int nid;
long ret;
nid = OBJ_obj2nid(p7->type);
switch (cmd) {
/* NOTE(emilia): does not support detached digested data. */
case PKCS7_OP_SET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
ret = p7->detached = (int)larg;
ASN1_OCTET_STRING *os;
os = p7->d.sign->contents->d.data;
ASN1_OCTET_STRING_free(os);
p7->d.sign->contents->d.data = NULL;
}
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
case PKCS7_OP_GET_DETACHED_SIGNATURE:
if (nid == NID_pkcs7_signed) {
if (!p7->d.sign || !p7->d.sign->contents->d.ptr)
ret = 1;
else
ret = 0;
p7->detached = ret;
} else {
PKCS7err(PKCS7_F_PKCS7_CTRL,
PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE);
ret = 0;
}
break;
default:
PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION);
ret = 0;
}
| 164,808 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t read_entry(
git_index_entry **out,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return 0;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return 0;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return 0;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return 0;
}
git__free(tmp_path);
return entry_size;
}
Commit Message: index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415 | static size_t read_entry(
static int read_entry(
git_index_entry **out,
size_t *out_size,
git_index *index,
const void *buffer,
size_t buffer_size,
const char *last)
{
size_t path_length, entry_size;
const char *path_ptr;
struct entry_short source;
git_index_entry entry = {{0}};
bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP;
char *tmp_path = NULL;
if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size)
return -1;
/* buffer is not guaranteed to be aligned */
memcpy(&source, buffer, sizeof(struct entry_short));
entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds);
entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds);
entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds);
entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds);
entry.dev = ntohl(source.dev);
entry.ino = ntohl(source.ino);
entry.mode = ntohl(source.mode);
entry.uid = ntohl(source.uid);
entry.gid = ntohl(source.gid);
entry.file_size = ntohl(source.file_size);
git_oid_cpy(&entry.id, &source.oid);
entry.flags = ntohs(source.flags);
if (entry.flags & GIT_IDXENTRY_EXTENDED) {
uint16_t flags_raw;
size_t flags_offset;
flags_offset = offsetof(struct entry_long, flags_extended);
memcpy(&flags_raw, (const char *) buffer + flags_offset,
sizeof(flags_raw));
flags_raw = ntohs(flags_raw);
memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw));
path_ptr = (const char *) buffer + offsetof(struct entry_long, path);
} else
path_ptr = (const char *) buffer + offsetof(struct entry_short, path);
if (!compressed) {
path_length = entry.flags & GIT_IDXENTRY_NAMEMASK;
/* if this is a very long string, we must find its
* real length without overflowing */
if (path_length == 0xFFF) {
const char *path_end;
path_end = memchr(path_ptr, '\0', buffer_size);
if (path_end == NULL)
return -1;
path_length = path_end - path_ptr;
}
entry_size = index_entry_size(path_length, 0, entry.flags);
entry.path = (char *)path_ptr;
} else {
size_t varint_len;
size_t strip_len = git_decode_varint((const unsigned char *)path_ptr,
&varint_len);
size_t last_len = strlen(last);
size_t prefix_len = last_len - strip_len;
size_t suffix_len = strlen(path_ptr + varint_len);
size_t path_len;
if (varint_len == 0)
return index_error_invalid("incorrect prefix length");
GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len);
GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1);
tmp_path = git__malloc(path_len);
GITERR_CHECK_ALLOC(tmp_path);
memcpy(tmp_path, last, prefix_len);
memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1);
entry_size = index_entry_size(suffix_len, varint_len, entry.flags);
entry.path = tmp_path;
}
if (entry_size == 0)
return -1;
if (INDEX_FOOTER_SIZE + entry_size > buffer_size)
return -1;
if (index_entry_dup(out, index, &entry) < 0) {
git__free(tmp_path);
return -1;
}
git__free(tmp_path);
*out_size = entry_size;
return 0;
}
| 169,300 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
Commit Message: Fix ParseElementHeader to support 0 payload elements
Cherry-pick'ing Change 5c83bbec9a5f6f00a349674ddad85b753d2ea219
from upstream. This fixes regression in some edge cases for mkv
playback.
BUG=26499283
Change-Id: I88de03219a3d941b6b2f251d384e29c36bdd4d9b
CWE ID: CWE-20 | long ParseElementHeader(IMkvReader* pReader, long long& pos,
long long stop, long long& id,
long long& size) {
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
long len;
id = ReadID(pReader, pos, len);
if (id < 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
if (stop >= 0 && pos >= stop)
return E_FILE_FORMAT_INVALID;
size = ReadUInt(pReader, pos, len);
if (size < 0 || len < 1 || len > 8) {
return E_FILE_FORMAT_INVALID;
}
const unsigned long long rollover_check =
static_cast<unsigned long long>(pos) + len;
if (rollover_check > LONG_LONG_MAX)
return E_FILE_FORMAT_INVALID;
pos += len; // consume length of size
if (stop >= 0 && pos > stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 174,229 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reflectStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
Element* impl = V8Element::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::reflectstringattributeAttr, cppValue);
}
Commit Message: binding: Removes unused code in templates/attributes.cpp.
Faking {{cpp_class}} and {{c8_class}} doesn't make sense.
Probably it made sense before the introduction of virtual
ScriptWrappable::wrap().
Checking the existence of window->document() doesn't seem
making sense to me, and CQ tests seem passing without the
check.
BUG=
Review-Url: https://codereview.chromium.org/2268433002
Cr-Commit-Position: refs/heads/master@{#413375}
CWE ID: CWE-189 | static void reflectStringAttributeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
TestInterfaceNode* impl = V8TestInterfaceNode::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
impl->setAttribute(HTMLNames::reflectstringattributeAttr, cppValue);
}
| 171,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state == OMX_StateInvalid) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID: | OMX_ERRORTYPE omx_vdec::empty_this_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
OMX_ERRORTYPE ret1 = OMX_ErrorNone;
unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount;
if (m_state != OMX_StateExecuting &&
m_state != OMX_StatePause &&
m_state != OMX_StateIdle) {
DEBUG_PRINT_ERROR("Empty this buffer in Invalid State");
return OMX_ErrorInvalidState;
}
if (buffer == NULL) {
DEBUG_PRINT_ERROR("ERROR:ETB Buffer is NULL");
return OMX_ErrorBadParameter;
}
if (!m_inp_bEnabled) {
DEBUG_PRINT_ERROR("ERROR:ETB incorrect state operation, input port is disabled.");
return OMX_ErrorIncorrectStateOperation;
}
if (buffer->nInputPortIndex != OMX_CORE_INPUT_PORT_INDEX) {
DEBUG_PRINT_ERROR("ERROR:ETB invalid port in header %u", (unsigned int)buffer->nInputPortIndex);
return OMX_ErrorBadPortIndex;
}
#ifdef _ANDROID_
if (iDivXDrmDecrypt) {
OMX_ERRORTYPE drmErr = iDivXDrmDecrypt->Decrypt(buffer);
if (drmErr != OMX_ErrorNone) {
DEBUG_PRINT_LOW("ERROR:iDivXDrmDecrypt->Decrypt %d", drmErr);
}
}
#endif //_ANDROID_
if (perf_flag) {
if (!latency) {
dec_time.stop();
latency = dec_time.processing_time_us();
dec_time.start();
}
}
if (arbitrary_bytes) {
nBufferIndex = buffer - m_inp_heap_ptr;
} else {
if (input_use_buffer == true) {
nBufferIndex = buffer - m_inp_heap_ptr;
m_inp_mem_ptr[nBufferIndex].nFilledLen = m_inp_heap_ptr[nBufferIndex].nFilledLen;
m_inp_mem_ptr[nBufferIndex].nTimeStamp = m_inp_heap_ptr[nBufferIndex].nTimeStamp;
m_inp_mem_ptr[nBufferIndex].nFlags = m_inp_heap_ptr[nBufferIndex].nFlags;
buffer = &m_inp_mem_ptr[nBufferIndex];
DEBUG_PRINT_LOW("Non-Arbitrary mode - buffer address is: malloc %p, pmem%p in Index %d, buffer %p of size %u",
&m_inp_heap_ptr[nBufferIndex], &m_inp_mem_ptr[nBufferIndex],nBufferIndex, buffer, (unsigned int)buffer->nFilledLen);
} else {
nBufferIndex = buffer - m_inp_mem_ptr;
}
}
if (nBufferIndex > drv_ctx.ip_buf.actualcount ) {
DEBUG_PRINT_ERROR("ERROR:ETB nBufferIndex is invalid");
return OMX_ErrorBadParameter;
}
if (buffer->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
codec_config_flag = true;
DEBUG_PRINT_LOW("%s: codec_config buffer", __FUNCTION__);
}
DEBUG_PRINT_LOW("[ETB] BHdr(%p) pBuf(%p) nTS(%lld) nFL(%u)",
buffer, buffer->pBuffer, buffer->nTimeStamp, (unsigned int)buffer->nFilledLen);
if (arbitrary_bytes) {
post_event ((unsigned long)hComp,(unsigned long)buffer,
OMX_COMPONENT_GENERATE_ETB_ARBITRARY);
} else {
post_event ((unsigned long)hComp,(unsigned long)buffer,OMX_COMPONENT_GENERATE_ETB);
}
time_stamp_dts.insert_timestamp(buffer);
return OMX_ErrorNone;
}
| 173,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(locale_get_display_language)
{
get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_get_display_language)
PHP_FUNCTION(locale_get_display_language)
{
get_icu_disp_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,186 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event,
const WebWindowFeatures& features) {
//// Check that the desired NavigationPolicy |policy| is compatible with the
//// observed input event |current_event|.
bool as_popup = !features.tool_bar_visible || !features.status_bar_visible ||
!features.scrollbars_visible || !features.menu_bar_visible ||
!features.resizable;
NavigationPolicy policy =
as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab;
UpdatePolicyForEvent(current_event, &policy);
return policy;
}
Commit Message: Only allow downloading in response to real keyboard modifiers
BUG=848531
Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf
Reviewed-on: https://chromium-review.googlesource.com/1082216
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564051}
CWE ID: | NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event,
} // anonymous namespace
//// Check that the desired NavigationPolicy |policy| is compatible with the
//// observed input event |current_event|.
NavigationPolicy EffectiveNavigationPolicy(NavigationPolicy policy,
const WebInputEvent* current_event,
const WebWindowFeatures& features) {
bool as_popup = !features.tool_bar_visible || !features.status_bar_visible ||
!features.scrollbars_visible || !features.menu_bar_visible ||
!features.resizable;
NavigationPolicy user_policy =
as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab;
| 173,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProcPutImage(ClientPtr client)
{
GC *pGC;
DrawablePtr pDraw;
long length; /* length of scanline server padded */
long lengthProto; /* length of scanline protocol padded */
char *tmpImage;
REQUEST(xPutImageReq);
REQUEST_AT_LEAST_SIZE(xPutImageReq);
VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess);
if (stuff->format == XYBitmap) {
if ((stuff->depth != 1) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
}
else if (stuff->format == XYPixmap) {
if ((pDraw->depth != stuff->depth) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
length *= stuff->depth;
}
else if (stuff->format == ZPixmap) {
if ((pDraw->depth != stuff->depth) || (stuff->leftPad != 0))
return BadMatch;
length = PixmapBytePad(stuff->width, stuff->depth);
}
else {
client->errorValue = stuff->format;
return BadValue;
}
tmpImage = (char *) &stuff[1];
lengthProto = length;
if (lengthProto >= (INT32_MAX / stuff->height))
return BadLength;
if ((bytes_to_int32(lengthProto * stuff->height) +
bytes_to_int32(sizeof(xPutImageReq))) != client->req_len)
return BadLength;
ReformatImage(tmpImage, lengthProto * stuff->height,
stuff->format == ZPixmap ? BitsPerPixel(stuff->depth) : 1,
ClientOrder(client));
(*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, stuff->dstX, stuff->dstY,
stuff->width, stuff->height,
stuff->leftPad, stuff->format, tmpImage);
return Success;
}
Commit Message:
CWE ID: CWE-369 | ProcPutImage(ClientPtr client)
{
GC *pGC;
DrawablePtr pDraw;
long length; /* length of scanline server padded */
long lengthProto; /* length of scanline protocol padded */
char *tmpImage;
REQUEST(xPutImageReq);
REQUEST_AT_LEAST_SIZE(xPutImageReq);
VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess);
if (stuff->format == XYBitmap) {
if ((stuff->depth != 1) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
}
else if (stuff->format == XYPixmap) {
if ((pDraw->depth != stuff->depth) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
length *= stuff->depth;
}
else if (stuff->format == ZPixmap) {
if ((pDraw->depth != stuff->depth) || (stuff->leftPad != 0))
return BadMatch;
length = PixmapBytePad(stuff->width, stuff->depth);
}
else {
client->errorValue = stuff->format;
return BadValue;
}
tmpImage = (char *) &stuff[1];
lengthProto = length;
if (stuff->height != 0 && lengthProto >= (INT32_MAX / stuff->height))
return BadLength;
if ((bytes_to_int32(lengthProto * stuff->height) +
bytes_to_int32(sizeof(xPutImageReq))) != client->req_len)
return BadLength;
ReformatImage(tmpImage, lengthProto * stuff->height,
stuff->format == ZPixmap ? BitsPerPixel(stuff->depth) : 1,
ClientOrder(client));
(*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, stuff->dstX, stuff->dstY,
stuff->width, stuff->height,
stuff->leftPad, stuff->format, tmpImage);
return Success;
}
| 165,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
int atomic)
{
unsigned long copy;
while (len > 0) {
while (!iov->iov_len)
iov++;
copy = min_t(unsigned long, len, iov->iov_len);
if (atomic) {
if (__copy_to_user_inatomic(iov->iov_base, from, copy))
return -EFAULT;
} else {
if (copy_to_user(iov->iov_base, from, copy))
return -EFAULT;
}
from += copy;
len -= copy;
iov->iov_base += copy;
iov->iov_len -= copy;
}
return 0;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_iov_copy_to_user(struct iovec *iov, const void *from, unsigned long len,
| 169,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base.
*/
size_t off = 0, len = 0;
if (cmd & 0x01) off = *delta++;
if (cmd & 0x02) off |= *delta++ << 8UL;
if (cmd & 0x04) off |= *delta++ << 16UL;
if (cmd & 0x08) off |= *delta++ << 24UL;
if (cmd & 0x10) len = *delta++;
if (cmd & 0x20) len |= *delta++ << 8UL;
if (cmd & 0x40) len |= *delta++ << 16UL;
if (!len) len = 0x10000;
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
}
else if (cmd) {
/* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
}
else {
/* cmd == 0 is reserved for future encodings.
*/
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
Commit Message: delta: fix sign-extension of big left-shift
Our delta code was originally adapted from JGit, which itself adapted it
from git itself. Due to this heritage, we inherited a bug from git.git
in how we compute the delta offset, which was fixed upstream in
48fb7deb5 (Fix big left-shifts of unsigned char, 2009-06-17). As
explained by Linus:
Shifting 'unsigned char' or 'unsigned short' left can result in sign
extension errors, since the C integer promotion rules means that the
unsigned char/short will get implicitly promoted to a signed 'int' due to
the shift (or due to other operations).
This normally doesn't matter, but if you shift things up sufficiently, it
will now set the sign bit in 'int', and a subsequent cast to a bigger type
(eg 'long' or 'unsigned long') will now sign-extend the value despite the
original expression being unsigned.
One example of this would be something like
unsigned long size;
unsigned char c;
size += c << 24;
where despite all the variables being unsigned, 'c << 24' ends up being a
signed entity, and will get sign-extended when then doing the addition in
an 'unsigned long' type.
Since git uses 'unsigned char' pointers extensively, we actually have this
bug in a couple of places.
In our delta code, we inherited such a bogus shift when computing the
offset at which the delta base is to be found. Due to the sign extension
we can end up with an offset where all the bits are set. This can allow
an arbitrary memory read, as the addition in `base_len < off + len` can
now overflow if `off` has all its bits set.
Fix the issue by casting the result of `*delta++ << 24UL` to an unsigned
integer again. Add a test with a crafted delta that would actually
succeed with an out-of-bounds read in case where the cast wouldn't
exist.
Reported-by: Riccardo Schirone <[email protected]>
Test-provided-by: Riccardo Schirone <[email protected]>
CWE ID: CWE-125 | int git_delta_apply(
void **out,
size_t *out_len,
const unsigned char *base,
size_t base_len,
const unsigned char *delta,
size_t delta_len)
{
const unsigned char *delta_end = delta + delta_len;
size_t base_sz, res_sz, alloc_sz;
unsigned char *res_dp;
*out = NULL;
*out_len = 0;
/*
* Check that the base size matches the data we were given;
* if not we would underflow while accessing data from the
* base object, resulting in data corruption or segfault.
*/
if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
if (hdr_sz(&res_sz, &delta, delta_end) < 0) {
giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data");
return -1;
}
GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1);
res_dp = git__malloc(alloc_sz);
GITERR_CHECK_ALLOC(res_dp);
res_dp[res_sz] = '\0';
*out = res_dp;
*out_len = res_sz;
while (delta < delta_end) {
unsigned char cmd = *delta++;
if (cmd & 0x80) {
/* cmd is a copy instruction; copy from the base. */
size_t off = 0, len = 0;
if (cmd & 0x01) off = *delta++;
if (cmd & 0x02) off |= *delta++ << 8UL;
if (cmd & 0x04) off |= *delta++ << 16UL;
if (cmd & 0x08) off |= ((unsigned) *delta++ << 24UL);
if (cmd & 0x10) len = *delta++;
if (cmd & 0x20) len |= *delta++ << 8UL;
if (cmd & 0x40) len |= *delta++ << 16UL;
if (!len) len = 0x10000;
if (base_len < off + len || res_sz < len)
goto fail;
memcpy(res_dp, base + off, len);
res_dp += len;
res_sz -= len;
} else if (cmd) {
/*
* cmd is a literal insert instruction; copy from
* the delta stream itself.
*/
if (delta_end - delta < cmd || res_sz < cmd)
goto fail;
memcpy(res_dp, delta, cmd);
delta += cmd;
res_dp += cmd;
res_sz -= cmd;
} else {
/* cmd == 0 is reserved for future encodings. */
goto fail;
}
}
if (delta != delta_end || res_sz)
goto fail;
return 0;
fail:
git__free(*out);
*out = NULL;
*out_len = 0;
giterr_set(GITERR_INVALID, "failed to apply delta");
return -1;
}
| 170,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DelegatedFrameHost::CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& dst_size,
const base::Callback<void(bool, const SkBitmap&)>& callback,
const SkColorType color_type) {
bool format_support = ((color_type == kRGB_565_SkColorType) ||
(color_type == kN32_SkColorType));
DCHECK(format_support);
if (!CanCopyToBitmap()) {
callback.Run(false, SkBitmap());
return;
}
const gfx::Size& dst_size_in_pixel =
client_->ConvertViewSizeToPixel(dst_size);
scoped_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateRequest(base::Bind(
&DelegatedFrameHost::CopyFromCompositingSurfaceHasResult,
dst_size_in_pixel,
color_type,
callback));
gfx::Rect src_subrect_in_pixel =
ConvertRectToPixel(client_->CurrentDeviceScaleFactor(), src_subrect);
request->set_area(src_subrect_in_pixel);
client_->RequestCopyOfOutput(request.Pass());
}
Commit Message: repairs CopyFromCompositingSurface in HighDPI
This CL removes the DIP=>Pixel transform in
DelegatedFrameHost::CopyFromCompositingSurface(), because said
transformation seems to be happening later in the copy logic
and is currently being applied twice.
BUG=397708
Review URL: https://codereview.chromium.org/421293002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286414 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DelegatedFrameHost::CopyFromCompositingSurface(
const gfx::Rect& src_subrect,
const gfx::Size& output_size,
const base::Callback<void(bool, const SkBitmap&)>& callback,
const SkColorType color_type) {
bool format_support = ((color_type == kRGB_565_SkColorType) ||
(color_type == kN32_SkColorType));
DCHECK(format_support);
if (!CanCopyToBitmap()) {
callback.Run(false, SkBitmap());
return;
}
scoped_ptr<cc::CopyOutputRequest> request =
cc::CopyOutputRequest::CreateRequest(base::Bind(
&DelegatedFrameHost::CopyFromCompositingSurfaceHasResult,
output_size,
color_type,
callback));
request->set_area(src_subrect);
client_->RequestCopyOfOutput(request.Pass());
}
| 171,193 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
Commit Message: ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: [email protected]
Signed-off-by: Lars-Peter Clausen <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-20 | static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb)
{
ext3_fsblk_t sb_block;
char *options = (char *) *data;
if (!options || strncmp(options, "sb=", 3) != 0)
return 1; /* Default location */
options += 3;
/*todo: use simple_strtoll with >32bit ext3 */
sb_block = simple_strtoul(options, &options, 0);
if (*options && *options != ',') {
ext3_msg(sb, KERN_ERR, "error: invalid sb specification: %s",
(char *) *data);
return 1;
}
if (*options == ',')
options++;
*data = (void *) options;
return sb_block;
}
| 166,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PassOwnPtr<WebCore::GraphicsContext> LayerTreeCoordinator::beginContentUpdate(const WebCore::IntSize& size, ShareableBitmap::Flags flags, ShareableSurface::Handle& handle, WebCore::IntPoint& offset)
{
OwnPtr<WebCore::GraphicsContext> graphicsContext;
for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
UpdateAtlas* atlas = m_updateAtlases[i].get();
if (atlas->flags() == flags) {
graphicsContext = atlas->beginPaintingOnAvailableBuffer(handle, size, offset);
if (graphicsContext)
return graphicsContext.release();
}
}
static const int ScratchBufferDimension = 1024; // Should be a power of two.
m_updateAtlases.append(adoptPtr(new UpdateAtlas(ScratchBufferDimension, flags)));
return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(handle, size, offset);
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | PassOwnPtr<WebCore::GraphicsContext> LayerTreeCoordinator::beginContentUpdate(const WebCore::IntSize& size, ShareableBitmap::Flags flags, ShareableSurface::Handle& handle, WebCore::IntPoint& offset)
{
OwnPtr<WebCore::GraphicsContext> graphicsContext;
for (unsigned i = 0; i < m_updateAtlases.size(); ++i) {
UpdateAtlas* atlas = m_updateAtlases[i].get();
if (atlas->flags() == flags) {
graphicsContext = atlas->beginPaintingOnAvailableBuffer(handle, size, offset);
if (graphicsContext)
return graphicsContext.release();
}
}
static const int ScratchBufferDimension = 1024; // Should be a power of two.
m_updateAtlases.append(adoptPtr(new UpdateAtlas(ScratchBufferDimension, flags)));
scheduleReleaseInactiveAtlases();
return m_updateAtlases.last()->beginPaintingOnAvailableBuffer(handle, size, offset);
}
| 170,269 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PaymentRequest::PaymentRequest(
content::RenderFrameHost* render_frame_host,
content::WebContents* web_contents,
std::unique_ptr<ContentPaymentRequestDelegate> delegate,
PaymentRequestWebContentsManager* manager,
PaymentRequestDisplayManager* display_manager,
mojo::InterfaceRequest<mojom::PaymentRequest> request,
ObserverForTest* observer_for_testing)
: web_contents_(web_contents),
delegate_(std::move(delegate)),
manager_(manager),
display_manager_(display_manager),
display_handle_(nullptr),
binding_(this, std::move(request)),
top_level_origin_(url_formatter::FormatUrlForSecurityDisplay(
web_contents_->GetLastCommittedURL())),
frame_origin_(url_formatter::FormatUrlForSecurityDisplay(
render_frame_host->GetLastCommittedURL())),
observer_for_testing_(observer_for_testing),
journey_logger_(delegate_->IsIncognito(),
ukm::GetSourceIdForWebContentsDocument(web_contents)),
weak_ptr_factory_(this) {
binding_.set_connection_error_handler(base::BindOnce(
&PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr()));
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | PaymentRequest::PaymentRequest(
content::RenderFrameHost* render_frame_host,
content::WebContents* web_contents,
std::unique_ptr<ContentPaymentRequestDelegate> delegate,
PaymentRequestWebContentsManager* manager,
PaymentRequestDisplayManager* display_manager,
mojo::InterfaceRequest<mojom::PaymentRequest> request,
ObserverForTest* observer_for_testing)
: web_contents_(web_contents),
log_(web_contents_),
delegate_(std::move(delegate)),
manager_(manager),
display_manager_(display_manager),
display_handle_(nullptr),
binding_(this, std::move(request)),
top_level_origin_(url_formatter::FormatUrlForSecurityDisplay(
web_contents_->GetLastCommittedURL())),
frame_origin_(url_formatter::FormatUrlForSecurityDisplay(
render_frame_host->GetLastCommittedURL())),
observer_for_testing_(observer_for_testing),
journey_logger_(delegate_->IsIncognito(),
ukm::GetSourceIdForWebContentsDocument(web_contents)),
weak_ptr_factory_(this) {
binding_.set_connection_error_handler(base::BindOnce(
&PaymentRequest::OnConnectionTerminated, weak_ptr_factory_.GetWeakPtr()));
}
| 173,084 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport MagickBooleanType SetQuantumDepth(const Image *image,
QuantumInfo *quantum_info,const size_t depth)
{
size_t
extent,
quantum;
/*
Allocate the quantum pixel buffer.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickSignature);
quantum_info->depth=depth;
if (quantum_info->format == FloatingPointQuantumFormat)
{
if (quantum_info->depth > 32)
quantum_info->depth=64;
else
if (quantum_info->depth > 16)
quantum_info->depth=32;
else
quantum_info->depth=16;
}
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;
extent=image->columns*quantum;
if (quantum != (extent/image->columns))
return(MagickFalse);
return(AcquireQuantumPixels(quantum_info,extent));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/110
CWE ID: CWE-369 | MagickExport MagickBooleanType SetQuantumDepth(const Image *image,
QuantumInfo *quantum_info,const size_t depth)
{
size_t
extent,
quantum;
/*
Allocate the quantum pixel buffer.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(quantum_info != (QuantumInfo *) NULL);
assert(quantum_info->signature == MagickSignature);
quantum_info->depth=depth;
if (quantum_info->format == FloatingPointQuantumFormat)
{
if (quantum_info->depth > 32)
quantum_info->depth=64;
else
if (quantum_info->depth > 16)
quantum_info->depth=32;
else
quantum_info->depth=16;
}
if (quantum_info->pixels != (unsigned char **) NULL)
DestroyQuantumPixels(quantum_info);
quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8;
extent=image->columns*quantum;
if ((image->columns != 0) && (quantum != (extent/image->columns)))
return(MagickFalse);
return(AcquireQuantumPixels(quantum_info,extent));
}
| 170,113 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) {
auto it = instance_map_.find(instance);
DCHECK(it != instance_map_.end());
for (auto& observer : it->second->observer_list)
observer.OnHostDestroyed();
instance_map_.erase(it);
}
Commit Message: Validate in-process plugin instance messages.
Bug: 733548, 733549
Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba
Reviewed-on: https://chromium-review.googlesource.com/538908
Commit-Queue: Bill Budge <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480696}
CWE ID: CWE-20 | void BrowserPpapiHostImpl::DeleteInstance(PP_Instance instance) {
// NOTE: 'instance' may be coming from a compromised renderer process. We
// take care here to make sure an attacker can't cause a UAF by deleting a
// non-existent plugin instance.
// See http://crbug.com/733548.
auto it = instance_map_.find(instance);
if (it != instance_map_.end()) {
// We need to tell the observers for that instance that we are destroyed
// because we won't have the opportunity to once we remove them from the
// |instance_map_|. If the instance was deleted, observers for those
// instances should never call back into the host anyway, so it is safe to
// tell them that the host is destroyed.
for (auto& observer : it->second->observer_list)
observer.OnHostDestroyed();
instance_map_.erase(it);
} else {
NOTREACHED();
}
}
| 172,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
Commit Message: bplist: Fix data range check for string/data/dict/array nodes
Passing a size of 0xFFFFFFFFFFFFFFFF to parse_string_node() might result
in a memcpy with a size of -1, leading to undefined behavior.
This commit makes sure that the actual node data (which depends on the size)
is in the range start_of_object..start_of_object+size.
Credit to OSS-Fuzz
CWE ID: CWE-787 | static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)
{
uint16_t type = 0;
uint64_t size = 0;
if (!object)
return NULL;
type = (**object) & BPLIST_MASK;
size = (**object) & BPLIST_FILL;
(*object)++;
if (size == BPLIST_FILL) {
switch (type) {
case BPLIST_DATA:
case BPLIST_STRING:
case BPLIST_UNICODE:
case BPLIST_ARRAY:
case BPLIST_SET:
case BPLIST_DICT:
{
uint16_t next_size = **object & BPLIST_FILL;
if ((**object & BPLIST_MASK) != BPLIST_UINT) {
PLIST_BIN_ERR("%s: invalid size node type for node type 0x%02x: found 0x%02x, expected 0x%02x\n", __func__, type, **object & BPLIST_MASK, BPLIST_UINT);
return NULL;
}
(*object)++;
next_size = 1 << next_size;
if (*object + next_size > bplist->offset_table) {
PLIST_BIN_ERR("%s: size node data bytes for node type 0x%02x point outside of valid range\n", __func__, type);
return NULL;
}
size = UINT_TO_HOST(*object, next_size);
(*object) += next_size;
break;
}
default:
break;
}
}
switch (type)
{
case BPLIST_NULL:
switch (size)
{
case BPLIST_TRUE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = TRUE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_FALSE:
{
plist_data_t data = plist_new_plist_data();
data->type = PLIST_BOOLEAN;
data->boolval = FALSE;
data->length = 1;
return node_create(NULL, data);
}
case BPLIST_NULL:
default:
return NULL;
}
case BPLIST_UINT:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UINT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uint_node(object, size);
case BPLIST_REAL:
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_REAL data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_real_node(object, size);
case BPLIST_DATE:
if (3 != size) {
PLIST_BIN_ERR("%s: invalid data size for BPLIST_DATE node\n", __func__);
return NULL;
}
if (*object + (uint64_t)(1 << size) > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_date_node(object, size);
case BPLIST_DATA:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DATA data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_data_node(object, size);
case BPLIST_STRING:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_STRING data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_string_node(object, size);
case BPLIST_UNICODE:
if (size*2 < size) {
PLIST_BIN_ERR("%s: Integer overflow when calculating BPLIST_UNICODE data size.\n", __func__);
return NULL;
}
if (*object + size*2 < *object || *object + size*2 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UNICODE data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_unicode_node(object, size);
case BPLIST_SET:
case BPLIST_ARRAY:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_ARRAY data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_array_node(bplist, object, size);
case BPLIST_UID:
if (*object + size+1 > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_UID data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_uid_node(object, size);
case BPLIST_DICT:
if (*object + size < *object || *object + size > bplist->offset_table) {
PLIST_BIN_ERR("%s: BPLIST_DICT data bytes point outside of valid range\n", __func__);
return NULL;
}
return parse_dict_node(bplist, object, size);
default:
PLIST_BIN_ERR("%s: unexpected node type 0x%02x\n", __func__, type);
return NULL;
}
return NULL;
}
| 168,334 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
Commit Message: CVE-2017-13025/IPv6 mobility: Add a bounds check before fetching data
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't cause 'tcpdump: pcap_loop: truncated dump file'
CWE ID: CWE-125 | mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_TCHECK_128BITS(&bp[i+2]);
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_TCHECK_16BITS(&bp[i+2]);
ND_TCHECK_16BITS(&bp[i+4]);
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
| 167,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
Commit Message: KEYS: close race between key lookup and freeing
When a key is being garbage collected, it's key->user would get put before
the ->destroy() callback is called, where the key is removed from it's
respective tracking structures.
This leaves a key hanging in a semi-invalid state which leaves a window open
for a different task to try an access key->user. An example is
find_keyring_by_name() which would dereference key->user for a key that is
in the process of being garbage collected (where key->user was freed but
->destroy() wasn't called yet - so it's still present in the linked list).
This would cause either a panic, or corrupt memory.
Fixes CVE-2014-9529.
Signed-off-by: Sasha Levin <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-362 | static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
/* now throw away the key memory */
if (key->type->destroy)
key->type->destroy(key);
key_user_put(key->user);
kfree(key->description);
#ifdef KEY_DEBUGGING
key->magic = KEY_DEBUG_MAGIC_X;
#endif
kmem_cache_free(key_jar, key);
}
}
| 166,783 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
Commit Message: unix: avoid use-after-free in ep_remove_wait_queue
Rainer Weikusat <[email protected]> writes:
An AF_UNIX datagram socket being the client in an n:1 association with
some server socket is only allowed to send messages to the server if the
receive queue of this socket contains at most sk_max_ack_backlog
datagrams. This implies that prospective writers might be forced to go
to sleep despite none of the message presently enqueued on the server
receive queue were sent by them. In order to ensure that these will be
woken up once space becomes again available, the present unix_dgram_poll
routine does a second sock_poll_wait call with the peer_wait wait queue
of the server socket as queue argument (unix_dgram_recvmsg does a wake
up on this queue after a datagram was received). This is inherently
problematic because the server socket is only guaranteed to remain alive
for as long as the client still holds a reference to it. In case the
connection is dissolved via connect or by the dead peer detection logic
in unix_dgram_sendmsg, the server socket may be freed despite "the
polling mechanism" (in particular, epoll) still has a pointer to the
corresponding peer_wait queue. There's no way to forcibly deregister a
wait queue with epoll.
Based on an idea by Jason Baron, the patch below changes the code such
that a wait_queue_t belonging to the client socket is enqueued on the
peer_wait queue of the server whenever the peer receive queue full
condition is detected by either a sendmsg or a poll. A wake up on the
peer queue is then relayed to the ordinary wait queue of the client
socket via wake function. The connection to the peer wait queue is again
dissolved if either a wake up is about to be relayed or the client
socket reconnects or a dead peer is detected or the client socket is
itself closed. This enables removing the second sock_poll_wait from
unix_dgram_poll, thus avoiding the use-after-free, while still ensuring
that no blocked writer sleeps forever.
Signed-off-by: Rainer Weikusat <[email protected]>
Fixes: ec0d215f9420 ("af_unix: fix 'poll for write'/connected DGRAM sockets")
Reviewed-by: Jason Baron <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
| 166,834 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
Commit Message: Fix buffer overrun (issue #678). Add assert for detecting this kind of issues earlier.
CWE ID: CWE-125 | int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
if (bytes_matched + i >= max_bytes_matched)
break;
next_input = input + i * input_incr;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
bytes_matched = yr_min(bytes_matched, max_bytes_matched);
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
| 168,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
uint32_t lun, void *hba_private)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
SCSIRequest *req;
SCSIDiskReq *r;
req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
r = DO_UPCAST(SCSIDiskReq, req, req);
r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);
return req;
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119 | static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,
uint32_t lun, void *hba_private)
{
SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);
SCSIRequest *req;
req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);
return req;
}
| 166,555 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WarmupURLFetcher::FetchWarmupURL(
size_t previous_attempt_counts,
const DataReductionProxyServer& proxy_server) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
previous_attempt_counts_ = previous_attempt_counts;
DCHECK_LE(0u, previous_attempt_counts_);
DCHECK_GE(2u, previous_attempt_counts_);
fetch_delay_timer_.Stop();
if (previous_attempt_counts_ == 0) {
FetchWarmupURLNow(proxy_server);
return;
}
fetch_delay_timer_.Start(
FROM_HERE, GetFetchWaitTime(),
base::BindOnce(&WarmupURLFetcher::FetchWarmupURLNow,
base::Unretained(this), proxy_server));
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | void WarmupURLFetcher::FetchWarmupURL(
size_t previous_attempt_counts,
const DataReductionProxyServer& proxy_server) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
previous_attempt_counts_ = previous_attempt_counts;
DCHECK_LE(0u, previous_attempt_counts_);
DCHECK_GE(2u, previous_attempt_counts_);
fetch_delay_timer_.Stop();
if (previous_attempt_counts_ == 0) {
FetchWarmupURLNow(proxy_server);
return;
}
fetch_delay_timer_.Start(
FROM_HERE, GetFetchWaitTime(),
base::BindOnce(&WarmupURLFetcher::FetchWarmupURLNow,
base::Unretained(this), proxy_server));
}
| 172,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int Chapters::GetEditionCount() const
{
return m_editions_count;
}
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 | int Chapters::GetEditionCount() const
const Chapters::Edition* Chapters::GetEdition(int idx) const {
if (idx < 0)
return NULL;
if (idx >= m_editions_count)
return NULL;
return m_editions + idx;
}
| 174,311 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() {
DCHECK(main_message_loop_proxy_->BelongsToCurrentThread());
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL;
}
Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr
Its lifetime is scoped to the RenderFrame, and it might go away before the
hosts that refer to it.
BUG=423030
Review URL: https://codereview.chromium.org/653243003
Cr-Commit-Position: refs/heads/master@{#299897}
CWE ID: CWE-399 | PepperMediaDeviceManager* PepperPlatformAudioInput::GetMediaDeviceManager() {
DCHECK(main_message_loop_proxy_->BelongsToCurrentThread());
RenderFrameImpl* const render_frame =
RenderFrameImpl::FromRoutingID(render_frame_id_);
return render_frame ?
PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL;
}
| 171,609 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::DisplayPinCode(
const dbus::ObjectPath& device_path,
const std::string& pincode) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": DisplayPinCode: " << pincode;
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_DISPLAY_PINCODE,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
pairing_delegate_->DisplayPinCode(this, pincode);
pairing_delegate_used_ = true;
}
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: | void BluetoothDeviceChromeOS::DisplayPinCode(
| 171,223 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _zip_cdir_new(int nentry, struct zip_error *error)
{
struct zip_cdir *cd;
if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry))
== NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
free(cd);
return NULL;
}
/* entries must be initialized by caller */
cd->nentry = nentry;
cd->size = cd->offset = 0;
cd->comment = NULL;
cd->comment_len = 0;
return cd;
}
Commit Message:
CWE ID: CWE-189 | _zip_cdir_new(int nentry, struct zip_error *error)
{
struct zip_cdir *cd;
if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
if ( nentry > ((size_t)-1)/sizeof(*(cd->entry)) || (cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*(size_t)nentry))
== NULL) {
_zip_error_set(error, ZIP_ER_MEMORY, 0);
free(cd);
return NULL;
}
/* entries must be initialized by caller */
cd->nentry = nentry;
cd->size = cd->offset = 0;
cd->comment = NULL;
cd->comment_len = 0;
return cd;
}
| 164,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, **pubkey, *sealdata, *ekeys;
HashTable *pubkeysht;
HashPosition pos;
EVP_PKEY **pkeys;
long * key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys;
unsigned char *buf = NULL, **eks;
char * data; int data_len;
char *method =NULL;
int method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
return;
}
pubkeysht = HASH_OF(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
if (EVP_CIPHER_iv_length(cipher) > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ciphers with modes requiring IV are not supported");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(long), 0);
memset(key_resources, 0, sizeof(*key_resources) * nkeys);
/* get the public keys we are using to seal this data */
zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
i = 0;
while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
&pos) == SUCCESS) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
if (pkeys[i] == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
zend_hash_move_forward_ex(pubkeysht, &pos);
i++;
}
if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
RETVAL_FALSE;
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
#if 0
/* Need this if allow ciphers that require initialization vector */
ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
iv = ivlen ? emalloc(ivlen + 1) : NULL;
#endif
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
EVP_CIPHER_CTX_cleanup(&ctx);
if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
EVP_SealFinal(&ctx, buf + len1, &len2);
if (len1 + len2 > 0) {
zval_dtor(sealdata);
buf[len1 + len2] = '\0';
buf = erealloc(buf, len1 + len2 + 1);
ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
eks[i] = NULL;
}
#if 0
/* If allow ciphers that need IV, we need this */
zval_dtor(*ivec);
if (ivlen) {
iv[ivlen] = '\0';
ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
} else {
ZVAL_EMPTY_STRING(*ivec);
}
#endif
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_cleanup(&ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == -1) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
Commit Message:
CWE ID: CWE-754 | PHP_FUNCTION(openssl_seal)
{
zval *pubkeys, **pubkey, *sealdata, *ekeys;
HashTable *pubkeysht;
HashPosition pos;
EVP_PKEY **pkeys;
long * key_resources; /* so we know what to cleanup */
int i, len1, len2, *eksl, nkeys;
unsigned char *buf = NULL, **eks;
char * data; int data_len;
char *method =NULL;
int method_len = 0;
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX ctx;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
return;
}
pubkeysht = HASH_OF(pubkeys);
nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
if (!nkeys) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
RETURN_FALSE;
}
if (method) {
cipher = EVP_get_cipherbyname(method);
if (!cipher) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
RETURN_FALSE;
}
if (EVP_CIPHER_iv_length(cipher) > 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Ciphers with modes requiring IV are not supported");
RETURN_FALSE;
}
} else {
cipher = EVP_rc4();
}
pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
eks = safe_emalloc(nkeys, sizeof(*eks), 0);
memset(eks, 0, sizeof(*eks) * nkeys);
key_resources = safe_emalloc(nkeys, sizeof(long), 0);
memset(key_resources, 0, sizeof(*key_resources) * nkeys);
/* get the public keys we are using to seal this data */
zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
i = 0;
while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
&pos) == SUCCESS) {
pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
if (pkeys[i] == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
RETVAL_FALSE;
goto clean_exit;
}
eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
zend_hash_move_forward_ex(pubkeysht, &pos);
i++;
}
if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
RETVAL_FALSE;
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
#if 0
/* Need this if allow ciphers that require initialization vector */
ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
iv = ivlen ? emalloc(ivlen + 1) : NULL;
#endif
/* allocate one byte extra to make room for \0 */
buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
EVP_CIPHER_CTX_cleanup(&ctx);
if (EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) <= 0 ||
!EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len) ||
!EVP_SealFinal(&ctx, buf + len1, &len2)) {
RETVAL_FALSE;
efree(buf);
EVP_CIPHER_CTX_cleanup(&ctx);
goto clean_exit;
}
if (len1 + len2 > 0) {
zval_dtor(sealdata);
buf[len1 + len2] = '\0';
buf = erealloc(buf, len1 + len2 + 1);
ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
zval_dtor(ekeys);
array_init(ekeys);
for (i=0; i<nkeys; i++) {
eks[i][eksl[i]] = '\0';
add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
eks[i] = NULL;
}
#if 0
/* If allow ciphers that need IV, we need this */
zval_dtor(*ivec);
if (ivlen) {
iv[ivlen] = '\0';
ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
} else {
ZVAL_EMPTY_STRING(*ivec);
}
#endif
} else {
efree(buf);
}
RETVAL_LONG(len1 + len2);
EVP_CIPHER_CTX_cleanup(&ctx);
clean_exit:
for (i=0; i<nkeys; i++) {
if (key_resources[i] == -1) {
EVP_PKEY_free(pkeys[i]);
}
if (eks[i]) {
efree(eks[i]);
}
}
efree(eks);
efree(eksl);
efree(pkeys);
efree(key_resources);
}
| 164,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: deinterlace_row(png_bytep buffer, png_const_bytep row,
unsigned int pixel_size, png_uint_32 w, int pass)
{
/* The inverse of the above, 'row' is part of row 'y' of the output image,
* in 'buffer'. The image is 'w' wide and this is pass 'pass', distribute
* the pixels of row into buffer and return the number written (to allow
* this to be checked).
*/
png_uint_32 xin, xout, xstep;
xout = PNG_PASS_START_COL(pass);
xstep = 1U<<PNG_PASS_COL_SHIFT(pass);
for (xin=0; xout<w; xout+=xstep)
{
pixel_copy(buffer, xout, row, xin, pixel_size);
++xin;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | deinterlace_row(png_bytep buffer, png_const_bytep row,
| 173,607 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderThread::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThread::Init", 0, "");
#if defined(OS_MACOSX)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
CoInitialize(0);
#endif
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
content::GetContentClient()->renderer()->RenderThreadStarted();
TRACE_EVENT_END_ETW("RenderThread::Init", 0, "");
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void RenderThread::Init() {
TRACE_EVENT_BEGIN_ETW("RenderThread::Init", 0, "");
#if defined(OS_MACOSX)
WebKit::WebView::setUseExternalPopupMenus(true);
#endif
lazy_tls.Pointer()->Set(this);
#if defined(OS_WIN)
if (RenderProcessImpl::InProcessPlugins())
CoInitialize(0);
#endif
suspend_webkit_shared_timer_ = true;
notify_webkit_of_modal_loop_ = true;
plugin_refresh_allowed_ = true;
widget_count_ = 0;
hidden_widget_count_ = 0;
idle_notification_delay_in_s_ = kInitialIdleHandlerDelayS;
task_factory_.reset(new ScopedRunnableMethodFactory<RenderThread>(this));
appcache_dispatcher_.reset(new AppCacheDispatcher(this));
indexed_db_dispatcher_.reset(new IndexedDBDispatcher());
db_message_filter_ = new DBMessageFilter();
AddFilter(db_message_filter_.get());
vc_manager_ = new VideoCaptureImplManager();
AddFilter(vc_manager_->video_capture_message_filter());
audio_input_message_filter_ = new AudioInputMessageFilter();
AddFilter(audio_input_message_filter_.get());
audio_message_filter_ = new AudioMessageFilter();
AddFilter(audio_message_filter_.get());
devtools_agent_message_filter_ = new DevToolsAgentFilter();
AddFilter(devtools_agent_message_filter_.get());
content::GetContentClient()->renderer()->RenderThreadStarted();
TRACE_EVENT_END_ETW("RenderThread::Init", 0, "");
}
| 170,326 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
MyObject *mobject;
mobject = MY_OBJECT (object);
switch (prop_id)
{
case PROP_THIS_IS_A_STRING:
g_free (mobject->this_is_a_string);
mobject->this_is_a_string = g_value_dup_string (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
Commit Message:
CWE ID: CWE-264 | my_object_set_property (GObject *object,
| 165,120 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void ieee80211_if_setup(struct net_device *dev)
{
ether_setup(dev);
dev->netdev_ops = &ieee80211_dataif_ops;
dev->destructor = free_netdev;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264 | static void ieee80211_if_setup(struct net_device *dev)
{
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->netdev_ops = &ieee80211_dataif_ops;
dev->destructor = free_netdev;
}
| 165,739 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int http_open(URLContext *h, const char *uri, int flags,
AVDictionary **options)
{
HTTPContext *s = h->priv_data;
int ret;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
s->filesize = -1;
s->location = av_strdup(uri);
if (!s->location)
return AVERROR(ENOMEM);
if (options)
av_dict_copy(&s->chained_options, *options, 0);
if (s->headers) {
int len = strlen(s->headers);
if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
av_log(h, AV_LOG_WARNING,
"No trailing CRLF found in HTTP header.\n");
ret = av_reallocp(&s->headers, len + 3);
if (ret < 0)
return ret;
s->headers[len] = '\r';
s->headers[len + 1] = '\n';
s->headers[len + 2] = '\0';
}
}
if (s->listen) {
return http_listen(h, uri, flags, options);
}
ret = http_open_cnx(h, options);
if (ret < 0)
av_dict_free(&s->chained_options);
return ret;
}
Commit Message: http: make length/offset-related variables unsigned.
Fixes #5992, reported and found by Paul Cher <[email protected]>.
CWE ID: CWE-119 | static int http_open(URLContext *h, const char *uri, int flags,
AVDictionary **options)
{
HTTPContext *s = h->priv_data;
int ret;
if( s->seekable == 1 )
h->is_streamed = 0;
else
h->is_streamed = 1;
s->filesize = UINT64_MAX;
s->location = av_strdup(uri);
if (!s->location)
return AVERROR(ENOMEM);
if (options)
av_dict_copy(&s->chained_options, *options, 0);
if (s->headers) {
int len = strlen(s->headers);
if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
av_log(h, AV_LOG_WARNING,
"No trailing CRLF found in HTTP header.\n");
ret = av_reallocp(&s->headers, len + 3);
if (ret < 0)
return ret;
s->headers[len] = '\r';
s->headers[len + 1] = '\n';
s->headers[len + 2] = '\0';
}
}
if (s->listen) {
return http_listen(h, uri, flags, options);
}
ret = http_open_cnx(h, options);
if (ret < 0)
av_dict_free(&s->chained_options);
return ret;
}
| 168,498 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) err = BAD_VALUE;
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
Commit Message: Correctly handle dup() failure in Parcel::readNativeHandle
bail out if dup() fails, instead of creating an invalid native_handle_t
Bug: 28395952
Change-Id: Ia1a6198c0f45165b9c6a55a803e5f64d8afa0572
CWE ID: CWE-20 | native_handle* Parcel::readNativeHandle() const
{
int numFds, numInts;
status_t err;
err = readInt32(&numFds);
if (err != NO_ERROR) return 0;
err = readInt32(&numInts);
if (err != NO_ERROR) return 0;
native_handle* h = native_handle_create(numFds, numInts);
if (!h) {
return 0;
}
for (int i=0 ; err==NO_ERROR && i<numFds ; i++) {
h->data[i] = dup(readFileDescriptor());
if (h->data[i] < 0) {
for (int j = 0; j < i; j++) {
close(h->data[j]);
}
native_handle_delete(h);
return 0;
}
}
err = read(h->data + numFds, sizeof(int)*numInts);
if (err != NO_ERROR) {
native_handle_close(h);
native_handle_delete(h);
h = 0;
}
return h;
}
| 173,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int writepng_init(mainprog_info *mainprog_ptr)
{
png_structp png_ptr; /* note: temporary variables! */
png_infop info_ptr;
int color_type, interlace_type;
/* could also replace libpng warning-handler (final NULL), but no need: */
png_ptr = png_create_write_struct(png_get_libpng_ver(NULL), mainprog_ptr,
writepng_error_handler, NULL);
if (!png_ptr)
return 4; /* out of memory */
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr, NULL);
return 4; /* out of memory */
}
/* setjmp() must be called in every function that calls a PNG-writing
* libpng function, unless an alternate error handler was installed--
* but compatible error handlers must either use longjmp() themselves
* (as in this program) or some other method to return control to
* application code, so here we go: */
if (setjmp(mainprog_ptr->jmpbuf)) {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 2;
}
/* make sure outfile is (re)opened in BINARY mode */
png_init_io(png_ptr, mainprog_ptr->outfile);
/* set the compression levels--in general, always want to leave filtering
* turned on (except for palette images) and allow all of the filters,
* which is the default; want 32K zlib window, unless entire image buffer
* is 16K or smaller (unknown here)--also the default; usually want max
* compression (NOT the default); and remaining compression flags should
* be left alone */
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
/*
>> this is default for no filtering; Z_FILTERED is default otherwise:
png_set_compression_strategy(png_ptr, Z_DEFAULT_STRATEGY);
>> these are all defaults:
png_set_compression_mem_level(png_ptr, 8);
png_set_compression_window_bits(png_ptr, 15);
png_set_compression_method(png_ptr, 8);
*/
/* set the image parameters appropriately */
if (mainprog_ptr->pnmtype == 5)
color_type = PNG_COLOR_TYPE_GRAY;
else if (mainprog_ptr->pnmtype == 6)
color_type = PNG_COLOR_TYPE_RGB;
else if (mainprog_ptr->pnmtype == 8)
color_type = PNG_COLOR_TYPE_RGB_ALPHA;
else {
png_destroy_write_struct(&png_ptr, &info_ptr);
return 11;
}
interlace_type = mainprog_ptr->interlaced? PNG_INTERLACE_ADAM7 :
PNG_INTERLACE_NONE;
png_set_IHDR(png_ptr, info_ptr, mainprog_ptr->width, mainprog_ptr->height,
mainprog_ptr->sample_depth, color_type, interlace_type,
PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
if (mainprog_ptr->gamma > 0.0)
png_set_gAMA(png_ptr, info_ptr, mainprog_ptr->gamma);
if (mainprog_ptr->have_bg) { /* we know it's RGBA, not gray+alpha */
png_color_16 background;
background.red = mainprog_ptr->bg_red;
background.green = mainprog_ptr->bg_green;
background.blue = mainprog_ptr->bg_blue;
png_set_bKGD(png_ptr, info_ptr, &background);
}
if (mainprog_ptr->have_time) {
png_time modtime;
png_convert_from_time_t(&modtime, mainprog_ptr->modtime);
png_set_tIME(png_ptr, info_ptr, &modtime);
}
if (mainprog_ptr->have_text) {
png_text text[6];
int num_text = 0;
if (mainprog_ptr->have_text & TEXT_TITLE) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Title";
text[num_text].text = mainprog_ptr->title;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_AUTHOR) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Author";
text[num_text].text = mainprog_ptr->author;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_DESC) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Description";
text[num_text].text = mainprog_ptr->desc;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_COPY) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "Copyright";
text[num_text].text = mainprog_ptr->copyright;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_EMAIL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "E-mail";
text[num_text].text = mainprog_ptr->email;
++num_text;
}
if (mainprog_ptr->have_text & TEXT_URL) {
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = "URL";
text[num_text].text = mainprog_ptr->url;
++num_text;
}
png_set_text(png_ptr, info_ptr, text, num_text);
}
/* write all chunks up to (but not including) first IDAT */
png_write_info(png_ptr, info_ptr);
/* if we wanted to write any more text info *after* the image data, we
* would set up text struct(s) here and call png_set_text() again, with
* just the new data; png_set_tIME() could also go here, but it would
* have no effect since we already called it above (only one tIME chunk
* allowed) */
/* set up the transformations: for now, just pack low-bit-depth pixels
* into bytes (one, two or four pixels per byte) */
png_set_packing(png_ptr);
/* png_set_shift(png_ptr, &sig_bit); to scale low-bit-depth values */
/* make sure we save our pointers for use in writepng_encode_image() */
mainprog_ptr->png_ptr = png_ptr;
mainprog_ptr->info_ptr = info_ptr;
/* OK, that's all we need to do for now; return happy */
return 0;
}
| 173,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_writeargs *args)
{
unsigned int len, v, hdr, dlen;
u32 max_blocksize = svc_max_payload(rqstp);
struct kvec *head = rqstp->rq_arg.head;
struct kvec *tail = rqstp->rq_arg.tail;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->offset);
args->count = ntohl(*p++);
args->stable = ntohl(*p++);
len = args->len = ntohl(*p++);
/*
* The count must equal the amount of data passed.
*/
if (args->count != args->len)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
if (args->count > max_blocksize) {
args->count = max_blocksize;
len = args->len = max_blocksize;
}
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
Commit Message: nfsd: stricter decoding of write-like NFSv2/v3 ops
The NFSv2/v3 code does not systematically check whether we decode past
the end of the buffer. This generally appears to be harmless, but there
are a few places where we do arithmetic on the pointers involved and
don't account for the possibility that a length could be negative. Add
checks to catch these.
Reported-by: Tuomas Haanpää <[email protected]>
Reported-by: Ari Kauppi <[email protected]>
Reviewed-by: NeilBrown <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-119 | nfs3svc_decode_writeargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_writeargs *args)
{
unsigned int len, v, hdr, dlen;
u32 max_blocksize = svc_max_payload(rqstp);
struct kvec *head = rqstp->rq_arg.head;
struct kvec *tail = rqstp->rq_arg.tail;
p = decode_fh(p, &args->fh);
if (!p)
return 0;
p = xdr_decode_hyper(p, &args->offset);
args->count = ntohl(*p++);
args->stable = ntohl(*p++);
len = args->len = ntohl(*p++);
if ((void *)p > head->iov_base + head->iov_len)
return 0;
/*
* The count must equal the amount of data passed.
*/
if (args->count != args->len)
return 0;
/*
* Check to make sure that we got the right number of
* bytes.
*/
hdr = (void*)p - head->iov_base;
dlen = head->iov_len + rqstp->rq_arg.page_len + tail->iov_len - hdr;
/*
* Round the length of the data which was specified up to
* the next multiple of XDR units and then compare that
* against the length which was actually received.
* Note that when RPCSEC/GSS (for example) is used, the
* data buffer can be padded so dlen might be larger
* than required. It must never be smaller.
*/
if (dlen < XDR_QUADLEN(len)*4)
return 0;
if (args->count > max_blocksize) {
args->count = max_blocksize;
len = args->len = max_blocksize;
}
rqstp->rq_vec[0].iov_base = (void*)p;
rqstp->rq_vec[0].iov_len = head->iov_len - hdr;
v = 0;
while (len > rqstp->rq_vec[v].iov_len) {
len -= rqstp->rq_vec[v].iov_len;
v++;
rqstp->rq_vec[v].iov_base = page_address(rqstp->rq_pages[v]);
rqstp->rq_vec[v].iov_len = PAGE_SIZE;
}
rqstp->rq_vec[v].iov_len = len;
args->vlen = v + 1;
return 1;
}
| 168,239 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
RFlagsAtOffset *flags = NULL;
RFlagsAtOffset key;
key.off = off;
if (dir >= 0) {
flags = r_skiplist_get_geq (f->by_off, &key);
} else {
flags = r_skiplist_get_leq (f->by_off, &key);
}
if (dir == 0 && flags && flags->off != off) {
return NULL;
}
return flags;
}
Commit Message: Fix crash in wasm disassembler
CWE ID: CWE-125 | static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
RFlagsAtOffset *flags = NULL;
RFlagsAtOffset key;
key.off = off;
if (dir >= 0) {
flags = r_skiplist_get_geq (f->by_off, &key);
} else {
flags = r_skiplist_get_leq (f->by_off, &key);
}
if (dir == 0 && flags && flags->off != off) {
return NULL;
}
return flags;
}
| 167,723 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
Commit Message: xmlparse.c: Deny internal entities closing the doctype
CWE ID: CWE-611 | processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) {
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
if (parser->m_freeInternalEntities) {
openEntity = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity->next;
} else {
openEntity
= (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (! openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
openEntity->next = parser->m_openInternalEntities;
parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
textStart = (char *)entity->textPtr;
textEnd = (char *)(entity->textPtr + entity->textLen);
/* Set a safe default value in case 'next' does not get set */
next = textStart;
#ifdef XML_DTD
if (entity->is_param) {
int tok
= XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd,
tok, next, &next, XML_FALSE, XML_FALSE);
} else
#endif /* XML_DTD */
result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
parser->m_processor = internalEntityProcessor;
} else {
entity->open = XML_FALSE;
parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
openEntity->next = parser->m_freeInternalEntities;
parser->m_freeInternalEntities = openEntity;
}
}
return result;
}
| 169,532 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.open_flags & (FMODE_READ|FMODE_WRITE|O_EXCL)))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs4_open_prepare(struct rpc_task *task, void *calldata)
{
struct nfs4_opendata *data = calldata;
struct nfs4_state_owner *sp = data->owner;
if (nfs_wait_on_sequence(data->o_arg.seqid, task) != 0)
return;
/*
* Check if we still need to send an OPEN call, or if we can use
* a delegation instead.
*/
if (data->state != NULL) {
struct nfs_delegation *delegation;
if (can_open_cached(data->state, data->o_arg.fmode, data->o_arg.open_flags))
goto out_no_action;
rcu_read_lock();
delegation = rcu_dereference(NFS_I(data->state->inode)->delegation);
if (delegation != NULL &&
test_bit(NFS_DELEGATION_NEED_RECLAIM, &delegation->flags) == 0) {
rcu_read_unlock();
goto out_no_action;
}
rcu_read_unlock();
}
/* Update sequence id. */
data->o_arg.id = sp->so_owner_id.id;
data->o_arg.clientid = sp->so_client->cl_clientid;
if (data->o_arg.claim == NFS4_OPEN_CLAIM_PREVIOUS) {
task->tk_msg.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_OPEN_NOATTR];
nfs_copy_fh(&data->o_res.fh, data->o_arg.fh);
}
data->timestamp = jiffies;
rpc_call_start(task);
return;
out_no_action:
task->tk_action = NULL;
}
| 165,695 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg,
struct cfg80211_ap_settings *params)
{
struct ieee_types_header *rate_ie;
int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable);
const u8 *var_pos = params->beacon.head + var_offset;
int len = params->beacon.head_len - var_offset;
u8 rate_len = 0;
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len);
if (rate_ie) {
memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len);
rate_len = rate_ie->len;
}
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES,
params->beacon.tail,
params->beacon.tail_len);
if (rate_ie)
memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len);
return;
}
Commit Message: mwifiex: Fix three heap overflow at parsing element in cfg80211_ap_settings
mwifiex_update_vs_ie(),mwifiex_set_uap_rates() and
mwifiex_set_wmm_params() call memcpy() without checking
the destination size.Since the source is given from
user-space, this may trigger a heap buffer overflow.
Fix them by putting the length check before performing memcpy().
This fix addresses CVE-2019-14814,CVE-2019-14815,CVE-2019-14816.
Signed-off-by: Wen Huang <[email protected]>
Acked-by: Ganapathi Bhat <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
CWE ID: CWE-120 | mwifiex_set_uap_rates(struct mwifiex_uap_bss_param *bss_cfg,
struct cfg80211_ap_settings *params)
{
struct ieee_types_header *rate_ie;
int var_offset = offsetof(struct ieee80211_mgmt, u.beacon.variable);
const u8 *var_pos = params->beacon.head + var_offset;
int len = params->beacon.head_len - var_offset;
u8 rate_len = 0;
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_SUPP_RATES, var_pos, len);
if (rate_ie) {
if (rate_ie->len > MWIFIEX_SUPPORTED_RATES)
return;
memcpy(bss_cfg->rates, rate_ie + 1, rate_ie->len);
rate_len = rate_ie->len;
}
rate_ie = (void *)cfg80211_find_ie(WLAN_EID_EXT_SUPP_RATES,
params->beacon.tail,
params->beacon.tail_len);
if (rate_ie) {
if (rate_ie->len > MWIFIEX_SUPPORTED_RATES - rate_len)
return;
memcpy(bss_cfg->rates + rate_len, rate_ie + 1, rate_ie->len);
}
return;
}
| 169,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext4_mb_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb2_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
ce = mb2_cache_entry_find_first(ext4_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb2_cache_entry_find_next(ext4_mb_cache, ce);
}
return NULL;
}
| 169,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FoFiType1::parse() {
char *line, *line1, *p, *p2;
char buf[256];
char c;
int n, code, i, j;
char *tokptr;
for (i = 1, line = (char *)file;
i <= 100 && line && (!name || !encoding);
++i) {
if (!name && !strncmp(line, "/FontName", 9)) {
strncpy(buf, line, 255);
buf[255] = '\0';
if ((p = strchr(buf+9, '/')) &&
(p = strtok_r(p+1, " \t\n\r", &tokptr))) {
name = copyString(p);
}
line = getNextLine(line);
} else if (!encoding &&
!strncmp(line, "/Encoding StandardEncoding def", 30)) {
encoding = fofiType1StandardEncoding;
} else if (!encoding &&
!strncmp(line, "/Encoding 256 array", 19)) {
encoding = (char **)gmallocn(256, sizeof(char *));
for (j = 0; j < 256; ++j) {
encoding[j] = NULL;
}
for (j = 0, line = getNextLine(line);
j < 300 && line && (line1 = getNextLine(line));
++j, line = line1) {
if ((n = line1 - line) > 255) {
error(-1, "FoFiType1::parse a line has more than 255 characters, we don't support this");
n = 255;
}
strncpy(buf, line, n);
buf[n] = '\0';
for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
if (!strncmp(p, "dup", 3)) {
for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
if (*p2) {
c = *p2; // store it so we can recover it after atoi
*p2 = '\0'; // terminate p so atoi works
code = atoi(p);
*p2 = c;
if (code == 8 && *p2 == '#') {
code = 0;
for (++p2; *p2 >= '0' && *p2 <= '7'; ++p2) {
code = code * 8 + (*p2 - '0');
code = code * 8 + (*p2 - '0');
}
}
if (code < 256) {
for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
if (*p == '/') {
++p;
c = *p2; // store it so we can recover it after copyString
*p2 = '\0'; // terminate p so copyString works
encoding[code] = copyString(p);
*p2 = c;
p = p2;
for (; *p == ' ' || *p == '\t'; ++p); // eat spaces between string and put
if (!strncmp(p, "put", 3)) {
for (p += 3; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; ++p);
if (*p)
{
line1 = &line[p - buf];
}
} else {
error(-1, "FoFiType1::parse no put after dup");
}
}
}
}
} else {
if (strtok_r(buf, " \t", &tokptr) &&
(p = strtok_r(NULL, " \t\n\r", &tokptr)) && !strcmp(p, "def")) {
break;
}
}
}
} else {
line = getNextLine(line);
}
}
parsed = gTrue;
}
Commit Message:
CWE ID: CWE-20 | void FoFiType1::parse() {
char *line, *line1, *p, *p2;
char buf[256];
char c;
int n, code, i, j;
char *tokptr;
for (i = 1, line = (char *)file;
i <= 100 && line && (!name || !encoding);
++i) {
if (!name && !strncmp(line, "/FontName", 9)) {
strncpy(buf, line, 255);
buf[255] = '\0';
if ((p = strchr(buf+9, '/')) &&
(p = strtok_r(p+1, " \t\n\r", &tokptr))) {
name = copyString(p);
}
line = getNextLine(line);
} else if (!encoding &&
!strncmp(line, "/Encoding StandardEncoding def", 30)) {
encoding = fofiType1StandardEncoding;
} else if (!encoding &&
!strncmp(line, "/Encoding 256 array", 19)) {
encoding = (char **)gmallocn(256, sizeof(char *));
for (j = 0; j < 256; ++j) {
encoding[j] = NULL;
}
for (j = 0, line = getNextLine(line);
j < 300 && line && (line1 = getNextLine(line));
++j, line = line1) {
if ((n = line1 - line) > 255) {
error(-1, "FoFiType1::parse a line has more than 255 characters, we don't support this");
n = 255;
}
strncpy(buf, line, n);
buf[n] = '\0';
for (p = buf; *p == ' ' || *p == '\t'; ++p) ;
if (!strncmp(p, "dup", 3)) {
for (p += 3; *p == ' ' || *p == '\t'; ++p) ;
for (p2 = p; *p2 >= '0' && *p2 <= '9'; ++p2) ;
if (*p2) {
c = *p2; // store it so we can recover it after atoi
*p2 = '\0'; // terminate p so atoi works
code = atoi(p);
*p2 = c;
if (code == 8 && *p2 == '#') {
code = 0;
for (++p2; *p2 >= '0' && *p2 <= '7'; ++p2) {
code = code * 8 + (*p2 - '0');
code = code * 8 + (*p2 - '0');
}
}
if (likely(code < 256 && code >= 0)) {
for (p = p2; *p == ' ' || *p == '\t'; ++p) ;
if (*p == '/') {
++p;
c = *p2; // store it so we can recover it after copyString
*p2 = '\0'; // terminate p so copyString works
encoding[code] = copyString(p);
*p2 = c;
p = p2;
for (; *p == ' ' || *p == '\t'; ++p); // eat spaces between string and put
if (!strncmp(p, "put", 3)) {
for (p += 3; *p == ' ' || *p == '\t' || *p == '\n' || *p == '\r'; ++p);
if (*p)
{
line1 = &line[p - buf];
}
} else {
error(-1, "FoFiType1::parse no put after dup");
}
}
}
}
} else {
if (strtok_r(buf, " \t", &tokptr) &&
(p = strtok_r(NULL, " \t\n\r", &tokptr)) && !strcmp(p, "def")) {
break;
}
}
}
} else {
line = getNextLine(line);
}
}
parsed = gTrue;
}
| 164,903 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
error_ = error;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionTtsPlatformImpl::set_error(const std::string& error) {
| 170,395 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HostPortAllocatorSession::SendSessionRequest(const std::string& host,
int port) {
GURL url("https://" + host + ":" + base::IntToString(port) +
GetSessionRequestUrl() + "&sn=1");
scoped_ptr<UrlFetcher> url_fetcher(new UrlFetcher(url, UrlFetcher::GET));
url_fetcher->SetRequestContext(url_context_);
url_fetcher->SetHeader("X-Talk-Google-Relay-Auth", relay_token());
url_fetcher->SetHeader("X-Google-Relay-Auth", relay_token());
url_fetcher->SetHeader("X-Stream-Type", "chromoting");
url_fetcher->Start(base::Bind(&HostPortAllocatorSession::OnSessionRequestDone,
base::Unretained(this), url_fetcher.get()));
url_fetchers_.insert(url_fetcher.release());
}
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::SendSessionRequest(const std::string& host,
int port) {
GURL url("https://" + host + ":" + base::IntToString(port) +
GetSessionRequestUrl() + "&sn=1");
scoped_ptr<net::URLFetcher> url_fetcher(
net::URLFetcher::Create(url, net::URLFetcher::GET, this));
url_fetcher->SetRequestContext(url_context_);
url_fetcher->AddExtraRequestHeader(
"X-Talk-Google-Relay-Auth: " + relay_token());
url_fetcher->AddExtraRequestHeader("X-Google-Relay-Auth: " + relay_token());
url_fetcher->AddExtraRequestHeader("X-Stream-Type: chromoting");
url_fetcher->Start();
url_fetchers_.insert(url_fetcher.release());
}
| 170,811 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hash_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));
int err;
if (len > ds)
len = ds;
else if (len < ds)
msg->msg_flags |= MSG_TRUNC;
lock_sock(sk);
if (ctx->more) {
ctx->more = 0;
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
if (err)
goto unlock;
}
err = memcpy_toiovec(msg->msg_iov, ctx->result, len);
unlock:
release_sock(sk);
return err ?: len;
}
Commit Message: crypto: algif - suppress sending source address information in recvmsg
The current code does not set the msg_namelen member to 0 and therefore
makes net/socket.c leak the local sockaddr_storage variable to userland
-- 128 bytes of kernel stack memory. Fix that.
Cc: <[email protected]> # 2.6.38
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-200 | static int hash_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req));
int err;
if (len > ds)
len = ds;
else if (len < ds)
msg->msg_flags |= MSG_TRUNC;
msg->msg_namelen = 0;
lock_sock(sk);
if (ctx->more) {
ctx->more = 0;
ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0);
err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req),
&ctx->completion);
if (err)
goto unlock;
}
err = memcpy_toiovec(msg->msg_iov, ctx->result, len);
unlock:
release_sock(sk);
return err ?: len;
}
| 166,046 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: fifo_open(notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type)
{
int ret;
int sav_errno;
if (fifo->name) {
sav_errno = 0;
if (!(ret = mkfifo(fifo->name, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)))
fifo->created_fifo = true;
else {
sav_errno = errno;
if (sav_errno != EEXIST)
log_message(LOG_INFO, "Unable to create %snotify fifo %s", type, fifo->name);
}
if (!sav_errno || sav_errno == EEXIST) {
/* Run the notify script if there is one */
if (fifo->script)
notify_fifo_exec(master, script_exit, fifo, fifo->script);
/* Now open the fifo */
if ((fifo->fd = open(fifo->name, O_RDWR | O_CLOEXEC | O_NONBLOCK)) == -1) {
log_message(LOG_INFO, "Unable to open %snotify fifo %s - errno %d", type, fifo->name, errno);
if (fifo->created_fifo) {
unlink(fifo->name);
fifo->created_fifo = false;
}
}
}
if (fifo->fd == -1) {
FREE(fifo->name);
fifo->name = NULL;
}
}
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59 | fifo_open(notify_fifo_t* fifo, int (*script_exit)(thread_t *), const char *type)
{
int ret;
int sav_errno;
if (fifo->name) {
sav_errno = 0;
if (!(ret = mkfifo(fifo->name, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)))
fifo->created_fifo = true;
else {
sav_errno = errno;
if (sav_errno != EEXIST)
log_message(LOG_INFO, "Unable to create %snotify fifo %s", type, fifo->name);
}
if (!sav_errno || sav_errno == EEXIST) {
/* Run the notify script if there is one */
if (fifo->script)
notify_fifo_exec(master, script_exit, fifo, fifo->script);
/* Now open the fifo */
if ((fifo->fd = open(fifo->name, O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOFOLLOW)) == -1) {
log_message(LOG_INFO, "Unable to open %snotify fifo %s - errno %d", type, fifo->name, errno);
if (fifo->created_fifo) {
unlink(fifo->name);
fifo->created_fifo = false;
}
}
}
if (fifo->fd == -1) {
FREE(fifo->name);
fifo->name = NULL;
}
}
}
| 168,996 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
guint pkt_len;
int pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9u", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
Commit Message: Don't treat the packet length as unsigned.
The scanf family of functions are as annoyingly bad at handling unsigned
numbers as strtoul() is - both of them are perfectly willing to accept a
value beginning with a negative sign as an unsigned value. When using
strtoul(), you can compensate for this by explicitly checking for a '-'
as the first character of the string, but you can't do that with
sscanf().
So revert to having pkt_len be signed, and scanning it with %d, but
check for a negative value and fail if we see a negative value.
Bug: 12394
Change-Id: I4b19b95f2e1ffc96dac5c91bff6698c246f52007
Reviewed-on: https://code.wireshark.org/review/15230
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len < 0) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: packet header has a negative packet length");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
| 167,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
int ulen;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
ulen = xfrm_replay_state_esn_len(up);
if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen)
return -EINVAL;
return 0;
}
Commit Message: xfrm_user: validate XFRM_MSG_NEWAE XFRMA_REPLAY_ESN_VAL replay_window
When a new xfrm state is created during an XFRM_MSG_NEWSA call we
validate the user supplied replay_esn to ensure that the size is valid
and to ensure that the replay_window size is within the allocated
buffer. However later it is possible to update this replay_esn via a
XFRM_MSG_NEWAE call. There we again validate the size of the supplied
buffer matches the existing state and if so inject the contents. We do
not at this point check that the replay_window is within the allocated
memory. This leads to out-of-bounds reads and writes triggered by
netlink packets. This leads to memory corruption and the potential for
priviledge escalation.
We already attempt to validate the incoming replay information in
xfrm_new_ae() via xfrm_replay_verify_len(). This confirms that the user
is not trying to change the size of the replay state buffer which
includes the replay_esn. It however does not check the replay_window
remains within that buffer. Add validation of the contained
replay_window.
CVE-2017-7184
Signed-off-by: Andy Whitcroft <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
int ulen;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
ulen = xfrm_replay_state_esn_len(up);
if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen)
return -EINVAL;
if (up->replay_window > up->bmp_len * sizeof(__u32) * 8)
return -EINVAL;
return 0;
}
| 170,075 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NORET_TYPE void do_exit(long code)
{
struct task_struct *tsk = current;
int group_dead;
profile_task_exit(tsk);
WARN_ON(atomic_read(&tsk->fs_excl));
if (unlikely(in_interrupt()))
panic("Aiee, killing interrupt handler!");
if (unlikely(!tsk->pid))
panic("Attempted to kill the idle task!");
tracehook_report_exit(&code);
validate_creds_for_do_exit(tsk);
/*
* We're taking recursive faults here in do_exit. Safest is to just
* leave this task alone and wait for reboot.
*/
if (unlikely(tsk->flags & PF_EXITING)) {
printk(KERN_ALERT
"Fixing recursive fault but reboot is needed!\n");
/*
* We can do this unlocked here. The futex code uses
* this flag just to verify whether the pi state
* cleanup has been done or not. In the worst case it
* loops once more. We pretend that the cleanup was
* done as there is no way to return. Either the
* OWNER_DIED bit is set by now or we push the blocked
* task into the wait for ever nirwana as well.
*/
tsk->flags |= PF_EXITPIDONE;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule();
}
exit_irq_thread();
exit_signals(tsk); /* sets PF_EXITING */
/*
* tsk->flags are checked in the futex code to protect against
* an exiting task cleaning up the robust pi futexes.
*/
smp_mb();
spin_unlock_wait(&tsk->pi_lock);
if (unlikely(in_atomic()))
printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n",
current->comm, task_pid_nr(current),
preempt_count());
acct_update_integrals(tsk);
group_dead = atomic_dec_and_test(&tsk->signal->live);
if (group_dead) {
hrtimer_cancel(&tsk->signal->real_timer);
exit_itimers(tsk->signal);
if (tsk->mm)
setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
}
acct_collect(code, group_dead);
if (group_dead)
tty_audit_exit();
if (unlikely(tsk->audit_context))
audit_free(tsk);
tsk->exit_code = code;
taskstats_exit(tsk, group_dead);
exit_mm(tsk);
if (group_dead)
acct_process();
trace_sched_process_exit(tsk);
exit_sem(tsk);
exit_files(tsk);
exit_fs(tsk);
check_stack_usage();
exit_thread();
cgroup_exit(tsk, 1);
if (group_dead && tsk->signal->leader)
disassociate_ctty(1);
module_put(task_thread_info(tsk)->exec_domain->module);
proc_exit_connector(tsk);
/*
* Flush inherited counters to the parent - before the parent
* gets woken up by child-exit notifications.
*/
perf_event_exit_task(tsk);
exit_notify(tsk, group_dead);
#ifdef CONFIG_NUMA
mpol_put(tsk->mempolicy);
tsk->mempolicy = NULL;
#endif
#ifdef CONFIG_FUTEX
if (unlikely(current->pi_state_cache))
kfree(current->pi_state_cache);
#endif
/*
* Make sure we are holding no locks:
*/
debug_check_no_locks_held(tsk);
/*
* We can do this unlocked here. The futex code uses this flag
* just to verify whether the pi state cleanup has been done
* or not. In the worst case it loops once more.
*/
tsk->flags |= PF_EXITPIDONE;
if (tsk->io_context)
exit_io_context();
if (tsk->splice_pipe)
__free_pipe_info(tsk->splice_pipe);
validate_creds_for_do_exit(tsk);
preempt_disable();
exit_rcu();
/* causes final put_task_struct in finish_task_switch(). */
tsk->state = TASK_DEAD;
schedule();
BUG();
/* Avoid "noreturn function does return". */
for (;;)
cpu_relax(); /* For when BUG is null */
}
Commit Message: block: Fix io_context leak after failure of clone with CLONE_IO
With CLONE_IO, parent's io_context->nr_tasks is incremented, but never
decremented whenever copy_process() fails afterwards, which prevents
exit_io_context() from calling IO schedulers exit functions.
Give a task_struct to exit_io_context(), and call exit_io_context() instead of
put_io_context() in copy_process() cleanup path.
Signed-off-by: Louis Rilling <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-20 | NORET_TYPE void do_exit(long code)
{
struct task_struct *tsk = current;
int group_dead;
profile_task_exit(tsk);
WARN_ON(atomic_read(&tsk->fs_excl));
if (unlikely(in_interrupt()))
panic("Aiee, killing interrupt handler!");
if (unlikely(!tsk->pid))
panic("Attempted to kill the idle task!");
tracehook_report_exit(&code);
validate_creds_for_do_exit(tsk);
/*
* We're taking recursive faults here in do_exit. Safest is to just
* leave this task alone and wait for reboot.
*/
if (unlikely(tsk->flags & PF_EXITING)) {
printk(KERN_ALERT
"Fixing recursive fault but reboot is needed!\n");
/*
* We can do this unlocked here. The futex code uses
* this flag just to verify whether the pi state
* cleanup has been done or not. In the worst case it
* loops once more. We pretend that the cleanup was
* done as there is no way to return. Either the
* OWNER_DIED bit is set by now or we push the blocked
* task into the wait for ever nirwana as well.
*/
tsk->flags |= PF_EXITPIDONE;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule();
}
exit_irq_thread();
exit_signals(tsk); /* sets PF_EXITING */
/*
* tsk->flags are checked in the futex code to protect against
* an exiting task cleaning up the robust pi futexes.
*/
smp_mb();
spin_unlock_wait(&tsk->pi_lock);
if (unlikely(in_atomic()))
printk(KERN_INFO "note: %s[%d] exited with preempt_count %d\n",
current->comm, task_pid_nr(current),
preempt_count());
acct_update_integrals(tsk);
group_dead = atomic_dec_and_test(&tsk->signal->live);
if (group_dead) {
hrtimer_cancel(&tsk->signal->real_timer);
exit_itimers(tsk->signal);
if (tsk->mm)
setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
}
acct_collect(code, group_dead);
if (group_dead)
tty_audit_exit();
if (unlikely(tsk->audit_context))
audit_free(tsk);
tsk->exit_code = code;
taskstats_exit(tsk, group_dead);
exit_mm(tsk);
if (group_dead)
acct_process();
trace_sched_process_exit(tsk);
exit_sem(tsk);
exit_files(tsk);
exit_fs(tsk);
check_stack_usage();
exit_thread();
cgroup_exit(tsk, 1);
if (group_dead && tsk->signal->leader)
disassociate_ctty(1);
module_put(task_thread_info(tsk)->exec_domain->module);
proc_exit_connector(tsk);
/*
* Flush inherited counters to the parent - before the parent
* gets woken up by child-exit notifications.
*/
perf_event_exit_task(tsk);
exit_notify(tsk, group_dead);
#ifdef CONFIG_NUMA
mpol_put(tsk->mempolicy);
tsk->mempolicy = NULL;
#endif
#ifdef CONFIG_FUTEX
if (unlikely(current->pi_state_cache))
kfree(current->pi_state_cache);
#endif
/*
* Make sure we are holding no locks:
*/
debug_check_no_locks_held(tsk);
/*
* We can do this unlocked here. The futex code uses this flag
* just to verify whether the pi state cleanup has been done
* or not. In the worst case it loops once more.
*/
tsk->flags |= PF_EXITPIDONE;
if (tsk->io_context)
exit_io_context(tsk);
if (tsk->splice_pipe)
__free_pipe_info(tsk->splice_pipe);
validate_creds_for_do_exit(tsk);
preempt_disable();
exit_rcu();
/* causes final put_task_struct in finish_task_switch(). */
tsk->state = TASK_DEAD;
schedule();
BUG();
/* Avoid "noreturn function does return". */
for (;;)
cpu_relax(); /* For when BUG is null */
}
| 169,886 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) {
if (using_ipc_proxy_)
return true;
if (!main_subprocess_.StartSrpcServices()) {
error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL,
"SRPC connection failure for " +
main_subprocess_.description());
return false;
}
if (!main_subprocess_.StartJSObjectProxy(this, error_info)) {
return false;
}
PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n",
main_subprocess_.detailed_description().c_str()));
return true;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool Plugin::LoadNaClModuleContinuationIntern(ErrorInfo* error_info) {
if (!main_subprocess_.StartSrpcServices()) {
error_info->SetReport(ERROR_SRPC_CONNECTION_FAIL,
"SRPC connection failure for " +
main_subprocess_.description());
return false;
}
if (!main_subprocess_.StartJSObjectProxy(this, error_info)) {
return false;
}
PLUGIN_PRINTF(("Plugin::LoadNaClModule (%s)\n",
main_subprocess_.detailed_description().c_str()));
return true;
}
| 170,743 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
char *text,ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p;
DrawInfo
*draw_info;
Image
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,offset,image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadTEXTImage(const ImageInfo *image_info,Image *image,
char *text,ExceptionInfo *exception)
{
char
filename[MaxTextExtent],
geometry[MaxTextExtent],
*p;
DrawInfo
*draw_info;
Image
*texture;
MagickBooleanType
status;
PointInfo
delta;
RectangleInfo
page;
ssize_t
offset;
TypeMetric
metrics;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
/*
Set the page geometry.
*/
delta.x=DefaultResolution;
delta.y=DefaultResolution;
if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0))
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(PSDensityGeometry,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
}
page.width=612;
page.height=792;
page.x=43;
page.y=43;
if (image_info->page != (char *) NULL)
(void) ParseAbsoluteGeometry(image_info->page,&page);
/*
Initialize Image structure.
*/
image->columns=(size_t) floor((((double) page.width*image->x_resolution)/
delta.x)+0.5);
image->rows=(size_t) floor((((double) page.height*image->y_resolution)/
delta.y)+0.5);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->page.x=0;
image->page.y=0;
texture=(Image *) NULL;
if (image_info->texture != (char *) NULL)
{
ImageInfo
*read_info;
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) CopyMagickString(read_info->filename,image_info->texture,
MaxTextExtent);
texture=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
}
/*
Annotate the text image.
*/
(void) SetImageBackgroundColor(image);
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
(void) CloneString(&draw_info->text,image_info->filename);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
status=GetTypeMetrics(image,draw_info,&metrics);
if (status == MagickFalse)
ThrowReaderException(TypeError,"UnableToGetTypeMetrics");
page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5);
(void) FormatLocaleString(geometry,MaxTextExtent,"0x0%+ld%+ld",(long) page.x,
(long) page.y);
(void) CloneString(&draw_info->geometry,geometry);
(void) CopyMagickString(filename,image_info->filename,MaxTextExtent);
if (*draw_info->text != '\0')
*draw_info->text='\0';
p=text;
for (offset=2*page.y; p != (char *) NULL; )
{
/*
Annotate image with text.
*/
(void) ConcatenateString(&draw_info->text,text);
(void) ConcatenateString(&draw_info->text,"\n");
offset+=(ssize_t) (metrics.ascent-metrics.descent);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,offset,image->rows);
if (status == MagickFalse)
break;
}
p=ReadBlobString(image,text);
if ((offset < (ssize_t) image->rows) && (p != (char *) NULL))
continue;
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,
image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (p == (char *) NULL)
break;
/*
Page is full-- allocate next image structure.
*/
*draw_info->text='\0';
offset=2*page.y;
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->next->columns=image->columns;
image->next->rows=image->rows;
image=SyncNextImageInList(image);
(void) CopyMagickString(image->filename,filename,MaxTextExtent);
(void) SetImageBackgroundColor(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
if (texture != (Image *) NULL)
{
MagickProgressMonitor
progress_monitor;
progress_monitor=SetImageProgressMonitor(image,
(MagickProgressMonitor) NULL,image->client_data);
(void) TextureImage(image,texture);
(void) SetImageProgressMonitor(image,progress_monitor,image->client_data);
}
(void) AnnotateImage(image,draw_info);
if (texture != (Image *) NULL)
texture=DestroyImage(texture);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int pgx_validate(jas_stream_t *in)
{
uchar buf[PGX_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < PGX_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (buf[0] << 8) | buf[1];
/* Ensure that the signature is correct for this format. */
if (magic != PGX_MAGIC) {
return -1;
}
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 | int pgx_validate(jas_stream_t *in)
{
jas_uchar buf[PGX_MAGICLEN];
uint_fast32_t magic;
int i;
int n;
assert(JAS_STREAM_MAXPUTBACK >= PGX_MAGICLEN);
/* Read the validation data (i.e., the data used for detecting
the format). */
if ((n = jas_stream_read(in, buf, PGX_MAGICLEN)) < 0) {
return -1;
}
/* Put the validation data back onto the stream, so that the
stream position will not be changed. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough data? */
if (n < PGX_MAGICLEN) {
return -1;
}
/* Compute the signature value. */
magic = (buf[0] << 8) | buf[1];
/* Ensure that the signature is correct for this format. */
if (magic != PGX_MAGIC) {
return -1;
}
return 0;
}
| 168,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: 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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dtls1_process_buffered_records(SSL *s)
{
pitem *item;
item = pqueue_peek(s->d1->unprocessed_rcds.q);
if (item)
{
/* Check if epoch is current. */
if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
return(1); /* Nothing to do. */
/* Process all the records. */
while (pqueue_peek(s->d1->unprocessed_rcds.q))
{
dtls1_get_unprocessed_record(s);
if ( ! dtls1_process_record(s))
return(0);
dtls1_buffer_record(s, &(s->d1->processed_rcds),
s->s3->rrec.seq_num);
}
}
/* sync epoch numbers once all the unprocessed records
* have been processed */
s->d1->processed_rcds.epoch = s->d1->r_epoch;
s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
return(1);
}
Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to
ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a
malloc failure, whilst the latter will fail if attempting to add a duplicate
record to the queue. This should never happen because duplicate records should
be detected and dropped before any attempt to add them to the queue.
Unfortunately records that arrive that are for the next epoch are not being
recorded correctly, and therefore replays are not being detected.
Additionally, these "should not happen" failures that can occur in
dtls1_buffer_record are not being treated as fatal and therefore an attacker
could exploit this by sending repeated replay records for the next epoch,
eventually causing a DoS through memory exhaustion.
Thanks to Chris Mueller for reporting this issue and providing initial
analysis and a patch. Further analysis and the final patch was performed by
Matt Caswell from the OpenSSL development team.
CVE-2015-0206
Reviewed-by: Dr Stephen Henson <[email protected]>
CWE ID: CWE-119 | dtls1_process_buffered_records(SSL *s)
{
pitem *item;
item = pqueue_peek(s->d1->unprocessed_rcds.q);
if (item)
{
/* Check if epoch is current. */
if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
return(1); /* Nothing to do. */
/* Process all the records. */
while (pqueue_peek(s->d1->unprocessed_rcds.q))
{
dtls1_get_unprocessed_record(s);
if ( ! dtls1_process_record(s))
return(0);
if(dtls1_buffer_record(s, &(s->d1->processed_rcds),
s->s3->rrec.seq_num)<0)
return -1;
}
}
/* sync epoch numbers once all the unprocessed records
* have been processed */
s->d1->processed_rcds.epoch = s->d1->r_epoch;
s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
return(1);
}
| 166,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
PROFILER_ENTER(context->priv->prof_nsc_decode)
context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
Commit Message: Fixed CVE-2018-8788
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-787 | BOOL nsc_process_message(NSC_CONTEXT* context, UINT16 bpp,
UINT32 width, UINT32 height,
const BYTE* data, UINT32 length,
BYTE* pDstData, UINT32 DstFormat,
UINT32 nDstStride,
UINT32 nXDst, UINT32 nYDst, UINT32 nWidth,
UINT32 nHeight, UINT32 flip)
{
wStream* s;
BOOL ret;
s = Stream_New((BYTE*)data, length);
if (!s)
return FALSE;
if (nDstStride == 0)
nDstStride = nWidth * GetBytesPerPixel(DstFormat);
switch (bpp)
{
case 32:
context->format = PIXEL_FORMAT_BGRA32;
break;
case 24:
context->format = PIXEL_FORMAT_BGR24;
break;
case 16:
context->format = PIXEL_FORMAT_BGR16;
break;
case 8:
context->format = PIXEL_FORMAT_RGB8;
break;
case 4:
context->format = PIXEL_FORMAT_A4;
break;
default:
Stream_Free(s, TRUE);
return FALSE;
}
context->width = width;
context->height = height;
ret = nsc_context_initialize(context, s);
Stream_Free(s, FALSE);
if (!ret)
return FALSE;
/* RLE decode */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_rle_decompress_data)
rc = nsc_rle_decompress_data(context);
PROFILER_EXIT(context->priv->prof_nsc_rle_decompress_data)
if (!rc)
return FALSE;
}
/* Colorloss recover, Chroma supersample and AYCoCg to ARGB Conversion in one step */
{
BOOL rc;
PROFILER_ENTER(context->priv->prof_nsc_decode)
rc = context->decode(context);
PROFILER_EXIT(context->priv->prof_nsc_decode)
if (!rc)
return FALSE;
}
if (!freerdp_image_copy(pDstData, DstFormat, nDstStride, nXDst, nYDst,
width, height, context->BitmapData,
PIXEL_FORMAT_BGRA32, 0, 0, 0, NULL, flip))
return FALSE;
return TRUE;
}
| 169,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionBrowserTest::OpenWindow(content::WebContents* contents,
const GURL& url,
bool newtab_process_should_equal_opener,
content::WebContents** newtab_result) {
content::WebContentsAddedObserver tab_added_observer;
ASSERT_TRUE(content::ExecuteScript(contents,
"window.open('" + url.spec() + "');"));
content::WebContents* newtab = tab_added_observer.GetWebContents();
ASSERT_TRUE(newtab);
WaitForLoadStop(newtab);
EXPECT_EQ(url, newtab->GetLastCommittedURL());
if (newtab_process_should_equal_opener) {
EXPECT_EQ(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
} else {
EXPECT_NE(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
}
if (newtab_result)
*newtab_result = newtab;
}
Commit Message: [Extensions] Update navigations across hypothetical extension extents
Update code to treat navigations across hypothetical extension extents
(e.g. for nonexistent extensions) the same as we do for navigations
crossing installed extension extents.
Bug: 598265
Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b
Reviewed-on: https://chromium-review.googlesource.com/617180
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#495779}
CWE ID: | void ExtensionBrowserTest::OpenWindow(content::WebContents* contents,
const GURL& url,
bool newtab_process_should_equal_opener,
bool should_succeed,
content::WebContents** newtab_result) {
content::WebContentsAddedObserver tab_added_observer;
ASSERT_TRUE(content::ExecuteScript(contents,
"window.open('" + url.spec() + "');"));
content::WebContents* newtab = tab_added_observer.GetWebContents();
ASSERT_TRUE(newtab);
WaitForLoadStop(newtab);
if (should_succeed) {
EXPECT_EQ(url, newtab->GetLastCommittedURL());
EXPECT_EQ(content::PAGE_TYPE_NORMAL,
newtab->GetController().GetLastCommittedEntry()->GetPageType());
} else {
// "Failure" comes in two forms: redirecting to about:blank or showing an
// error page. At least one should be true.
EXPECT_TRUE(
newtab->GetLastCommittedURL() == GURL(url::kAboutBlankURL) ||
newtab->GetController().GetLastCommittedEntry()->GetPageType() ==
content::PAGE_TYPE_ERROR);
}
if (newtab_process_should_equal_opener) {
EXPECT_EQ(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
} else {
EXPECT_NE(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
}
if (newtab_result)
*newtab_result = newtab;
}
| 172,958 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: stub_charset ()
{
locale = get_locale_var ("LC_CTYPE");
locale = get_locale_var ("LC_CTYPE");
if (locale == 0 || *locale == 0)
return "ASCII";
s = strrchr (locale, '.');
if (s)
{
t = strchr (s, '@');
if (t)
*t = 0;
return ++s;
}
else if (STREQ (locale, "UTF-8"))
return "UTF-8";
else
return "ASCII";
}
Commit Message:
CWE ID: CWE-119 | stub_charset ()
{
locale = get_locale_var ("LC_CTYPE");
locale = get_locale_var ("LC_CTYPE");
if (locale == 0 || *locale == 0)
{
strcpy (charsetbuf, "ASCII");
return charsetbuf;
}
s = strrchr (locale, '.');
if (s)
{
strcpy (charsetbuf, s+1);
t = strchr (charsetbuf, '@');
if (t)
*t = 0;
return charsetbuf;
}
strcpy (charsetbuf, locale);
return charsetbuf;
}
| 165,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1];
struct xfrm_dump_info info;
BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) >
sizeof(cb->args) - sizeof(cb->args[0]));
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
if (!cb->args[0]) {
cb->args[0] = 1;
xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY);
}
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
Commit Message: ipsec: Fix aborted xfrm policy dump crash
An independent security researcher, Mohamed Ghannam, has reported
this vulnerability to Beyond Security's SecuriTeam Secure Disclosure
program.
The xfrm_dump_policy_done function expects xfrm_dump_policy to
have been called at least once or it will crash. This can be
triggered if a dump fails because the target socket's receive
buffer is full.
This patch fixes it by using the cb->start mechanism to ensure that
the initialisation is always done regardless of the buffer situation.
Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list")
Signed-off-by: Herbert Xu <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
CWE ID: CWE-416 | static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args;
struct xfrm_dump_info info;
info.in_skb = cb->skb;
info.out_skb = skb;
info.nlmsg_seq = cb->nlh->nlmsg_seq;
info.nlmsg_flags = NLM_F_MULTI;
(void) xfrm_policy_walk(net, walk, dump_one_policy, &info);
return skb->len;
}
| 167,662 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MirrorMockURLRequestJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const base::FilePath& file_path,
ReportResponseHeadersOnUI report_on_ui)
: net::URLRequestMockHTTPJob(request, network_delegate, file_path),
report_on_ui_(report_on_ui) {}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | MirrorMockURLRequestJob(net::URLRequest* request,
| 172,578 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fput(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
struct task_struct *task = current;
file_sb_list_del(file);
if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
init_task_work(&file->f_u.fu_rcuhead, ____fput);
if (!task_work_add(task, &file->f_u.fu_rcuhead, true))
return;
/*
* After this task has run exit_task_work(),
* task_work_add() will fail. Fall through to delayed
* fput to avoid leaking *file.
*/
}
if (llist_add(&file->f_u.fu_llist, &delayed_fput_list))
schedule_work(&delayed_fput_work);
}
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void fput(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
struct task_struct *task = current;
if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
init_task_work(&file->f_u.fu_rcuhead, ____fput);
if (!task_work_add(task, &file->f_u.fu_rcuhead, true))
return;
/*
* After this task has run exit_task_work(),
* task_work_add() will fail. Fall through to delayed
* fput to avoid leaking *file.
*/
}
if (llist_add(&file->f_u.fu_llist, &delayed_fput_list))
schedule_work(&delayed_fput_work);
}
}
| 166,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected 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
}
return false; //no, we did not load a cue point
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Cues::LoadCuePoint() const
| 174,397 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock_irq(&slave_active_lock);
}
}
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-20 | static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
spin_lock(&master->timer->lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock(&master->timer->lock);
spin_unlock_irq(&slave_active_lock);
}
}
}
| 167,401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.