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 lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20 | static int lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
if (pow((float) r+1, dim) <= entries)
return -1;
if ((int) floor(pow((float) r, dim)) > entries)
return -1;
return r;
}
| 169,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage,
store_image_row(const png_store* ps, png_const_structp pp, int nImage,
png_uint_32 y)
{
png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2;
if (ps->image == NULL)
png_error(pp, "no allocated image");
if (coffset + ps->cb_row + 3 > ps->cb_image)
png_error(pp, "image too small");
return ps->image + coffset;
}
| 173,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
#if 0
const Tracks* const pTracks = m_pSegment->GetTracks();
assert(pTracks);
const long tn = static_cast<long>(track);
const Track* const pTrack = pTracks->GetTrackByNumber(tn);
if (pTrack == NULL)
return E_FILE_FORMAT_INVALID;
#endif
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Cluster::ParseSimpleBlock(long long block_size, long long& pos,
long& len) {
const long long block_start = pos;
const long long block_stop = pos + block_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
long status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long track = ReadUInt(pReader, pos, len);
if (track < 0) // error
return static_cast<long>(track);
if (track == 0)
return E_FILE_FORMAT_INVALID;
pos += len; // consume track number
if ((pos + 2) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 2) > avail) {
len = 2;
return E_BUFFER_NOT_FULL;
}
pos += 2; // consume timecode
if ((pos + 1) > block_stop)
return E_FILE_FORMAT_INVALID;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
unsigned char flags;
status = pReader->Read(pos, 1, &flags);
if (status < 0) { // error or underflow
len = 1;
return status;
}
++pos; // consume flags byte
assert(pos <= avail);
if (pos >= block_stop)
return E_FILE_FORMAT_INVALID;
const int lacing = int(flags & 0x06) >> 1;
if ((lacing != 0) && (block_stop > avail)) {
len = static_cast<long>(block_stop - pos);
return E_BUFFER_NOT_FULL;
}
status = CreateBlock(0x23, // simple block id
block_start, block_size,
0); // DiscardPadding
if (status != 0)
return status;
m_pos = block_stop;
return 0; // success
}
| 173,858 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 processInputBuffer(client *c) {
server.current_client = c;
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Return if clients are paused. */
if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break;
/* Immediately abort if the client is in the middle of something. */
if (c->flags & CLIENT_BLOCKED) break;
/* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands). */
if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = PROTO_REQ_MULTIBULK;
} else {
c->reqtype = PROTO_REQ_INLINE;
}
}
if (c->reqtype == PROTO_REQ_INLINE) {
if (processInlineBuffer(c) != C_OK) break;
} else if (c->reqtype == PROTO_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != C_OK) break;
} else {
serverPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == C_OK)
resetClient(c);
/* freeMemoryIfNeeded may flush slave output buffers. This may result
* into a slave, that may be the active client, to be freed. */
if (server.current_client == NULL) break;
}
}
server.current_client = NULL;
}
Commit Message: Security: Cross Protocol Scripting protection.
This is an attempt at mitigating problems due to cross protocol
scripting, an attack targeting services using line oriented protocols
like Redis that can accept HTTP requests as valid protocol, by
discarding the invalid parts and accepting the payloads sent, for
example, via a POST request.
For this to be effective, when we detect POST and Host: and terminate
the connection asynchronously, the networking code was modified in order
to never process further input. It was later verified that in a
pipelined request containing a POST command, the successive commands are
not executed.
CWE ID: CWE-254 | void processInputBuffer(client *c) {
server.current_client = c;
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Return if clients are paused. */
if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break;
/* Immediately abort if the client is in the middle of something. */
if (c->flags & CLIENT_BLOCKED) break;
/* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands).
*
* The same applies for clients we want to terminate ASAP. */
if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = PROTO_REQ_MULTIBULK;
} else {
c->reqtype = PROTO_REQ_INLINE;
}
}
if (c->reqtype == PROTO_REQ_INLINE) {
if (processInlineBuffer(c) != C_OK) break;
} else if (c->reqtype == PROTO_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != C_OK) break;
} else {
serverPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == C_OK)
resetClient(c);
/* freeMemoryIfNeeded may flush slave output buffers. This may result
* into a slave, that may be the active client, to be freed. */
if (server.current_client == NULL) break;
}
}
server.current_client = NULL;
}
| 168,453 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
adb_mutex_lock(&socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
local_socket_close_locked(s);
goto restart;
}
}
adb_mutex_unlock(&socket_list_lock);
}
Commit Message: adb: switch the socket list mutex to a recursive_mutex.
sockets.cpp was branching on whether a socket close function was
local_socket_close in order to avoid a potential deadlock if the socket
list lock was held while closing a peer socket.
Bug: http://b/28347842
Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3
(cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa)
CWE ID: CWE-264 | void close_all_sockets(atransport* t) {
asocket* s;
/* this is a little gross, but since s->close() *will* modify
** the list out from under you, your options are limited.
*/
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
restart:
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->transport == t || (s->peer && s->peer->transport == t)) {
local_socket_close(s);
goto restart;
}
}
}
| 174,150 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
Commit Message: avcodec/mpeg4videodec: Clear interlaced_dct for studio profile
Fixes: Out of array access
Fixes: 13090/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5408668986638336
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: Kieran Kunhya <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->interlaced_dct = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
| 170,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: PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
min_shrink(0),
max_shrink(0),
desired_dpi(0),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_addr(),
preview_request_id(0),
is_first_request(false),
print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
date(),
title(),
url() {
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | PrintMsg_Print_Params::PrintMsg_Print_Params()
: page_size(),
content_size(),
printable_area(),
margin_top(0),
margin_left(0),
dpi(0),
min_shrink(0),
max_shrink(0),
desired_dpi(0),
document_cookie(0),
selection_only(false),
supports_alpha_blend(false),
preview_ui_id(-1),
preview_request_id(0),
is_first_request(false),
print_scaling_option(WebKit::WebPrintScalingOptionSourceSize),
print_to_pdf(false),
display_header_footer(false),
date(),
title(),
url() {
}
| 170,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jp2_box_t *jp2_box_create(int type)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
return 0;
}
memset(box, 0, sizeof(jp2_box_t));
box->type = type;
box->len = 0;
if (!(boxinfo = jp2_boxinfolookup(type))) {
return 0;
}
box->info = boxinfo;
box->ops = &boxinfo->ops;
return box;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | jp2_box_t *jp2_box_create(int type)
jp2_box_t *jp2_box_create0()
{
jp2_box_t *box;
if (!(box = jas_malloc(sizeof(jp2_box_t)))) {
return 0;
}
memset(box, 0, sizeof(jp2_box_t));
box->type = 0;
box->len = 0;
// Mark the box data as never having been constructed
// so that we will not errantly attempt to destroy it later.
box->ops = &jp2_boxinfo_unk.ops;
return box;
}
jp2_box_t *jp2_box_create(int type)
{
jp2_box_t *box;
jp2_boxinfo_t *boxinfo;
if (!(box = jp2_box_create0())) {
return 0;
}
box->type = type;
box->len = 0;
if (!(boxinfo = jp2_boxinfolookup(type))) {
return 0;
}
box->info = boxinfo;
box->ops = &boxinfo->ops;
return box;
}
| 168,317 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 itacns_add_data_files(sc_pkcs15_card_t *p15card)
{
const size_t array_size =
sizeof(itacns_data_files)/sizeof(itacns_data_files[0]);
unsigned int i;
int rv;
sc_pkcs15_data_t *p15_personaldata = NULL;
sc_pkcs15_data_info_t dinfo;
struct sc_pkcs15_object *objs[32];
struct sc_pkcs15_data_info *cinfo;
for(i=0; i < array_size; i++) {
sc_path_t path;
sc_pkcs15_data_info_t data;
sc_pkcs15_object_t obj;
if (itacns_data_files[i].cie_only &&
p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2)
continue;
sc_format_path(itacns_data_files[i].path, &path);
memset(&data, 0, sizeof(data));
memset(&obj, 0, sizeof(obj));
strlcpy(data.app_label, itacns_data_files[i].label,
sizeof(data.app_label));
strlcpy(obj.label, itacns_data_files[i].label,
sizeof(obj.label));
data.path = path;
rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv,
"Could not add data file");
}
/*
* If we got this far, we can read the Personal Data file and glean
* the user's full name. Thus we can use it to put together a
* user-friendlier card name.
*/
memset(&dinfo, 0, sizeof(dinfo));
strcpy(dinfo.app_label, "EF_DatiPersonali");
/* Find EF_DatiPersonali */
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT,
objs, 32);
if(rv < 0) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Data enumeration failed");
return SC_SUCCESS;
}
for(i=0; i<32; i++) {
cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
if(!strcmp("EF_DatiPersonali", objs[i]->label))
break;
}
if(i>=32) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not find EF_DatiPersonali: "
"keeping generic card name");
return SC_SUCCESS;
}
rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata);
if (rv) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not read EF_DatiPersonali: "
"keeping generic card name");
}
{
char fullname[160];
if(get_name_from_EF_DatiPersonali(p15_personaldata->data,
fullname, sizeof(fullname))) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not parse EF_DatiPersonali: "
"keeping generic card name");
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
set_string(&p15card->tokeninfo->label, fullname);
}
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int itacns_add_data_files(sc_pkcs15_card_t *p15card)
{
const size_t array_size =
sizeof(itacns_data_files)/sizeof(itacns_data_files[0]);
unsigned int i;
int rv;
sc_pkcs15_data_t *p15_personaldata = NULL;
sc_pkcs15_data_info_t dinfo;
struct sc_pkcs15_object *objs[32];
struct sc_pkcs15_data_info *cinfo;
for(i=0; i < array_size; i++) {
sc_path_t path;
sc_pkcs15_data_info_t data;
sc_pkcs15_object_t obj;
if (itacns_data_files[i].cie_only &&
p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2)
continue;
sc_format_path(itacns_data_files[i].path, &path);
memset(&data, 0, sizeof(data));
memset(&obj, 0, sizeof(obj));
strlcpy(data.app_label, itacns_data_files[i].label,
sizeof(data.app_label));
strlcpy(obj.label, itacns_data_files[i].label,
sizeof(obj.label));
data.path = path;
rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data);
SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv,
"Could not add data file");
}
/*
* If we got this far, we can read the Personal Data file and glean
* the user's full name. Thus we can use it to put together a
* user-friendlier card name.
*/
memset(&dinfo, 0, sizeof(dinfo));
strcpy(dinfo.app_label, "EF_DatiPersonali");
/* Find EF_DatiPersonali */
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT,
objs, 32);
if(rv < 0) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Data enumeration failed");
return SC_SUCCESS;
}
for(i=0; i<32; i++) {
cinfo = (struct sc_pkcs15_data_info *) objs[i]->data;
if(!strcmp("EF_DatiPersonali", objs[i]->label))
break;
}
if(i>=32) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not find EF_DatiPersonali: "
"keeping generic card name");
return SC_SUCCESS;
}
rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata);
if (rv) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not read EF_DatiPersonali: "
"keeping generic card name");
return SC_SUCCESS;
}
{
char fullname[160];
if(get_name_from_EF_DatiPersonali(p15_personaldata->data,
fullname, sizeof(fullname))) {
sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL,
"Could not parse EF_DatiPersonali: "
"keeping generic card name");
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
set_string(&p15card->tokeninfo->label, fullname);
}
sc_pkcs15_free_data_object(p15_personaldata);
return SC_SUCCESS;
}
| 169,066 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 region16_simplify_bands(REGION16* region)
{
/** Simplify consecutive bands that touch and have the same items
*
* ==================== ====================
* | 1 | | 2 | | | | |
* ==================== | | | |
* | 1 | | 2 | ====> | 1 | | 2 |
* ==================== | | | |
* | 1 | | 2 | | | | |
* ==================== ====================
*
*/
RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;
int nbRects, finalNbRects;
int bandItems, toMove;
finalNbRects = nbRects = region16_n_rects(region);
if (nbRects < 2)
return TRUE;
band1 = region16_rects_noconst(region);
endPtr = band1 + nbRects;
do
{
band2 = next_band(band1, endPtr, &bandItems);
if (band2 == endPtr)
break;
if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))
{
/* adjust the bottom of band1 items */
tmp = band1;
while (tmp < band2)
{
tmp->bottom = band2->bottom;
tmp++;
}
/* override band2, we don't move band1 pointer as the band after band2
* may be merged too */
endBand = band2 + bandItems;
toMove = (endPtr - endBand) * sizeof(RECTANGLE_16);
if (toMove)
MoveMemory(band2, endBand, toMove);
finalNbRects -= bandItems;
endPtr -= bandItems;
}
else
{
band1 = band2;
}
}
while (TRUE);
if (finalNbRects != nbRects)
{
int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));
region->data = realloc(region->data, allocSize);
if (!region->data)
{
region->data = &empty_region;
return FALSE;
}
region->data->nbRects = finalNbRects;
region->data->size = allocSize;
}
return TRUE;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772 | static BOOL region16_simplify_bands(REGION16* region)
{
/** Simplify consecutive bands that touch and have the same items
*
* ==================== ====================
* | 1 | | 2 | | | | |
* ==================== | | | |
* | 1 | | 2 | ====> | 1 | | 2 |
* ==================== | | | |
* | 1 | | 2 | | | | |
* ==================== ====================
*
*/
RECTANGLE_16* band1, *band2, *endPtr, *endBand, *tmp;
int nbRects, finalNbRects;
int bandItems, toMove;
finalNbRects = nbRects = region16_n_rects(region);
if (nbRects < 2)
return TRUE;
band1 = region16_rects_noconst(region);
endPtr = band1 + nbRects;
do
{
band2 = next_band(band1, endPtr, &bandItems);
if (band2 == endPtr)
break;
if ((band1->bottom == band2->top) && band_match(band1, band2, endPtr))
{
/* adjust the bottom of band1 items */
tmp = band1;
while (tmp < band2)
{
tmp->bottom = band2->bottom;
tmp++;
}
/* override band2, we don't move band1 pointer as the band after band2
* may be merged too */
endBand = band2 + bandItems;
toMove = (endPtr - endBand) * sizeof(RECTANGLE_16);
if (toMove)
MoveMemory(band2, endBand, toMove);
finalNbRects -= bandItems;
endPtr -= bandItems;
}
else
{
band1 = band2;
}
}
while (TRUE);
if (finalNbRects != nbRects)
{
REGION16_DATA* data;
size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16));
data = realloc(region->data, allocSize);
if (!data)
free(region->data);
region->data = data;
if (!region->data)
{
region->data = &empty_region;
return FALSE;
}
region->data->nbRects = finalNbRects;
region->data->size = allocSize;
}
return TRUE;
}
| 169,497 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_scale_16_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth > 8;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_scale_16_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(colour_type)
this->next = *that;
*that = this;
return bit_depth > 8;
}
| 173,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DatabaseImpl::IDBThreadHelper::CreateTransaction(
int64_t transaction_id,
const std::vector<int64_t>& object_store_ids,
blink::WebIDBTransactionMode mode) {
DCHECK(idb_thread_checker_.CalledOnValidThread());
if (!connection_->IsConnected())
return;
connection_->database()->CreateTransaction(transaction_id, connection_.get(),
object_store_ids, mode);
}
Commit Message: [IndexedDB] Fixed transaction use-after-free vuln
Bug: 725032
Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa
Reviewed-on: https://chromium-review.googlesource.com/518483
Reviewed-by: Joshua Bell <[email protected]>
Commit-Queue: Daniel Murphy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#475952}
CWE ID: CWE-416 | void DatabaseImpl::IDBThreadHelper::CreateTransaction(
int64_t transaction_id,
const std::vector<int64_t>& object_store_ids,
blink::WebIDBTransactionMode mode) {
DCHECK(idb_thread_checker_.CalledOnValidThread());
if (!connection_->IsConnected())
return;
// Can't call BadMessage as we're no longer on the IO thread. So ignore.
if (connection_->GetTransaction(transaction_id))
return;
connection_->database()->CreateTransaction(transaction_id, connection_.get(),
object_store_ids, mode);
}
| 172,351 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
print_web_view_(NULL),
is_preview_enabled_(IsPrintPreviewEnabled()),
is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
user_cancelled_scripted_print_count_(0),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false) {
}
Commit Message: Guard against the same PrintWebViewHelper being re-entered.
BUG=159165
Review URL: https://chromiumcodereview.appspot.com/11367076
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@165821 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | PrintWebViewHelper::PrintWebViewHelper(content::RenderView* render_view)
: content::RenderViewObserver(render_view),
content::RenderViewObserverTracker<PrintWebViewHelper>(render_view),
print_web_view_(NULL),
is_preview_enabled_(IsPrintPreviewEnabled()),
is_scripted_print_throttling_disabled_(IsPrintThrottlingDisabled()),
is_print_ready_metafile_sent_(false),
ignore_css_margins_(false),
user_cancelled_scripted_print_count_(0),
is_scripted_printing_blocked_(false),
notify_browser_of_print_failure_(true),
print_for_preview_(false),
print_node_in_progress_(false) {
}
| 170,698 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gdImagePtr gdImageCreate (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sy)) {
return NULL;
}
im = (gdImage *) gdCalloc(1, sizeof(gdImage));
/* Row-major ever since gd 1.3 */
im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; i < sy; i++) {
/* Row-major ever since gd 1.3 */
im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
}
im->sx = sx;
im->sy = sy;
im->colorsTotal = 0;
im->transparent = (-1);
im->interlace = 0;
im->thick = 1;
im->AA = 0;
im->AA_polygon = 0;
for (i = 0; i < gdMaxColors; i++) {
im->open[i] = 1;
im->red[i] = 0;
im->green[i] = 0;
im->blue[i] = 0;
}
im->trueColor = 0;
im->tpixels = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190 | gdImagePtr gdImageCreate (int sx, int sy)
{
int i;
gdImagePtr im;
if (overflow2(sx, sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sy)) {
return NULL;
}
if (overflow2(sizeof(unsigned char *), sx)) {
return NULL;
}
im = (gdImage *) gdCalloc(1, sizeof(gdImage));
/* Row-major ever since gd 1.3 */
im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy);
im->polyInts = 0;
im->polyAllocated = 0;
im->brush = 0;
im->tile = 0;
im->style = 0;
for (i = 0; i < sy; i++) {
/* Row-major ever since gd 1.3 */
im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char));
}
im->sx = sx;
im->sy = sy;
im->colorsTotal = 0;
im->transparent = (-1);
im->interlace = 0;
im->thick = 1;
im->AA = 0;
im->AA_polygon = 0;
for (i = 0; i < gdMaxColors; i++) {
im->open[i] = 1;
im->red[i] = 0;
im->green[i] = 0;
im->blue[i] = 0;
}
im->trueColor = 0;
im->tpixels = 0;
im->cx1 = 0;
im->cy1 = 0;
im->cx2 = im->sx - 1;
im->cy2 = im->sy - 1;
im->interpolation = NULL;
im->interpolation_id = GD_BILINEAR_FIXED;
return im;
}
| 167,127 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = (mWidth * mHeight * 3) / 2;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec
Bug: 27833616
Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0
CWE ID: CWE-20 | void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader =
port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
++mInputBufferCount;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
return;
}
uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset;
uint32_t *start_code = (uint32_t *)bitstream;
bool volHeader = *start_code == 0xB0010000;
if (volHeader) {
PVCleanUpVideoDecoder(mHandle);
mInitialized = false;
}
if (!mInitialized) {
uint8_t *vol_data[1];
int32_t vol_size = 0;
vol_data[0] = NULL;
if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) {
vol_data[0] = bitstream;
vol_size = inHeader->nFilledLen;
}
MP4DecodingMode mode =
(mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE;
Bool success = PVInitVideoDecoder(
mHandle, vol_data, &vol_size, 1,
outputBufferWidth(), outputBufferHeight(), mode);
if (!success) {
ALOGW("PVInitVideoDecoder failed. Unsupported content?");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
if (mode != actualMode) {
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
PVSetPostProcType((VideoDecControls *) mHandle, 0);
bool hasFrameData = false;
if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
} else if (volHeader) {
hasFrameData = true;
}
mInitialized = true;
if (mode == MPEG4_MODE && handlePortSettingsChange()) {
return;
}
if (!hasFrameData) {
continue;
}
}
if (!mFramesConfigured) {
PortInfo *port = editPortInfo(1);
OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader;
PVSetReferenceYUV(mHandle, outHeader->pBuffer);
mFramesConfigured = true;
}
uint32_t useExtTimestamp = (inHeader->nOffset == 0);
uint32_t timestamp = 0xFFFFFFFF;
if (useExtTimestamp) {
mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp);
timestamp = mPvTime;
mPvTime++;
}
int32_t bufferSize = inHeader->nFilledLen;
int32_t tmp = bufferSize;
OMX_U32 frameSize = (mWidth * mHeight * 3) / 2;
if (outHeader->nAllocLen < frameSize) {
android_errorWriteLog(0x534e4554, "27833616");
ALOGE("Insufficient output buffer size");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (PVDecodeVideoFrame(
mHandle, &bitstream, ×tamp, &tmp,
&useExtTimestamp,
outHeader->pBuffer) != PV_TRUE) {
ALOGE("failed to decode video frame.");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
if (handlePortSettingsChange()) {
return;
}
outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp);
mPvToOmxTimeMap.removeItem(timestamp);
inHeader->nOffset += bufferSize;
inHeader->nFilledLen = 0;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
} else {
outHeader->nFlags = 0;
}
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
++mInputBufferCount;
outHeader->nOffset = 0;
outHeader->nFilledLen = frameSize;
List<BufferInfo *>::iterator it = outQueue.begin();
while ((*it)->mHeader != outHeader) {
++it;
}
BufferInfo *outInfo = *it;
outInfo->mOwnedByUs = false;
outQueue.erase(it);
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
++mNumSamplesOutput;
}
}
| 174,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"s256");
}
Commit Message:
CWE ID: CWE-20 | size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address)
{
/* VPD - all zeros */
return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00,
"*s256");
}
| 164,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value)
{
/*
* Convert jiffies to nanoseconds and separate with
* one divide.
*/
u64 nsec = (u64)jiffies * TICK_NSEC;
long tv_usec;
value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tv_usec);
tv_usec /= NSEC_PER_USEC;
value->tv_usec = tv_usec;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | void jiffies_to_timeval(const unsigned long jiffies, struct timeval *value)
{
/*
* Convert jiffies to nanoseconds and separate with
* one divide.
*/
u32 rem;
value->tv_sec = div_u64_rem((u64)jiffies * TICK_NSEC,
NSEC_PER_SEC, &rem);
value->tv_usec = rem / NSEC_PER_USEC;
}
| 165,755 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::EOS() const
//// long long element_size)
{
return (m_pSegment == NULL);
}
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 Cluster::EOS() const
pEntry = NULL;
if (index < 0)
return -1; // generic error
if (m_entries_count < 0)
return E_BUFFER_NOT_FULL;
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (index < m_entries_count) {
pEntry = m_entries[index];
assert(pEntry);
return 1; // found entry
}
if (m_element_size < 0) // we don't know cluster end yet
return E_BUFFER_NOT_FULL; // underflow
const long long element_stop = m_element_start + m_element_size;
if (m_pos >= element_stop)
return 0; // nothing left to parse
return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed
}
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
//// long long element_size)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment, idx, element_start);
// element_size);
assert(pCluster);
return pCluster;
}
| 174,270 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
| 166,869 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
ret = gss_wrap_iov(minor_status,
context_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_wrap_iov(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
int *conf_state,
gss_iov_buffer_desc *iov,
int iov_count)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_wrap_iov(minor_status,
sc->ctx_handle,
conf_req_flag,
qop_req,
conf_state,
iov,
iov_count);
return (ret);
}
| 166,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
Commit Message: SoftMP3: memset safely
Bug: 29422022
Change-Id: I70c9e33269d16bf8c163815706ac24e18e34fe97
CWE ID: CWE-264 | void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %u, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
if (!memsetSafe(outHeader, 0, outHeader->nFilledLen)) {
return;
}
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
if (!memsetSafe(outHeader, 0, mConfig->outputFrameSize * sizeof(int16_t))) {
return;
}
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
| 173,415 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 impeg2d_get_slice_pos(dec_state_multi_core_t *ps_dec_state_multi_core)
{
WORD32 u4_bits;
WORD32 i4_row;
dec_state_t *ps_dec = ps_dec_state_multi_core->ps_dec_state[0];
WORD32 i4_prev_row;
stream_t s_bitstrm;
WORD32 i4_start_row;
WORD32 i4_slice_bistream_ofst;
WORD32 i;
s_bitstrm = ps_dec->s_bit_stream;
i4_prev_row = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_start_mb_y = 0;
ps_dec_state_multi_core->ps_dec_state[1]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_end_mb_y = ps_dec->u2_num_vert_mb;
ps_dec_state_multi_core->ps_dec_state[1]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_end_mb_y = -1;
if(ps_dec->i4_num_cores == 1)
return 0;
/* Reset the jobq to start of the jobq buffer */
impeg2_jobq_reset((jobq_t *)ps_dec->pv_jobq);
i4_start_row = -1;
i4_slice_bistream_ofst = 0;
while(1)
{
WORD32 i4_is_slice;
if(s_bitstrm.u4_offset + START_CODE_LEN >= s_bitstrm.u4_max_offset)
{
break;
}
u4_bits = impeg2d_bit_stream_nxt(&s_bitstrm,START_CODE_LEN);
i4_row = u4_bits & 0xFF;
/* Detect end of frame */
i4_is_slice = (((u4_bits >> 8) == 0x01) && (i4_row) && (i4_row <= ps_dec->u2_num_vert_mb));
if(!i4_is_slice)
break;
i4_row -= 1;
if(i4_prev_row != i4_row)
{
/* Create a job for previous slice row */
if(i4_start_row != -1)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = i4_row;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
/* Store current slice's bitstream offset */
i4_slice_bistream_ofst = s_bitstrm.u4_offset >> 3;
i4_slice_bistream_ofst -= (size_t)s_bitstrm.pv_bs_buf & 3;
i4_prev_row = i4_row;
/* Store current slice's row position */
i4_start_row = i4_row;
}
impeg2d_bit_stream_flush(&s_bitstrm, START_CODE_LEN);
/* Flush the bytes till a start code is encountered */
while(impeg2d_bit_stream_nxt(&s_bitstrm, 24) != START_CODE_PREFIX)
{
impeg2d_bit_stream_get(&s_bitstrm, 8);
if(s_bitstrm.u4_offset >= s_bitstrm.u4_max_offset)
{
break;
}
}
}
/* Create job for the last slice row */
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = ps_dec->u2_num_vert_mb;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
e_ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(e_ret != IV_SUCCESS)
return e_ret;
}
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
{
for(i = 0; i < ps_dec->u2_vertical_size; i+=64)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i;
s_job.i2_start_mb_y >>= 4;
s_job.i2_end_mb_y = (i + 64);
s_job.i2_end_mb_y >>= 4;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i4_bistream_ofst = 0;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
}
impeg2_jobq_terminate(ps_dec->pv_jobq);
ps_dec->i4_bytes_consumed = s_bitstrm.u4_offset >> 3;
ps_dec->i4_bytes_consumed -= ((size_t)s_bitstrm.pv_bs_buf & 3);
return 0;
}
Commit Message: Fix for handling streams which resulted in negative num_mbs_left
Bug: 26070014
Change-Id: Id9f063a2c72a802d991b92abaf00ec687db5bb0f
CWE ID: CWE-119 | WORD32 impeg2d_get_slice_pos(dec_state_multi_core_t *ps_dec_state_multi_core)
{
WORD32 u4_bits;
WORD32 i4_row;
dec_state_t *ps_dec = ps_dec_state_multi_core->ps_dec_state[0];
WORD32 i4_prev_row;
stream_t s_bitstrm;
WORD32 i4_start_row;
WORD32 i4_slice_bistream_ofst;
WORD32 i;
s_bitstrm = ps_dec->s_bit_stream;
i4_prev_row = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_start_mb_y = 0;
ps_dec_state_multi_core->ps_dec_state[1]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_start_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[0]->i4_end_mb_y = ps_dec->u2_num_vert_mb;
ps_dec_state_multi_core->ps_dec_state[1]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[2]->i4_end_mb_y = -1;
ps_dec_state_multi_core->ps_dec_state[3]->i4_end_mb_y = -1;
if(ps_dec->i4_num_cores == 1)
return 0;
/* Reset the jobq to start of the jobq buffer */
impeg2_jobq_reset((jobq_t *)ps_dec->pv_jobq);
i4_start_row = -1;
i4_slice_bistream_ofst = 0;
while(1)
{
WORD32 i4_is_slice;
if(s_bitstrm.u4_offset + START_CODE_LEN >= s_bitstrm.u4_max_offset)
{
break;
}
u4_bits = impeg2d_bit_stream_nxt(&s_bitstrm,START_CODE_LEN);
i4_row = u4_bits & 0xFF;
/* Detect end of frame */
i4_is_slice = (((u4_bits >> 8) == 0x01) && (i4_row) && (i4_row <= ps_dec->u2_num_vert_mb));
if(!i4_is_slice)
break;
i4_row -= 1;
if(i4_prev_row < i4_row)
{
/* Create a job for previous slice row */
if(i4_start_row != -1)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = i4_row;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
/* Store current slice's bitstream offset */
i4_slice_bistream_ofst = s_bitstrm.u4_offset >> 3;
i4_slice_bistream_ofst -= (size_t)s_bitstrm.pv_bs_buf & 3;
i4_prev_row = i4_row;
/* Store current slice's row position */
i4_start_row = i4_row;
} else if (i4_prev_row > i4_row) {
android_errorWriteLog(0x534e4554, "26070014");
}
impeg2d_bit_stream_flush(&s_bitstrm, START_CODE_LEN);
/* Flush the bytes till a start code is encountered */
while(impeg2d_bit_stream_nxt(&s_bitstrm, 24) != START_CODE_PREFIX)
{
impeg2d_bit_stream_get(&s_bitstrm, 8);
if(s_bitstrm.u4_offset >= s_bitstrm.u4_max_offset)
{
break;
}
}
}
/* Create job for the last slice row */
{
job_t s_job;
IV_API_CALL_STATUS_T e_ret;
s_job.i2_start_mb_y = i4_start_row;
s_job.i2_end_mb_y = ps_dec->u2_num_vert_mb;
s_job.i4_cmd = CMD_PROCESS;
s_job.i4_bistream_ofst = i4_slice_bistream_ofst;
e_ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(e_ret != IV_SUCCESS)
return e_ret;
}
if((NULL != ps_dec->ps_disp_pic) && ((0 == ps_dec->u4_share_disp_buf) || (IV_YUV_420P != ps_dec->i4_chromaFormat)))
{
for(i = 0; i < ps_dec->u2_vertical_size; i+=64)
{
job_t s_job;
IV_API_CALL_STATUS_T ret;
s_job.i2_start_mb_y = i;
s_job.i2_start_mb_y >>= 4;
s_job.i2_end_mb_y = (i + 64);
s_job.i2_end_mb_y >>= 4;
s_job.i4_cmd = CMD_FMTCONV;
s_job.i4_bistream_ofst = 0;
ret = impeg2_jobq_queue(ps_dec->pv_jobq, &s_job, sizeof(s_job), 1, 0);
if(ret != IV_SUCCESS)
return ret;
}
}
impeg2_jobq_terminate(ps_dec->pv_jobq);
ps_dec->i4_bytes_consumed = s_bitstrm.u4_offset >> 3;
ps_dec->i4_bytes_consumed -= ((size_t)s_bitstrm.pv_bs_buf & 3);
return 0;
}
| 173,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int xt_check_entry_offsets(const void *base,
unsigned int target_offset,
unsigned int next_offset)
{
const struct xt_entry_target *t;
const char *e = base;
if (target_offset + sizeof(*t) > next_offset)
return -EINVAL;
t = (void *)(e + target_offset);
if (t->u.target_size < sizeof(*t))
return -EINVAL;
if (target_offset + t->u.target_size > next_offset)
return -EINVAL;
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
target_offset + sizeof(struct xt_standard_target) != next_offset)
return -EINVAL;
return 0;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264 | int xt_check_entry_offsets(const void *base,
const char *elems,
unsigned int target_offset,
unsigned int next_offset)
{
long size_of_base_struct = elems - (const char *)base;
const struct xt_entry_target *t;
const char *e = base;
/* target start is within the ip/ip6/arpt_entry struct */
if (target_offset < size_of_base_struct)
return -EINVAL;
if (target_offset + sizeof(*t) > next_offset)
return -EINVAL;
t = (void *)(e + target_offset);
if (t->u.target_size < sizeof(*t))
return -EINVAL;
if (target_offset + t->u.target_size > next_offset)
return -EINVAL;
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 &&
target_offset + sizeof(struct xt_standard_target) != next_offset)
return -EINVAL;
return 0;
}
| 167,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool_t xdr_krb5_tl_data(XDR *xdrs, krb5_tl_data **tl_data_head)
{
krb5_tl_data *tl, *tl2;
bool_t more;
unsigned int len;
switch (xdrs->x_op) {
case XDR_FREE:
tl = tl2 = *tl_data_head;
while (tl) {
tl2 = tl->tl_data_next;
free(tl->tl_data_contents);
free(tl);
tl = tl2;
}
break;
case XDR_ENCODE:
tl = *tl_data_head;
while (1) {
more = (tl != NULL);
if (!xdr_bool(xdrs, &more))
return FALSE;
if (tl == NULL)
break;
if (!xdr_krb5_int16(xdrs, &tl->tl_data_type))
return FALSE;
len = tl->tl_data_length;
if (!xdr_bytes(xdrs, (char **) &tl->tl_data_contents, &len, ~0))
return FALSE;
tl = tl->tl_data_next;
}
break;
case XDR_DECODE:
tl = NULL;
while (1) {
if (!xdr_bool(xdrs, &more))
return FALSE;
if (more == FALSE)
break;
tl2 = (krb5_tl_data *) malloc(sizeof(krb5_tl_data));
if (tl2 == NULL)
return FALSE;
memset(tl2, 0, sizeof(krb5_tl_data));
if (!xdr_krb5_int16(xdrs, &tl2->tl_data_type))
return FALSE;
if (!xdr_bytes(xdrs, (char **)&tl2->tl_data_contents, &len, ~0))
return FALSE;
tl2->tl_data_length = len;
tl2->tl_data_next = tl;
tl = tl2;
}
*tl_data_head = tl;
break;
}
return TRUE;
}
Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421]
[MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free
partial deserialization results upon failure to deserialize. This
responsibility belongs to the callers, svctcp_getargs() and
svcudp_getargs(); doing it in the unwrap function results in freeing
the results twice.
In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers
we are freeing, as other XDR functions such as xdr_bytes() and
xdr_string().
ticket: 8056 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | bool_t xdr_krb5_tl_data(XDR *xdrs, krb5_tl_data **tl_data_head)
{
krb5_tl_data *tl, *tl2;
bool_t more;
unsigned int len;
switch (xdrs->x_op) {
case XDR_FREE:
tl = tl2 = *tl_data_head;
while (tl) {
tl2 = tl->tl_data_next;
free(tl->tl_data_contents);
free(tl);
tl = tl2;
}
*tl_data_head = NULL;
break;
case XDR_ENCODE:
tl = *tl_data_head;
while (1) {
more = (tl != NULL);
if (!xdr_bool(xdrs, &more))
return FALSE;
if (tl == NULL)
break;
if (!xdr_krb5_int16(xdrs, &tl->tl_data_type))
return FALSE;
len = tl->tl_data_length;
if (!xdr_bytes(xdrs, (char **) &tl->tl_data_contents, &len, ~0))
return FALSE;
tl = tl->tl_data_next;
}
break;
case XDR_DECODE:
tl = NULL;
while (1) {
if (!xdr_bool(xdrs, &more))
return FALSE;
if (more == FALSE)
break;
tl2 = (krb5_tl_data *) malloc(sizeof(krb5_tl_data));
if (tl2 == NULL)
return FALSE;
memset(tl2, 0, sizeof(krb5_tl_data));
if (!xdr_krb5_int16(xdrs, &tl2->tl_data_type))
return FALSE;
if (!xdr_bytes(xdrs, (char **)&tl2->tl_data_contents, &len, ~0))
return FALSE;
tl2->tl_data_length = len;
tl2->tl_data_next = tl;
tl = tl2;
}
*tl_data_head = tl;
break;
}
return TRUE;
}
| 166,791 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
{
vcpu->arch.apic->vapic_addr = vapic_addr;
if (vapic_addr)
__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
else
__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
}
Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368)
In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the
potential to corrupt kernel memory if userspace provides an address that
is at the end of a page. This patches concerts those functions to use
kvm_write_guest_cached and kvm_read_guest_cached. It also checks the
vapic_address specified by userspace during ioctl processing and returns
an error to userspace if the address is not a valid GPA.
This is generally not guest triggerable, because the required write is
done by firmware that runs before the guest. Also, it only affects AMD
processors and oldish Intel that do not have the FlexPriority feature
(unless you disable FlexPriority, of course; then newer processors are
also affected).
Fixes: b93463aa59d6 ('KVM: Accelerated apic support')
Reported-by: Andrew Honig <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Honig <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | void kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
{
if (vapic_addr) {
if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
&vcpu->arch.apic->vapic_cache,
vapic_addr, sizeof(u32)))
return -EINVAL;
__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
} else {
__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
}
vcpu->arch.apic->vapic_addr = vapic_addr;
return 0;
}
| 165,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_close(struct sock *sk, long timeout)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct list_head *pos, *temp;
unsigned int data_was_unread;
pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
lock_sock(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_state = SCTP_SS_CLOSING;
ep = sctp_sk(sk)->ep;
/* Clean up any skbs sitting on the receive queue. */
data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
/* Walk all associations on an endpoint. */
list_for_each_safe(pos, temp, &ep->asocs) {
asoc = list_entry(pos, struct sctp_association, asocs);
if (sctp_style(sk, TCP)) {
/* A closed association can still be in the list if
* it belongs to a TCP-style listening socket that is
* not yet accepted. If so, free it. If not, send an
* ABORT or SHUTDOWN based on the linger options.
*/
if (sctp_state(asoc, CLOSED)) {
sctp_unhash_established(asoc);
sctp_association_free(asoc);
continue;
}
}
if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
!skb_queue_empty(&asoc->ulpq.reasm) ||
(sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
struct sctp_chunk *chunk;
chunk = sctp_make_abort_user(asoc, NULL, 0);
if (chunk)
sctp_primitive_ABORT(net, asoc, chunk);
} else
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
/* On a TCP-style socket, block for at most linger_time if set. */
if (sctp_style(sk, TCP) && timeout)
sctp_wait_for_close(sk, timeout);
/* This will run the backlog queue. */
release_sock(sk);
/* Supposedly, no process has access to the socket, but
* the net layers still may.
*/
local_bh_disable();
bh_lock_sock(sk);
/* Hold the sock, since sk_common_release() will put sock_put()
* and we have just a little more cleanup.
*/
sock_hold(sk);
sk_common_release(sk);
bh_unlock_sock(sk);
local_bh_enable();
sock_put(sk);
SCTP_DBG_OBJCNT_DEC(sock);
}
Commit Message: sctp: fix ASCONF list handling
->auto_asconf_splist is per namespace and mangled by functions like
sctp_setsockopt_auto_asconf() which doesn't guarantee any serialization.
Also, the call to inet_sk_copy_descendant() was backuping
->auto_asconf_list through the copy but was not honoring
->do_auto_asconf, which could lead to list corruption if it was
different between both sockets.
This commit thus fixes the list handling by using ->addr_wq_lock
spinlock to protect the list. A special handling is done upon socket
creation and destruction for that. Error handlig on sctp_init_sock()
will never return an error after having initialized asconf, so
sctp_destroy_sock() can be called without addrq_wq_lock. The lock now
will be take on sctp_close_sock(), before locking the socket, so we
don't do it in inverse order compared to sctp_addr_wq_timeout_handler().
Instead of taking the lock on sctp_sock_migrate() for copying and
restoring the list values, it's preferred to avoid rewritting it by
implementing sctp_copy_descendant().
Issue was found with a test application that kept flipping sysctl
default_auto_asconf on and off, but one could trigger it by issuing
simultaneous setsockopt() calls on multiple sockets or by
creating/destroying sockets fast enough. This is only triggerable
locally.
Fixes: 9f7d653b67ae ("sctp: Add Auto-ASCONF support (core).")
Reported-by: Ji Jianwen <[email protected]>
Suggested-by: Neil Horman <[email protected]>
Suggested-by: Hannes Frederic Sowa <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static void sctp_close(struct sock *sk, long timeout)
{
struct net *net = sock_net(sk);
struct sctp_endpoint *ep;
struct sctp_association *asoc;
struct list_head *pos, *temp;
unsigned int data_was_unread;
pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
lock_sock(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
sk->sk_state = SCTP_SS_CLOSING;
ep = sctp_sk(sk)->ep;
/* Clean up any skbs sitting on the receive queue. */
data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
/* Walk all associations on an endpoint. */
list_for_each_safe(pos, temp, &ep->asocs) {
asoc = list_entry(pos, struct sctp_association, asocs);
if (sctp_style(sk, TCP)) {
/* A closed association can still be in the list if
* it belongs to a TCP-style listening socket that is
* not yet accepted. If so, free it. If not, send an
* ABORT or SHUTDOWN based on the linger options.
*/
if (sctp_state(asoc, CLOSED)) {
sctp_unhash_established(asoc);
sctp_association_free(asoc);
continue;
}
}
if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
!skb_queue_empty(&asoc->ulpq.reasm) ||
(sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
struct sctp_chunk *chunk;
chunk = sctp_make_abort_user(asoc, NULL, 0);
if (chunk)
sctp_primitive_ABORT(net, asoc, chunk);
} else
sctp_primitive_SHUTDOWN(net, asoc, NULL);
}
/* On a TCP-style socket, block for at most linger_time if set. */
if (sctp_style(sk, TCP) && timeout)
sctp_wait_for_close(sk, timeout);
/* This will run the backlog queue. */
release_sock(sk);
/* Supposedly, no process has access to the socket, but
* the net layers still may.
* Also, sctp_destroy_sock() needs to be called with addr_wq_lock
* held and that should be grabbed before socket lock.
*/
spin_lock_bh(&net->sctp.addr_wq_lock);
bh_lock_sock(sk);
/* Hold the sock, since sk_common_release() will put sock_put()
* and we have just a little more cleanup.
*/
sock_hold(sk);
sk_common_release(sk);
bh_unlock_sock(sk);
spin_unlock_bh(&net->sctp.addr_wq_lock);
sock_put(sk);
SCTP_DBG_OBJCNT_DEC(sock);
}
| 166,628 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TargetHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
auto_attacher_.SetRenderFrameHost(frame_host);
}
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 | void TargetHandler::SetRenderer(RenderProcessHost* process_host,
void TargetHandler::SetRenderer(int process_host_id,
RenderFrameHostImpl* frame_host) {
auto_attacher_.SetRenderFrameHost(frame_host);
}
| 172,780 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmGlobalEntry *ptr = NULL;
int buflen = bin->buf->length;
if (sec->payload_data + 32 > buflen) {
return 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 && len < buflen && r < count) {
if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) {
return ret;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
r_list_append (ret, ptr);
r++;
}
return ret;
beach:
free (ptr);
return ret;
}
Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr
CWE ID: CWE-125 | static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) {
RList *ret = NULL;
RBinWasmGlobalEntry *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 (RBinWasmGlobalEntry))) {
return ret;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) {
goto beach;
}
if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) {
goto beach;
}
r_list_append (ret, ptr);
r++;
}
return ret;
beach:
free (ptr);
return ret;
}
| 168,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *ieee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx;
int err;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
return -EMSGSIZE;
ieee = nla_nest_start(skb, DCB_ATTR_IEEE);
if (!ieee)
return -EMSGSIZE;
if (ops->ieee_getets) {
struct ieee_ets ets;
err = ops->ieee_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_getmaxrate) {
struct ieee_maxrate maxrate;
err = ops->ieee_getmaxrate(netdev, &maxrate);
if (!err) {
err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE,
sizeof(maxrate), &maxrate);
if (err)
return -EMSGSIZE;
}
}
if (ops->ieee_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE);
if (!app)
return -EMSGSIZE;
spin_lock(&dcb_lock);
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app),
&itr->app);
if (err) {
spin_unlock(&dcb_lock);
return -EMSGSIZE;
}
}
}
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
nla_nest_end(skb, app);
/* get peer info if available */
if (ops->ieee_peer_getets) {
struct ieee_ets ets;
err = ops->ieee_peer_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_peer_getpfc) {
struct ieee_pfc pfc;
err = ops->ieee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_IEEE_PEER_APP,
DCB_ATTR_IEEE_APP_UNSPEC,
DCB_ATTR_IEEE_APP);
if (err)
return -EMSGSIZE;
}
nla_nest_end(skb, ieee);
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
return -EMSGSIZE;
}
return 0;
}
Commit Message: dcbnl: fix various netlink info leaks
The dcb netlink interface leaks stack memory in various places:
* perm_addr[] buffer is only filled at max with 12 of the 32 bytes but
copied completely,
* no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand,
so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes
for ieee_pfc structs, etc.,
* the same is true for CEE -- no in-kernel driver fills the whole
struct,
Prevent all of the above stack info leaks by properly initializing the
buffers/structures involved.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int dcbnl_ieee_fill(struct sk_buff *skb, struct net_device *netdev)
{
struct nlattr *ieee, *app;
struct dcb_app_type *itr;
const struct dcbnl_rtnl_ops *ops = netdev->dcbnl_ops;
int dcbx;
int err;
if (nla_put_string(skb, DCB_ATTR_IFNAME, netdev->name))
return -EMSGSIZE;
ieee = nla_nest_start(skb, DCB_ATTR_IEEE);
if (!ieee)
return -EMSGSIZE;
if (ops->ieee_getets) {
struct ieee_ets ets;
memset(&ets, 0, sizeof(ets));
err = ops->ieee_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_getmaxrate) {
struct ieee_maxrate maxrate;
memset(&maxrate, 0, sizeof(maxrate));
err = ops->ieee_getmaxrate(netdev, &maxrate);
if (!err) {
err = nla_put(skb, DCB_ATTR_IEEE_MAXRATE,
sizeof(maxrate), &maxrate);
if (err)
return -EMSGSIZE;
}
}
if (ops->ieee_getpfc) {
struct ieee_pfc pfc;
memset(&pfc, 0, sizeof(pfc));
err = ops->ieee_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
app = nla_nest_start(skb, DCB_ATTR_IEEE_APP_TABLE);
if (!app)
return -EMSGSIZE;
spin_lock(&dcb_lock);
list_for_each_entry(itr, &dcb_app_list, list) {
if (itr->ifindex == netdev->ifindex) {
err = nla_put(skb, DCB_ATTR_IEEE_APP, sizeof(itr->app),
&itr->app);
if (err) {
spin_unlock(&dcb_lock);
return -EMSGSIZE;
}
}
}
if (netdev->dcbnl_ops->getdcbx)
dcbx = netdev->dcbnl_ops->getdcbx(netdev);
else
dcbx = -EOPNOTSUPP;
spin_unlock(&dcb_lock);
nla_nest_end(skb, app);
/* get peer info if available */
if (ops->ieee_peer_getets) {
struct ieee_ets ets;
memset(&ets, 0, sizeof(ets));
err = ops->ieee_peer_getets(netdev, &ets);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_ETS, sizeof(ets), &ets))
return -EMSGSIZE;
}
if (ops->ieee_peer_getpfc) {
struct ieee_pfc pfc;
memset(&pfc, 0, sizeof(pfc));
err = ops->ieee_peer_getpfc(netdev, &pfc);
if (!err &&
nla_put(skb, DCB_ATTR_IEEE_PEER_PFC, sizeof(pfc), &pfc))
return -EMSGSIZE;
}
if (ops->peer_getappinfo && ops->peer_getapptable) {
err = dcbnl_build_peer_app(netdev, skb,
DCB_ATTR_IEEE_PEER_APP,
DCB_ATTR_IEEE_APP_UNSPEC,
DCB_ATTR_IEEE_APP);
if (err)
return -EMSGSIZE;
}
nla_nest_end(skb, ieee);
if (dcbx >= 0) {
err = nla_put_u8(skb, DCB_ATTR_DCBX, dcbx);
if (err)
return -EMSGSIZE;
}
return 0;
}
| 166,059 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
assert(m_pos < 0);
assert(m_pUnknownSize);
#if 0
assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this
const long long element_start = m_pUnknownSize->m_element_start;
pos = -m_pos;
assert(pos > element_start);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
long long element_size = -1;
for (;;) { //determine cluster size
if ((total >= 0) && (pos >= total))
{
element_size = total - element_start;
assert(element_size > 0);
break;
}
if ((segment_stop >= 0) && (pos >= segment_stop))
{
element_size = segment_stop - element_start;
assert(element_size > 0);
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) //error (or underflow)
return static_cast<long>(id);
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID
element_size = pos - element_start;
assert(element_size > 0);
break;
}
#ifdef _DEBUG
switch (id)
{
case 0x20: //BlockGroup
case 0x23: //Simple Block
case 0x67: //TimeCode
case 0x2B: //PrevSize
break;
default:
assert(false);
break;
}
#endif
pos += len; //consume ID (of sub-element)
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
pos += len; //consume size field of element
if (size == 0) //weird
continue;
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID; //not allowed for sub-elements
if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird
return E_FILE_FORMAT_INVALID;
pos += size; //consume payload of sub-element
assert((segment_stop < 0) || (pos <= segment_stop));
} //determine cluster size
assert(element_size >= 0);
m_pos = element_start + element_size;
m_pUnknownSize = 0;
return 2; //continue parsing
#else
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) // error or underflow
return status;
if (status == 0) // parsed a block
return 2; // continue parsing
assert(status > 0); // nothing left to parse of this cluster
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
assert(size >= 0);
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; // continue parsing
#endif
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) {
if (m_pos >= 0 || m_pUnknownSize == NULL)
return E_PARSE_FAILED;
const long status = m_pUnknownSize->Parse(pos, len);
if (status < 0) // error or underflow
return status;
if (status == 0) // parsed a block
return 2; // continue parsing
const long long start = m_pUnknownSize->m_element_start;
const long long size = m_pUnknownSize->GetElementSize();
if (size < 0)
return E_FILE_FORMAT_INVALID;
pos = start + size;
m_pos = pos;
m_pUnknownSize = 0;
return 2; // continue parsing
}
| 173,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
{
major = 1;
minor = 0;
build = 0;
revision = 27;
}
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 | void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision)
| 174,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: QTN2QT(QTNode *in)
{
TSQuery out;
int len;
int sumlen = 0,
nnode = 0;
QTN2QTState state;
cntsize(in, &sumlen, &nnode);
len = COMPUTESIZE(nnode, sumlen);
out = (TSQuery) palloc0(len);
SET_VARSIZE(out, len);
out->size = nnode;
state.curitem = GETQUERY(out);
state.operand = state.curoperand = GETOPERAND(out);
fillQT(&state, in);
return out;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | QTN2QT(QTNode *in)
{
TSQuery out;
int len;
int sumlen = 0,
nnode = 0;
QTN2QTState state;
cntsize(in, &sumlen, &nnode);
if (TSQUERY_TOO_BIG(nnode, sumlen))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("tsquery is too large")));
len = COMPUTESIZE(nnode, sumlen);
out = (TSQuery) palloc0(len);
SET_VARSIZE(out, len);
out->size = nnode;
state.curitem = GETQUERY(out);
state.operand = state.curoperand = GETOPERAND(out);
fillQT(&state, in);
return out;
}
| 166,414 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)
{
zval **ptr, **zdata_ptr;
php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);
#if 0
{
zval tmp;
INIT_PZVAL_ARRAY(&tmp, params);
fprintf(stderr, "params = ");
zend_print_zval_r(&tmp, 1 TSRMLS_CC);
fprintf(stderr, "\n");
}
#endif
hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);
if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))
|| (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))
) {
zval *tmp, *arg, **args;
/* create the entry if it doesn't exist */
zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);
Z_ADDREF_PP(ptr);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr);
MAKE_STD_ZVAL(arg);
array_init(arg);
zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args);
*current_args = args;
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);
}
} else {
/* merge */
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);
} else {
zend_hash_index_find(params, hkey.num, (void *) &ptr);
}
zdata_ptr = &zdata;
if (Z_TYPE_PP(ptr) == IS_ARRAY
&& SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr)
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)
) {
/*
* params = [arr => [value => [0 => 1]]]
* ^- ptr
* zdata = [arr => [0 => NULL]]
* ^- zdata_ptr
*/
zval **test_ptr;
while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)
) {
if (Z_TYPE_PP(test_ptr) == IS_ARRAY) {
/* now find key in ptr */
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
} else {
if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else if (hkey.num) {
Z_ADDREF_PP(test_ptr);
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
}
} else {
/* this is the leaf */
Z_ADDREF_PP(test_ptr);
if (Z_TYPE_PP(ptr) != IS_ARRAY) {
zval_dtor(*ptr);
array_init(*ptr);
}
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else if (hkey.num) {
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
}
break;
}
}
}
}
/* bubble up */
while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));
*current_param = ptr;
}
Commit Message: fix bug #73055
CWE ID: CWE-704 | static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)
{
zval **ptr, **zdata_ptr;
php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);
#if 0
{
zval tmp;
INIT_PZVAL_ARRAY(&tmp, params);
fprintf(stderr, "params = ");
zend_print_zval_r(&tmp, 1 TSRMLS_CC);
fprintf(stderr, "\n");
}
#endif
hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);
if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))
|| (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))
) {
zval *tmp, *arg, **args;
/* create the entry if it doesn't exist */
zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);
Z_ADDREF_PP(ptr);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr);
MAKE_STD_ZVAL(arg);
array_init(arg);
zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args);
*current_args = args;
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);
}
} else {
/* merge */
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);
} else {
zend_hash_index_find(params, hkey.num, (void *) &ptr);
}
zdata_ptr = &zdata;
if (Z_TYPE_PP(ptr) == IS_ARRAY
&& SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr)
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)
) {
/*
* params = [arr => [value => [0 => 1]]]
* ^- ptr
* zdata = [arr => [0 => NULL]]
* ^- zdata_ptr
*/
zval **test_ptr;
while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)
) {
if (Z_TYPE_PP(test_ptr) == IS_ARRAY && Z_TYPE_PP(ptr) == IS_ARRAY) {
/* now find key in ptr */
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
} else {
if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else if (hkey.num) {
Z_ADDREF_PP(test_ptr);
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
}
} else {
/* this is the leaf */
Z_ADDREF_PP(test_ptr);
if (Z_TYPE_PP(ptr) != IS_ARRAY) {
zval_dtor(*ptr);
array_init(*ptr);
}
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else if (hkey.num) {
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
}
break;
}
}
}
}
/* bubble up */
while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));
*current_param = ptr;
}
| 169,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cg_opendir(const char *path, struct fuse_file_info *fi)
{
struct fuse_context *fc = fuse_get_context();
const char *cgroup;
struct file_info *dir_info;
char *controller = NULL;
if (!fc)
return -EIO;
if (strcmp(path, "/cgroup") == 0) {
cgroup = NULL;
controller = NULL;
} else {
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup) {
/* this is just /cgroup/controller, return its contents */
cgroup = "/";
}
}
if (cgroup && !fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) {
return -EACCES;
}
/* we'll free this at cg_releasedir */
dir_info = malloc(sizeof(*dir_info));
if (!dir_info)
return -ENOMEM;
dir_info->controller = must_copy_string(controller);
dir_info->cgroup = must_copy_string(cgroup);
dir_info->type = LXC_TYPE_CGDIR;
dir_info->buf = NULL;
dir_info->file = NULL;
dir_info->buflen = 0;
fi->fh = (unsigned long)dir_info;
return 0;
}
Commit Message: Fix checking of parent directories
Taken from the justification in the launchpad bug:
To a task in freezer cgroup /a/b/c/d, it should appear that there are no
cgroups other than its descendents. Since this is a filesystem, we must have
the parent directories, but each parent cgroup should only contain the child
which the task can see.
So, when this task looks at /a/b, it should see only directory 'c' and no
files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already
exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x
exists or not. Opening /a/b/tasks should result in -ENOENT.
The caller_may_see_dir checks specifically whether a task may see a cgroup
directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing
opendir('/a/b/c/d').
caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at
/a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the
task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only)
directory which he can see in the path - 'c'.
Beyond this, regular DAC permissions should apply, with the
root-in-user-namespace privilege over its mapped uids being respected. The
fc_may_access check does this check for both directories and files.
This is CVE-2015-1342 (LP: #1508481)
Signed-off-by: Serge Hallyn <[email protected]>
CWE ID: CWE-264 | static int cg_opendir(const char *path, struct fuse_file_info *fi)
{
struct fuse_context *fc = fuse_get_context();
const char *cgroup;
struct file_info *dir_info;
char *controller = NULL;
if (!fc)
return -EIO;
if (strcmp(path, "/cgroup") == 0) {
cgroup = NULL;
controller = NULL;
} else {
controller = pick_controller_from_path(fc, path);
if (!controller)
return -EIO;
cgroup = find_cgroup_in_path(path);
if (!cgroup) {
/* this is just /cgroup/controller, return its contents */
cgroup = "/";
}
}
if (cgroup) {
if (!caller_may_see_dir(fc->pid, controller, cgroup))
return -ENOENT;
if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY))
return -EACCES;
}
/* we'll free this at cg_releasedir */
dir_info = malloc(sizeof(*dir_info));
if (!dir_info)
return -ENOMEM;
dir_info->controller = must_copy_string(controller);
dir_info->cgroup = must_copy_string(cgroup);
dir_info->type = LXC_TYPE_CGDIR;
dir_info->buf = NULL;
dir_info->file = NULL;
dir_info->buflen = 0;
fi->fh = (unsigned long)dir_info;
return 0;
}
| 166,707 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PasswordInputType::EnableSecureTextInput() {
LocalFrame* frame = GetElement().GetDocument().GetFrame();
if (!frame)
return;
frame->Selection().SetUseSecureKeyboardEntryWhenActive(true);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | void PasswordInputType::EnableSecureTextInput() {
| 171,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev,
struct dj_report *dj_report)
{
/* Called in delayed work context */
struct hid_device *djrcv_hdev = djrcv_dev->hdev;
struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent);
struct usb_device *usbdev = interface_to_usbdev(intf);
struct hid_device *dj_hiddev;
struct dj_device *dj_dev;
/* Device index goes from 1 to 6, we need 3 bytes to store the
* semicolon, the index, and a null terminator
*/
unsigned char tmpstr[3];
if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] &
SPFUNCTION_DEVICE_LIST_EMPTY) {
dbg_hid("%s: device list is empty\n", __func__);
djrcv_dev->querying_devices = false;
return;
}
if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) ||
(dj_report->device_index > DJ_DEVICE_INDEX_MAX)) {
dev_err(&djrcv_hdev->dev, "%s: invalid device index:%d\n",
__func__, dj_report->device_index);
return;
}
if (djrcv_dev->paired_dj_devices[dj_report->device_index]) {
/* The device is already known. No need to reallocate it. */
dbg_hid("%s: device is already known\n", __func__);
return;
}
dj_hiddev = hid_allocate_device();
if (IS_ERR(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n",
__func__);
return;
}
dj_hiddev->ll_driver = &logi_dj_ll_driver;
dj_hiddev->dev.parent = &djrcv_hdev->dev;
dj_hiddev->bus = BUS_USB;
dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor);
dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct);
snprintf(dj_hiddev->name, sizeof(dj_hiddev->name),
"Logitech Unifying Device. Wireless PID:%02x%02x",
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB],
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]);
usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys));
snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index);
strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys));
dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL);
if (!dj_dev) {
dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n",
__func__);
goto dj_device_allocate_fail;
}
dj_dev->reports_supported = get_unaligned_le32(
dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE);
dj_dev->hdev = dj_hiddev;
dj_dev->dj_receiver_dev = djrcv_dev;
dj_dev->device_index = dj_report->device_index;
dj_hiddev->driver_data = dj_dev;
djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev;
if (hid_add_device(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n",
__func__);
goto hid_add_device_fail;
}
return;
hid_add_device_fail:
djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL;
kfree(dj_dev);
dj_device_allocate_fail:
hid_destroy_device(dj_hiddev);
}
Commit Message: HID: logitech: perform bounds checking on device_id early enough
device_index is a char type and the size of paired_dj_deivces is 7
elements, therefore proper bounds checking has to be applied to
device_index before it is used.
We are currently performing the bounds checking in
logi_dj_recv_add_djhid_device(), which is too late, as malicious device
could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the
problem in one of the report forwarding functions called from
logi_dj_raw_event().
Fix this by performing the check at the earliest possible ocasion in
logi_dj_raw_event().
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-119 | static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev,
struct dj_report *dj_report)
{
/* Called in delayed work context */
struct hid_device *djrcv_hdev = djrcv_dev->hdev;
struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent);
struct usb_device *usbdev = interface_to_usbdev(intf);
struct hid_device *dj_hiddev;
struct dj_device *dj_dev;
/* Device index goes from 1 to 6, we need 3 bytes to store the
* semicolon, the index, and a null terminator
*/
unsigned char tmpstr[3];
if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] &
SPFUNCTION_DEVICE_LIST_EMPTY) {
dbg_hid("%s: device list is empty\n", __func__);
djrcv_dev->querying_devices = false;
return;
}
if (djrcv_dev->paired_dj_devices[dj_report->device_index]) {
/* The device is already known. No need to reallocate it. */
dbg_hid("%s: device is already known\n", __func__);
return;
}
dj_hiddev = hid_allocate_device();
if (IS_ERR(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n",
__func__);
return;
}
dj_hiddev->ll_driver = &logi_dj_ll_driver;
dj_hiddev->dev.parent = &djrcv_hdev->dev;
dj_hiddev->bus = BUS_USB;
dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor);
dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct);
snprintf(dj_hiddev->name, sizeof(dj_hiddev->name),
"Logitech Unifying Device. Wireless PID:%02x%02x",
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB],
dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]);
usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys));
snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index);
strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys));
dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL);
if (!dj_dev) {
dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n",
__func__);
goto dj_device_allocate_fail;
}
dj_dev->reports_supported = get_unaligned_le32(
dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE);
dj_dev->hdev = dj_hiddev;
dj_dev->dj_receiver_dev = djrcv_dev;
dj_dev->device_index = dj_report->device_index;
dj_hiddev->driver_data = dj_dev;
djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev;
if (hid_add_device(dj_hiddev)) {
dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n",
__func__);
goto hid_add_device_fail;
}
return;
hid_add_device_fail:
djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL;
kfree(dj_dev);
dj_device_allocate_fail:
hid_destroy_device(dj_hiddev);
}
| 166,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const CuePoint* Cues::GetFirst() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const CuePoint* Cues::GetFirst() const
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
| 174,321 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DocumentLoader::InstallNewDocument(
const KURL& url,
Document* owner_document,
WebGlobalObjectReusePolicy global_object_reuse_policy,
const AtomicString& mime_type,
const AtomicString& encoding,
InstallNewDocumentReason reason,
ParserSynchronizationPolicy parsing_policy,
const KURL& overriding_url) {
DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive());
DCHECK_EQ(frame_->Tree().ChildCount(), 0u);
if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) {
GetFrameLoader().StateMachine()->AdvanceTo(
FrameLoaderStateMachine::kCommittedFirstRealLoad);
}
const SecurityOrigin* previous_security_origin = nullptr;
if (frame_->GetDocument())
previous_security_origin = frame_->GetDocument()->GetSecurityOrigin();
if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting)
frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_));
if (reason == InstallNewDocumentReason::kNavigation)
WillCommitNavigation();
Document* document = frame_->DomWindow()->InstallNewDocument(
mime_type,
DocumentInit::Create()
.WithDocumentLoader(this)
.WithURL(url)
.WithOwnerDocument(owner_document)
.WithNewRegistrationContext(),
false);
if (frame_->IsMainFrame())
frame_->ClearActivation();
if (frame_->HasReceivedUserGestureBeforeNavigation() !=
had_sticky_activation_) {
frame_->SetDocumentHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
}
if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) {
frame_->Tree().ExperimentalSetNulledName();
}
if (!overriding_url.IsEmpty())
document->SetBaseURLOverride(overriding_url);
DidInstallNewDocument(document);
if (reason == InstallNewDocumentReason::kNavigation)
DidCommitNavigation(global_object_reuse_policy);
if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) {
if (document->GetSettings()
->GetForceTouchEventFeatureDetectionForInspector()) {
OriginTrialContext::FromOrCreate(document)->AddFeature(
"ForceTouchEventFeatureDetectionForInspector");
}
OriginTrialContext::AddTokensFromHeader(
document, response_.HttpHeaderField(HTTPNames::Origin_Trial));
}
bool stale_while_revalidate_enabled =
OriginTrials::StaleWhileRevalidateEnabled(document);
fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled);
if (stale_while_revalidate_enabled &&
!RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag())
UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled);
parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding);
ScriptableDocumentParser* scriptable_parser =
parser_->AsScriptableDocumentParser();
if (scriptable_parser && GetResource()) {
scriptable_parser->SetInlineScriptCacheHandler(
ToRawResource(GetResource())->InlineScriptCacheHandler());
}
document->ApplyFeaturePolicyFromHeader(
response_.HttpHeaderField(HTTPNames::Feature_Policy));
GetFrameLoader().DispatchDidClearDocumentOfWindowObject();
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID: | void DocumentLoader::InstallNewDocument(
const KURL& url,
Document* owner_document,
WebGlobalObjectReusePolicy global_object_reuse_policy,
const AtomicString& mime_type,
const AtomicString& encoding,
InstallNewDocumentReason reason,
ParserSynchronizationPolicy parsing_policy,
const KURL& overriding_url) {
DCHECK(!frame_->GetDocument() || !frame_->GetDocument()->IsActive());
DCHECK_EQ(frame_->Tree().ChildCount(), 0u);
if (GetFrameLoader().StateMachine()->IsDisplayingInitialEmptyDocument()) {
GetFrameLoader().StateMachine()->AdvanceTo(
FrameLoaderStateMachine::kCommittedFirstRealLoad);
}
const SecurityOrigin* previous_security_origin = nullptr;
const ContentSecurityPolicy* previous_csp = nullptr;
if (frame_->GetDocument()) {
previous_security_origin = frame_->GetDocument()->GetSecurityOrigin();
previous_csp = frame_->GetDocument()->GetContentSecurityPolicy();
}
if (global_object_reuse_policy != WebGlobalObjectReusePolicy::kUseExisting)
frame_->SetDOMWindow(LocalDOMWindow::Create(*frame_));
if (reason == InstallNewDocumentReason::kNavigation)
WillCommitNavigation();
Document* document = frame_->DomWindow()->InstallNewDocument(
mime_type,
DocumentInit::Create()
.WithDocumentLoader(this)
.WithURL(url)
.WithOwnerDocument(owner_document)
.WithNewRegistrationContext()
.WithPreviousDocumentCSP(previous_csp),
false);
if (frame_->IsMainFrame())
frame_->ClearActivation();
if (frame_->HasReceivedUserGestureBeforeNavigation() !=
had_sticky_activation_) {
frame_->SetDocumentHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
GetLocalFrameClient().SetHasReceivedUserGestureBeforeNavigation(
had_sticky_activation_);
}
if (ShouldClearWindowName(*frame_, previous_security_origin, *document)) {
frame_->Tree().ExperimentalSetNulledName();
}
if (!overriding_url.IsEmpty())
document->SetBaseURLOverride(overriding_url);
DidInstallNewDocument(document, previous_csp);
if (reason == InstallNewDocumentReason::kNavigation)
DidCommitNavigation(global_object_reuse_policy);
if (GetFrameLoader().StateMachine()->CommittedFirstRealDocumentLoad()) {
if (document->GetSettings()
->GetForceTouchEventFeatureDetectionForInspector()) {
OriginTrialContext::FromOrCreate(document)->AddFeature(
"ForceTouchEventFeatureDetectionForInspector");
}
OriginTrialContext::AddTokensFromHeader(
document, response_.HttpHeaderField(HTTPNames::Origin_Trial));
}
bool stale_while_revalidate_enabled =
OriginTrials::StaleWhileRevalidateEnabled(document);
fetcher_->SetStaleWhileRevalidateEnabled(stale_while_revalidate_enabled);
if (stale_while_revalidate_enabled &&
!RuntimeEnabledFeatures::StaleWhileRevalidateEnabledByRuntimeFlag())
UseCounter::Count(frame_, WebFeature::kStaleWhileRevalidateEnabled);
parser_ = document->OpenForNavigation(parsing_policy, mime_type, encoding);
ScriptableDocumentParser* scriptable_parser =
parser_->AsScriptableDocumentParser();
if (scriptable_parser && GetResource()) {
scriptable_parser->SetInlineScriptCacheHandler(
ToRawResource(GetResource())->InlineScriptCacheHandler());
}
document->ApplyFeaturePolicyFromHeader(
response_.HttpHeaderField(HTTPNames::Feature_Policy));
GetFrameLoader().DispatchDidClearDocumentOfWindowObject();
}
| 172,618 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-200 | static int create_problem_dir(GHashTable *problem_info, unsigned pid)
{
/* Exit if free space is less than 1/4 of MaxCrashReportsSize */
if (g_settings_nMaxCrashReportsSize > 0)
{
if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location))
exit(1);
}
/* Create temp directory with the problem data.
* This directory is renamed to final directory name after
* all files have been stored into it.
*/
gchar *dir_basename = g_hash_table_lookup(problem_info, "basename");
if (!dir_basename)
dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE);
char *path = xasprintf("%s/%s-%s-%u.new",
g_settings_dump_location,
dir_basename,
iso_date_string(NULL),
pid);
/* This item is useless, don't save it */
g_hash_table_remove(problem_info, "basename");
/* No need to check the path length, as all variables used are limited,
* and dd_create() fails if the path is too long.
*/
struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE);
if (!dd)
{
error_msg_and_die("Error creating problem directory '%s'", path);
}
dd_create_basic_files(dd, client_uid, NULL);
dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION);
gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE);
if (!gpkey)
{
/* Obtain and save the command line. */
char *cmdline = get_cmdline(pid);
if (cmdline)
{
dd_save_text(dd, FILENAME_CMDLINE, cmdline);
free(cmdline);
}
}
/* Store id of the user whose application crashed. */
char uid_str[sizeof(long) * 3 + 2];
sprintf(uid_str, "%lu", (long)client_uid);
dd_save_text(dd, FILENAME_UID, uid_str);
GHashTableIter iter;
gpointer gpvalue;
g_hash_table_iter_init(&iter, problem_info);
while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue))
{
dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue);
}
dd_close(dd);
/* Not needing it anymore */
g_hash_table_destroy(problem_info);
/* Move the completely created problem directory
* to final directory.
*/
char *newpath = xstrndup(path, strlen(path) - strlen(".new"));
if (rename(path, newpath) == 0)
strcpy(path, newpath);
free(newpath);
log_notice("Saved problem directory of pid %u to '%s'", pid, path);
/* We let the peer know that problem dir was created successfully
* _before_ we run potentially long-running post-create.
*/
printf("HTTP/1.1 201 Created\r\n\r\n");
fflush(NULL);
close(STDOUT_FILENO);
xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */
/* Trim old problem directories if necessary */
if (g_settings_nMaxCrashReportsSize > 0)
{
trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path);
}
run_post_create(path);
/* free(path); */
exit(0);
}
| 170,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | USHORT CNB::QueryL4HeaderOffset(PVOID PacketData, ULONG IpHeaderOffset) const
{
USHORT Res;
auto ppr = ParaNdis_ReviewIPPacket(RtlOffsetToPointer(PacketData, IpHeaderOffset),
GetDataLength(), FALSE, __FUNCTION__);
if (ppr.ipStatus != ppresNotIP)
{
Res = static_cast<USHORT>(IpHeaderOffset + ppr.ipHeaderSize);
}
else
{
DPrintf(0, ("[%s] ERROR: NOT an IP packet - expected troubles!\n", __FUNCTION__));
Res = 0;
}
return Res;
}
| 170,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyMono24(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMono24(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] >> 8;
}
}
| 174,016 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserMainParts::PostDestroyThreads() {
if (BrowserProcessMain::GetInstance()->GetProcessModel() ==
PROCESS_MODEL_SINGLE_PROCESS) {
BrowserContext::AssertNoContextsExist();
}
device_client_.reset();
display::Screen::SetScreenInstance(nullptr);
gpu::oxide_shim::SetGLShareGroup(nullptr);
gl_share_context_ = nullptr;
#if defined(OS_LINUX)
gpu::SetGpuInfoCollectorOxideLinux(nullptr);
#endif
}
Commit Message:
CWE ID: CWE-20 | void BrowserMainParts::PostDestroyThreads() {
device_client_.reset();
display::Screen::SetScreenInstance(nullptr);
gpu::oxide_shim::SetGLShareGroup(nullptr);
gl_share_context_ = nullptr;
#if defined(OS_LINUX)
gpu::SetGpuInfoCollectorOxideLinux(nullptr);
#endif
}
| 165,422 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int list_locations(struct kmem_cache *s, char *buf,
enum track_item alloc)
{
int len = 0;
unsigned long i;
struct loc_track t = { 0, 0, NULL };
int node;
if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
GFP_TEMPORARY))
return sprintf(buf, "Out of memory\n");
/* Push back cpu slabs */
flush_all(s);
for_each_node_state(node, N_NORMAL_MEMORY) {
struct kmem_cache_node *n = get_node(s, node);
unsigned long flags;
struct page *page;
if (!atomic_long_read(&n->nr_slabs))
continue;
spin_lock_irqsave(&n->list_lock, flags);
list_for_each_entry(page, &n->partial, lru)
process_slab(&t, s, page, alloc);
list_for_each_entry(page, &n->full, lru)
process_slab(&t, s, page, alloc);
spin_unlock_irqrestore(&n->list_lock, flags);
}
for (i = 0; i < t.count; i++) {
struct location *l = &t.loc[i];
if (len > PAGE_SIZE - 100)
break;
len += sprintf(buf + len, "%7ld ", l->count);
if (l->addr)
len += sprint_symbol(buf + len, (unsigned long)l->addr);
else
len += sprintf(buf + len, "<not-available>");
if (l->sum_time != l->min_time) {
unsigned long remainder;
len += sprintf(buf + len, " age=%ld/%ld/%ld",
l->min_time,
div_long_long_rem(l->sum_time, l->count, &remainder),
l->max_time);
} else
len += sprintf(buf + len, " age=%ld",
l->min_time);
if (l->min_pid != l->max_pid)
len += sprintf(buf + len, " pid=%ld-%ld",
l->min_pid, l->max_pid);
else
len += sprintf(buf + len, " pid=%ld",
l->min_pid);
if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " cpus=");
len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->cpus);
}
if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " nodes=");
len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->nodes);
}
len += sprintf(buf + len, "\n");
}
free_loc_track(&t);
if (!t.count)
len += sprintf(buf, "No data\n");
return len;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int list_locations(struct kmem_cache *s, char *buf,
enum track_item alloc)
{
int len = 0;
unsigned long i;
struct loc_track t = { 0, 0, NULL };
int node;
if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location),
GFP_TEMPORARY))
return sprintf(buf, "Out of memory\n");
/* Push back cpu slabs */
flush_all(s);
for_each_node_state(node, N_NORMAL_MEMORY) {
struct kmem_cache_node *n = get_node(s, node);
unsigned long flags;
struct page *page;
if (!atomic_long_read(&n->nr_slabs))
continue;
spin_lock_irqsave(&n->list_lock, flags);
list_for_each_entry(page, &n->partial, lru)
process_slab(&t, s, page, alloc);
list_for_each_entry(page, &n->full, lru)
process_slab(&t, s, page, alloc);
spin_unlock_irqrestore(&n->list_lock, flags);
}
for (i = 0; i < t.count; i++) {
struct location *l = &t.loc[i];
if (len > PAGE_SIZE - 100)
break;
len += sprintf(buf + len, "%7ld ", l->count);
if (l->addr)
len += sprint_symbol(buf + len, (unsigned long)l->addr);
else
len += sprintf(buf + len, "<not-available>");
if (l->sum_time != l->min_time) {
len += sprintf(buf + len, " age=%ld/%ld/%ld",
l->min_time,
(long)div_u64(l->sum_time, l->count),
l->max_time);
} else
len += sprintf(buf + len, " age=%ld",
l->min_time);
if (l->min_pid != l->max_pid)
len += sprintf(buf + len, " pid=%ld-%ld",
l->min_pid, l->max_pid);
else
len += sprintf(buf + len, " pid=%ld",
l->min_pid);
if (num_online_cpus() > 1 && !cpus_empty(l->cpus) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " cpus=");
len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->cpus);
}
if (num_online_nodes() > 1 && !nodes_empty(l->nodes) &&
len < PAGE_SIZE - 60) {
len += sprintf(buf + len, " nodes=");
len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50,
l->nodes);
}
len += sprintf(buf + len, "\n");
}
free_loc_track(&t);
if (!t.count)
len += sprintf(buf, "No data\n");
return len;
}
| 165,758 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_bearer_type_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
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_bearer_type_print(netdissect_options *ndo, const u_char *dat)
l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) {
ND_PRINT((ndo, "D"));
}
}
| 167,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.add(name.impl());
if (Frame* f = frame())
f->script()->namedItemAdded(this, name);
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void HTMLDocument::addItemToMap(HashCountedSet<StringImpl*>& map, const AtomicString& name)
void HTMLDocument::addItemToMap(HashCountedSet<AtomicString>& map, const AtomicString& name)
{
if (name.isEmpty())
return;
map.add(name);
if (Frame* f = frame())
f->script()->namedItemAdded(this, name);
}
| 171,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t cm_write(struct file *file, const char __user * user_buf,
size_t count, loff_t *ppos)
{
static char *buf;
static u32 max_size;
static u32 uncopied_bytes;
struct acpi_table_header table;
acpi_status status;
if (!(*ppos)) {
/* parse the table header to get the table length */
if (count <= sizeof(struct acpi_table_header))
return -EINVAL;
if (copy_from_user(&table, user_buf,
sizeof(struct acpi_table_header)))
return -EFAULT;
uncopied_bytes = max_size = table.length;
buf = kzalloc(max_size, GFP_KERNEL);
if (!buf)
return -ENOMEM;
}
if (buf == NULL)
return -EINVAL;
if ((*ppos > max_size) ||
(*ppos + count > max_size) ||
(*ppos + count < count) ||
(count > uncopied_bytes))
return -EINVAL;
if (copy_from_user(buf + (*ppos), user_buf, count)) {
kfree(buf);
buf = NULL;
return -EFAULT;
}
uncopied_bytes -= count;
*ppos += count;
if (!uncopied_bytes) {
status = acpi_install_method(buf);
kfree(buf);
buf = NULL;
if (ACPI_FAILURE(status))
return -EINVAL;
add_taint(TAINT_OVERRIDDEN_ACPI_TABLE);
}
return count;
}
Commit Message: ACPI: Split out custom_method functionality into an own driver
With /sys/kernel/debug/acpi/custom_method root can write
to arbitrary memory and increase his priveleges, even if
these are restricted.
-> Make this an own debug .config option and warn about the
security issue in the config description.
-> Still keep acpi/debugfs.c which now only creates an empty
/sys/kernel/debug/acpi directory. There might be other
users of it later.
Signed-off-by: Thomas Renninger <[email protected]>
Acked-by: Rafael J. Wysocki <[email protected]>
Acked-by: [email protected]
Signed-off-by: Len Brown <[email protected]>
CWE ID: CWE-264 | static ssize_t cm_write(struct file *file, const char __user * user_buf,
| 165,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 MaybeReportDownloadDeepScanningVerdict(
Profile* profile,
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
BinaryUploadService::Result result,
DeepScanningClientResponse response) {
if (response.malware_scan_verdict().verdict() ==
MalwareDeepScanningVerdict::UWS ||
response.malware_scan_verdict().verdict() ==
MalwareDeepScanningVerdict::MALWARE) {
extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile)
->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256);
}
}
Commit Message: Add reporting for DLP deep scanning
For each triggered rule in the DLP response, we report the download as
violating that rule.
This also implements the UnsafeReportingEnabled enterprise policy, which
controls whether or not we do any reporting.
Bug: 980777
Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381
Commit-Queue: Daniel Rubery <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Reviewed-by: Roger Tawa <[email protected]>
Cr-Commit-Position: refs/heads/master@{#691371}
CWE ID: CWE-416 | void MaybeReportDownloadDeepScanningVerdict(
Profile* profile,
const GURL& url,
const std::string& file_name,
const std::string& download_digest_sha256,
BinaryUploadService::Result result,
DeepScanningClientResponse response) {
if (result != BinaryUploadService::Result::SUCCESS)
return;
if (!g_browser_process->local_state()->GetBoolean(
policy::policy_prefs::kUnsafeEventsReportingEnabled))
return;
if (response.malware_scan_verdict().verdict() ==
MalwareDeepScanningVerdict::UWS ||
response.malware_scan_verdict().verdict() ==
MalwareDeepScanningVerdict::MALWARE) {
extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile)
->OnDangerousDeepScanningResult(url, file_name, download_digest_sha256);
}
if (response.dlp_scan_verdict().status() == DlpDeepScanningVerdict::SUCCESS) {
if (!response.dlp_scan_verdict().triggered_rules().empty()) {
extensions::SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile)
->OnSensitiveDataEvent(response.dlp_scan_verdict(), url, file_name,
download_digest_sha256);
}
}
}
| 172,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style,
const xmlChar *name, const xmlChar *ns,
ATTRIBUTE_UNUSED const xmlChar *ignored) {
xsltAttrElemPtr tmp;
xsltAttrElemPtr refs;
tmp = values;
while (tmp != NULL) {
if (tmp->set != NULL) {
/*
* Check against cycles !
*/
if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets recursion detected on %s\n",
name);
} else {
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"Importing attribute list %s\n", tmp->set);
#endif
refs = xsltGetSAS(style, tmp->set, tmp->ns);
if (refs == NULL) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets %s reference missing %s\n",
name, tmp->set);
} else {
/*
* recurse first for cleanup
*/
xsltResolveSASCallback(refs, style, name, ns, NULL);
/*
* Then merge
*/
xsltMergeAttrElemList(style, values, refs);
/*
* Then suppress the reference
*/
tmp->set = NULL;
tmp->ns = NULL;
}
}
}
tmp = tmp->next;
}
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltResolveSASCallback(xsltAttrElemPtr values, xsltStylesheetPtr style,
xsltResolveSASCallbackInt(xsltAttrElemPtr values, xsltStylesheetPtr style,
const xmlChar *name, const xmlChar *ns,
int depth) {
xsltAttrElemPtr tmp;
xsltAttrElemPtr refs;
tmp = values;
if ((name == NULL) || (name[0] == 0))
return;
if (depth > 100) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets recursion detected on %s\n",
name);
return;
}
while (tmp != NULL) {
if (tmp->set != NULL) {
/*
* Check against cycles !
*/
if ((xmlStrEqual(name, tmp->set)) && (xmlStrEqual(ns, tmp->ns))) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets recursion detected on %s\n",
name);
} else {
#ifdef WITH_XSLT_DEBUG_ATTRIBUTES
xsltGenericDebug(xsltGenericDebugContext,
"Importing attribute list %s\n", tmp->set);
#endif
refs = xsltGetSAS(style, tmp->set, tmp->ns);
if (refs == NULL) {
xsltGenericError(xsltGenericErrorContext,
"xsl:attribute-set : use-attribute-sets %s reference missing %s\n",
name, tmp->set);
} else {
/*
* recurse first for cleanup
*/
xsltResolveSASCallbackInt(refs, style, name, ns, depth + 1);
/*
* Then merge
*/
xsltMergeAttrElemList(style, values, refs);
/*
* Then suppress the reference
*/
tmp->set = NULL;
tmp->ns = NULL;
}
}
}
tmp = tmp->next;
}
}
| 173,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenameFile(const DownloadId& id,
const FilePath& new_path,
const FilePath& unique_path,
net::Error rename_error,
RenameFileState state,
RenameFileOverwrite should_overwrite) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Rename(unique_path))
.Times(1)
.WillOnce(Return(rename_error));
if (rename_error != net::OK) {
EXPECT_CALL(*file, BytesSoFar())
.Times(AtLeast(1))
.WillRepeatedly(Return(byte_count_[id]));
EXPECT_CALL(*file, GetHashState())
.Times(AtLeast(1));
EXPECT_CALL(*file, GetDownloadManager())
.Times(AtLeast(1));
} else if (state == COMPLETE) {
#if defined(OS_MACOSX)
EXPECT_CALL(*file, AnnotateWithSourceInformation());
#endif
}
if (state == IN_PROGRESS) {
download_file_manager_->RenameInProgressDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
} else { // state == COMPLETE
download_file_manager_->RenameCompletingDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
}
if (rename_error != net::OK) {
EXPECT_CALL(*download_manager_,
OnDownloadInterrupted(
id.local(),
byte_count_[id],
"",
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), FilePath()));
ProcessAllPendingMessages();
++error_count_[id];
} else {
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), unique_path));
ProcessAllPendingMessages();
}
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void RenameFile(const DownloadId& id,
const FilePath& new_path,
const FilePath& unique_path,
net::Error rename_error,
RenameFileState state,
RenameFileOverwrite should_overwrite) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Rename(unique_path))
.Times(1)
.WillOnce(Return(rename_error));
if (rename_error != net::OK) {
EXPECT_CALL(*file, BytesSoFar())
.Times(AtLeast(1))
.WillRepeatedly(Return(byte_count_[id]));
EXPECT_CALL(*file, GetHashState())
.Times(AtLeast(1));
EXPECT_CALL(*file, GetDownloadManager())
.Times(AtLeast(1));
}
download_file_manager_->RenameDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
if (rename_error != net::OK) {
EXPECT_CALL(*download_manager_,
OnDownloadInterrupted(
id.local(),
byte_count_[id],
"",
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), FilePath()));
ProcessAllPendingMessages();
++error_count_[id];
} else {
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), unique_path));
ProcessAllPendingMessages();
}
}
| 170,881 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SectionHasAutofilledField(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <[email protected]>
Commit-Queue: Sebastien Seguin-Gagnon <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID: | bool SectionHasAutofilledField(const FormStructure& form_structure,
| 173,201 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)
{
struct dentry *parent;
struct inode *p_inode;
int ret = 0;
if (!dentry)
dentry = path->dentry;
if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))
return 0;
parent = dget_parent(dentry);
p_inode = parent->d_inode;
if (unlikely(!fsnotify_inode_watches_children(p_inode)))
__fsnotify_update_child_dentry_flags(p_inode);
else if (p_inode->i_fsnotify_mask & mask) {
/* we are notifying a parent so come up with the new mask which
* specifies these are events which came from a child. */
mask |= FS_EVENT_ON_CHILD;
if (path)
ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,
dentry->d_name.name, 0);
else
ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,
dentry->d_name.name, 0);
}
dput(parent);
return ret;
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362 | int __fsnotify_parent(const struct path *path, struct dentry *dentry, __u32 mask)
{
struct dentry *parent;
struct inode *p_inode;
int ret = 0;
if (!dentry)
dentry = path->dentry;
if (!(dentry->d_flags & DCACHE_FSNOTIFY_PARENT_WATCHED))
return 0;
parent = dget_parent(dentry);
p_inode = parent->d_inode;
if (unlikely(!fsnotify_inode_watches_children(p_inode)))
__fsnotify_update_child_dentry_flags(p_inode);
else if (p_inode->i_fsnotify_mask & mask) {
struct name_snapshot name;
/* we are notifying a parent so come up with the new mask which
* specifies these are events which came from a child. */
mask |= FS_EVENT_ON_CHILD;
take_dentry_name_snapshot(&name, dentry);
if (path)
ret = fsnotify(p_inode, mask, path, FSNOTIFY_EVENT_PATH,
name.name, 0);
else
ret = fsnotify(p_inode, mask, dentry->d_inode, FSNOTIFY_EVENT_INODE,
name.name, 0);
release_dentry_name_snapshot(&name);
}
dput(parent);
return ret;
}
| 168,264 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
sidx = sizeof (t_chunk_info) * nc;
cidx = gdCalloc (sidx, 1);
if (!cidx) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
Commit Message: gd2: handle corrupt images better (CVE-2016-3074)
Make sure we do some range checking on corrupted chunks.
Thanks to Hans Jerry Illikainen <[email protected]> for indepth report
and reproducer information. Made for easy test case writing :).
CWE ID: CWE-189 | _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy,
int *cs, int *vers, int *fmt, int *ncx, int *ncy,
t_chunk_info ** chunkIdx)
{
int i;
int ch;
char id[5];
t_chunk_info *cidx;
int sidx;
int nc;
GD2_DBG (printf ("Reading gd2 header info\n"));
for (i = 0; i < 4; i++) {
ch = gdGetC (in);
if (ch == EOF) {
goto fail1;
};
id[i] = ch;
};
id[4] = 0;
GD2_DBG (printf ("Got file code: %s\n", id));
/* Equiv. of 'magick'. */
if (strcmp (id, GD2_ID) != 0) {
GD2_DBG (printf ("Not a valid gd2 file\n"));
goto fail1;
};
/* Version */
if (gdGetWord (vers, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Version: %d\n", *vers));
if ((*vers != 1) && (*vers != 2)) {
GD2_DBG (printf ("Bad version: %d\n", *vers));
goto fail1;
};
/* Image Size */
if (!gdGetWord (sx, in)) {
GD2_DBG (printf ("Could not get x-size\n"));
goto fail1;
}
if (!gdGetWord (sy, in)) {
GD2_DBG (printf ("Could not get y-size\n"));
goto fail1;
}
GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy));
/* Chunk Size (pixels, not bytes!) */
if (gdGetWord (cs, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("ChunkSize: %d\n", *cs));
if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) {
GD2_DBG (printf ("Bad chunk size: %d\n", *cs));
goto fail1;
};
/* Data Format */
if (gdGetWord (fmt, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("Format: %d\n", *fmt));
if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) &&
(*fmt != GD2_FMT_TRUECOLOR_RAW) &&
(*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) {
GD2_DBG (printf ("Bad data format: %d\n", *fmt));
goto fail1;
};
/* # of chunks wide */
if (gdGetWord (ncx, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks Wide\n", *ncx));
/* # of chunks high */
if (gdGetWord (ncy, in) != 1) {
goto fail1;
};
GD2_DBG (printf ("%d Chunks vertically\n", *ncy));
if (gd2_compressed (*fmt)) {
nc = (*ncx) * (*ncy);
GD2_DBG (printf ("Reading %d chunk index entries\n", nc));
sidx = sizeof (t_chunk_info) * nc;
cidx = gdCalloc (sidx, 1);
if (!cidx) {
goto fail1;
}
for (i = 0; i < nc; i++) {
if (gdGetInt (&cidx[i].offset, in) != 1) {
goto fail2;
};
if (gdGetInt (&cidx[i].size, in) != 1) {
goto fail2;
};
if (cidx[i].offset < 0 || cidx[i].size < 0)
goto fail2;
};
*chunkIdx = cidx;
};
GD2_DBG (printf ("gd2 header complete\n"));
return 1;
fail2:
gdFree(cidx);
fail1:
return 0;
}
| 167,382 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec = {0};
vpx_codec_enc_cfg_t cfg = {0};
int frame_count = 0;
vpx_image_t raw = {0};
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
const int fps = 2; // TODO(dkovalev) add command line argument
const double bits_per_pixel_per_frame = 0.067;
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
encoder = get_vpx_encoder_by_name(argv[1]);
if (!encoder)
die("Unsupported codec.");
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[2], NULL, 0);
info.frame_height = strtol(argv[3], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = (unsigned int)(bits_per_pixel_per_frame * cfg.g_w *
cfg.g_h * fps / 1000);
cfg.g_lag_in_frames = 0;
writer = vpx_video_writer_open(argv[5], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[5]);
if (!(infile = fopen(argv[4], "rb")))
die("Failed to open %s for reading.", argv[4]);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
++frame_count;
if (frame_count == 22 && encoder->fourcc == VP8_FOURCC) {
set_roi_map(&cfg, &codec);
} else if (frame_count == 33) {
set_active_map(&cfg, &codec);
} else if (frame_count == 44) {
unset_active_map(&cfg, &codec);
}
encode_frame(&codec, &raw, frame_count, writer);
}
encode_frame(&codec, NULL, -1, writer);
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | int main(int argc, char **argv) {
FILE *infile = NULL;
vpx_codec_ctx_t codec;
vpx_codec_enc_cfg_t cfg;
int frame_count = 0;
vpx_image_t raw;
vpx_codec_err_t res;
VpxVideoInfo info;
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
const int fps = 2; // TODO(dkovalev) add command line argument
const double bits_per_pixel_per_frame = 0.067;
exec_name = argv[0];
if (argc != 6)
die("Invalid number of arguments");
memset(&info, 0, sizeof(info));
encoder = get_vpx_encoder_by_name(argv[1]);
if (encoder == NULL) {
die("Unsupported codec.");
}
assert(encoder != NULL);
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(argv[2], NULL, 0);
info.frame_height = strtol(argv[3], NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
printf("Using %s\n", vpx_codec_iface_name(encoder->codec_interface()));
res = vpx_codec_enc_config_default(encoder->codec_interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = (unsigned int)(bits_per_pixel_per_frame * cfg.g_w *
cfg.g_h * fps / 1000);
cfg.g_lag_in_frames = 0;
writer = vpx_video_writer_open(argv[5], kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", argv[5]);
if (!(infile = fopen(argv[4], "rb")))
die("Failed to open %s for reading.", argv[4]);
if (vpx_codec_enc_init(&codec, encoder->codec_interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
// Encode frames.
while (vpx_img_read(&raw, infile)) {
++frame_count;
if (frame_count == 22 && encoder->fourcc == VP8_FOURCC) {
set_roi_map(&cfg, &codec);
} else if (frame_count == 33) {
set_active_map(&cfg, &codec);
} else if (frame_count == 44) {
unset_active_map(&cfg, &codec);
}
encode_frame(&codec, &raw, frame_count, writer);
}
// Flush encoder.
while (encode_frame(&codec, NULL, -1, writer)) {}
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
| 174,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long Cluster::GetElementSize() const
{
return m_element_size;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Cluster::GetElementSize() const
| 174,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long restore_tm_sigcontexts(struct pt_regs *regs,
struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs, *tm_v_regs;
#endif
unsigned long err = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));
err |= __copy_from_user(¤t->thread.ckpt_regs, sc->gp_regs,
sizeof(regs->gpr));
/*
* TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.
* TEXASR was set by the signal delivery reclaim, as was TFIAR.
* Users doing anything abhorrent like thread-switching w/ signals for
* TM-Suspended code will have to back TEXASR/TFIAR up themselves.
* For the case of getting a signal and simply returning from it,
* we don't need to re-copy them here.
*/
err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);
err |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
/* pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK);
/* pull in MSR LE from user context */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/* The following non-GPR non-FPR non-VR state is also checkpointed: */
err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);
err |= __get_user(current->thread.ckpt_regs.ctr,
&sc->gp_regs[PT_CTR]);
err |= __get_user(current->thread.ckpt_regs.link,
&sc->gp_regs[PT_LNK]);
err |= __get_user(current->thread.ckpt_regs.xer,
&sc->gp_regs[PT_XER]);
err |= __get_user(current->thread.ckpt_regs.ccr,
&sc->gp_regs[PT_CCR]);
/* These regs are not checkpointed; they can go in 'regs'. */
err |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]);
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
err |= __get_user(tm_v_regs, &tm_sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
if (tm_v_regs && !access_ok(VERIFY_READ,
tm_v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
err |= __copy_from_user(¤t->thread.transact_vr, tm_v_regs,
33 * sizeof(vector128));
}
else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
memset(¤t->thread.transact_vr, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL && tm_v_regs != NULL) {
err |= __get_user(current->thread.vrsave,
(u32 __user *)&v_regs[33]);
err |= __get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_v_regs[33]);
}
else {
current->thread.vrsave = 0;
current->thread.transact_vrsave = 0;
}
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
err |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
if (v_regs && ((msr & MSR_VSX) != 0)) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_from_user(current, v_regs);
err |= copy_transact_vsx_from_user(current, tm_v_regs);
} else {
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
}
#endif
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return err;
}
Commit Message: powerpc/tm: Block signal return setting invalid MSR state
Currently we allow both the MSR T and S bits to be set by userspace on
a signal return. Unfortunately this is a reserved configuration and
will cause a TM Bad Thing exception if attempted (via rfid).
This patch checks for this case in both the 32 and 64 bit signals
code. If both T and S are set, we mark the context as invalid.
Found using a syscall fuzzer.
Fixes: 2b0a576d15e0 ("powerpc: Add new transactional memory state to the signal context")
Cc: [email protected] # v3.9+
Signed-off-by: Michael Neuling <[email protected]>
Signed-off-by: Michael Ellerman <[email protected]>
CWE ID: CWE-20 | static long restore_tm_sigcontexts(struct pt_regs *regs,
struct sigcontext __user *sc,
struct sigcontext __user *tm_sc)
{
#ifdef CONFIG_ALTIVEC
elf_vrreg_t __user *v_regs, *tm_v_regs;
#endif
unsigned long err = 0;
unsigned long msr;
#ifdef CONFIG_VSX
int i;
#endif
/* copy the GPRs */
err |= __copy_from_user(regs->gpr, tm_sc->gp_regs, sizeof(regs->gpr));
err |= __copy_from_user(¤t->thread.ckpt_regs, sc->gp_regs,
sizeof(regs->gpr));
/*
* TFHAR is restored from the checkpointed 'wound-back' ucontext's NIP.
* TEXASR was set by the signal delivery reclaim, as was TFIAR.
* Users doing anything abhorrent like thread-switching w/ signals for
* TM-Suspended code will have to back TEXASR/TFIAR up themselves.
* For the case of getting a signal and simply returning from it,
* we don't need to re-copy them here.
*/
err |= __get_user(regs->nip, &tm_sc->gp_regs[PT_NIP]);
err |= __get_user(current->thread.tm_tfhar, &sc->gp_regs[PT_NIP]);
/* get MSR separately, transfer the LE bit if doing signal return */
err |= __get_user(msr, &sc->gp_regs[PT_MSR]);
/* Don't allow reserved mode. */
if (MSR_TM_RESV(msr))
return -EINVAL;
/* pull in MSR TM from user context */
regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK);
/* pull in MSR LE from user context */
regs->msr = (regs->msr & ~MSR_LE) | (msr & MSR_LE);
/* The following non-GPR non-FPR non-VR state is also checkpointed: */
err |= __get_user(regs->ctr, &tm_sc->gp_regs[PT_CTR]);
err |= __get_user(regs->link, &tm_sc->gp_regs[PT_LNK]);
err |= __get_user(regs->xer, &tm_sc->gp_regs[PT_XER]);
err |= __get_user(regs->ccr, &tm_sc->gp_regs[PT_CCR]);
err |= __get_user(current->thread.ckpt_regs.ctr,
&sc->gp_regs[PT_CTR]);
err |= __get_user(current->thread.ckpt_regs.link,
&sc->gp_regs[PT_LNK]);
err |= __get_user(current->thread.ckpt_regs.xer,
&sc->gp_regs[PT_XER]);
err |= __get_user(current->thread.ckpt_regs.ccr,
&sc->gp_regs[PT_CCR]);
/* These regs are not checkpointed; they can go in 'regs'. */
err |= __get_user(regs->trap, &sc->gp_regs[PT_TRAP]);
err |= __get_user(regs->dar, &sc->gp_regs[PT_DAR]);
err |= __get_user(regs->dsisr, &sc->gp_regs[PT_DSISR]);
err |= __get_user(regs->result, &sc->gp_regs[PT_RESULT]);
/*
* Do this before updating the thread state in
* current->thread.fpr/vr. That way, if we get preempted
* and another task grabs the FPU/Altivec, it won't be
* tempted to save the current CPU state into the thread_struct
* and corrupt what we are writing there.
*/
discard_lazy_cpu_state();
/*
* Force reload of FP/VEC.
* This has to be done before copying stuff into current->thread.fpr/vr
* for the reasons explained in the previous comment.
*/
regs->msr &= ~(MSR_FP | MSR_FE0 | MSR_FE1 | MSR_VEC | MSR_VSX);
#ifdef CONFIG_ALTIVEC
err |= __get_user(v_regs, &sc->v_regs);
err |= __get_user(tm_v_regs, &tm_sc->v_regs);
if (err)
return err;
if (v_regs && !access_ok(VERIFY_READ, v_regs, 34 * sizeof(vector128)))
return -EFAULT;
if (tm_v_regs && !access_ok(VERIFY_READ,
tm_v_regs, 34 * sizeof(vector128)))
return -EFAULT;
/* Copy 33 vec registers (vr0..31 and vscr) from the stack */
if (v_regs != NULL && tm_v_regs != NULL && (msr & MSR_VEC) != 0) {
err |= __copy_from_user(¤t->thread.vr_state, v_regs,
33 * sizeof(vector128));
err |= __copy_from_user(¤t->thread.transact_vr, tm_v_regs,
33 * sizeof(vector128));
}
else if (current->thread.used_vr) {
memset(¤t->thread.vr_state, 0, 33 * sizeof(vector128));
memset(¤t->thread.transact_vr, 0, 33 * sizeof(vector128));
}
/* Always get VRSAVE back */
if (v_regs != NULL && tm_v_regs != NULL) {
err |= __get_user(current->thread.vrsave,
(u32 __user *)&v_regs[33]);
err |= __get_user(current->thread.transact_vrsave,
(u32 __user *)&tm_v_regs[33]);
}
else {
current->thread.vrsave = 0;
current->thread.transact_vrsave = 0;
}
if (cpu_has_feature(CPU_FTR_ALTIVEC))
mtspr(SPRN_VRSAVE, current->thread.vrsave);
#endif /* CONFIG_ALTIVEC */
/* restore floating point */
err |= copy_fpr_from_user(current, &sc->fp_regs);
err |= copy_transact_fpr_from_user(current, &tm_sc->fp_regs);
#ifdef CONFIG_VSX
/*
* Get additional VSX data. Update v_regs to point after the
* VMX data. Copy VSX low doubleword from userspace to local
* buffer for formatting, then into the taskstruct.
*/
if (v_regs && ((msr & MSR_VSX) != 0)) {
v_regs += ELF_NVRREG;
tm_v_regs += ELF_NVRREG;
err |= copy_vsx_from_user(current, v_regs);
err |= copy_transact_vsx_from_user(current, tm_v_regs);
} else {
for (i = 0; i < 32 ; i++) {
current->thread.fp_state.fpr[i][TS_VSRLOWOFFSET] = 0;
current->thread.transact_fp.fpr[i][TS_VSRLOWOFFSET] = 0;
}
}
#endif
tm_enable();
/* Make sure the transaction is marked as failed */
current->thread.tm_texasr |= TEXASR_FS;
/* This loads the checkpointed FP/VEC state, if used */
tm_recheckpoint(¤t->thread, msr);
/* This loads the speculative FP/VEC state, if used */
if (msr & MSR_FP) {
do_load_up_transact_fpu(¤t->thread);
regs->msr |= (MSR_FP | current->thread.fpexc_mode);
}
#ifdef CONFIG_ALTIVEC
if (msr & MSR_VEC) {
do_load_up_transact_altivec(¤t->thread);
regs->msr |= MSR_VEC;
}
#endif
return err;
}
| 167,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObject* proxyImp = V8TestObject::toNative(info.Holder());
TestNode* imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void locationWithExceptionAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info)
{
TestObject* proxyImp = V8TestObject::toNative(info.Holder());
RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithException());
if (!imp)
return;
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue);
imp->setHrefThrows(cppValue);
}
| 171,684 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::CreateBlock(long long id,
long long pos, // absolute pos of payload
long long size, long long discard_padding) {
assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock
if (m_entries_count < 0) { // haven't parsed anything yet
assert(m_entries == NULL);
assert(m_entries_size == 0);
m_entries_size = 1024;
m_entries = new BlockEntry* [m_entries_size];
m_entries_count = 0;
} else {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (m_entries_count >= m_entries_size) {
const long entries_size = 2 * m_entries_size;
BlockEntry** const entries = new BlockEntry* [entries_size];
assert(entries);
BlockEntry** src = m_entries;
BlockEntry** const src_end = src + m_entries_count;
BlockEntry** dst = entries;
while (src != src_end)
*dst++ = *src++;
delete[] m_entries;
m_entries = entries;
m_entries_size = entries_size;
}
}
if (id == 0x20) // BlockGroup ID
return CreateBlockGroup(pos, size, discard_padding);
else // SimpleBlock ID
return CreateSimpleBlock(pos, size);
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Cluster::CreateBlock(long long id,
long long pos, // absolute pos of payload
long long size, long long discard_padding) {
assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock
if (m_entries_count < 0) { // haven't parsed anything yet
assert(m_entries == NULL);
assert(m_entries_size == 0);
m_entries_size = 1024;
m_entries = new (std::nothrow) BlockEntry*[m_entries_size];
if (m_entries == NULL)
return -1;
m_entries_count = 0;
} else {
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (m_entries_count >= m_entries_size) {
const long entries_size = 2 * m_entries_size;
BlockEntry** const entries = new (std::nothrow) BlockEntry*[entries_size];
if (entries == NULL)
return -1;
BlockEntry** src = m_entries;
BlockEntry** const src_end = src + m_entries_count;
BlockEntry** dst = entries;
while (src != src_end)
*dst++ = *src++;
delete[] m_entries;
m_entries = entries;
m_entries_size = entries_size;
}
}
if (id == 0x20) // BlockGroup ID
return CreateBlockGroup(pos, size, discard_padding);
else // SimpleBlock ID
return CreateSimpleBlock(pos, size);
}
| 173,805 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 isofs_read_inode(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
struct isofs_sb_info *sbi = ISOFS_SB(sb);
unsigned long bufsize = ISOFS_BUFFER_SIZE(inode);
unsigned long block;
int high_sierra = sbi->s_high_sierra;
struct buffer_head *bh = NULL;
struct iso_directory_record *de;
struct iso_directory_record *tmpde = NULL;
unsigned int de_len;
unsigned long offset;
struct iso_inode_info *ei = ISOFS_I(inode);
int ret = -EIO;
block = ei->i_iget5_block;
bh = sb_bread(inode->i_sb, block);
if (!bh)
goto out_badread;
offset = ei->i_iget5_offset;
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (offset + de_len > bufsize) {
int frag1 = bufsize - offset;
tmpde = kmalloc(de_len, GFP_KERNEL);
if (tmpde == NULL) {
printk(KERN_INFO "%s: out of memory\n", __func__);
ret = -ENOMEM;
goto fail;
}
memcpy(tmpde, bh->b_data + offset, frag1);
brelse(bh);
bh = sb_bread(inode->i_sb, ++block);
if (!bh)
goto out_badread;
memcpy((char *)tmpde+frag1, bh->b_data, de_len - frag1);
de = tmpde;
}
inode->i_ino = isofs_get_ino(ei->i_iget5_block,
ei->i_iget5_offset,
ISOFS_BUFFER_BITS(inode));
/* Assume it is a normal-format file unless told otherwise */
ei->i_file_format = isofs_file_normal;
if (de->flags[-high_sierra] & 2) {
if (sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
else
inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
set_nlink(inode, 1); /*
* Set to 1. We know there are 2, but
* the find utility tries to optimize
* if it is 2, and it screws up. It is
* easier to give 1 which tells find to
* do it the hard way.
*/
} else {
if (sbi->s_fmode != ISOFS_INVALID_MODE) {
inode->i_mode = S_IFREG | sbi->s_fmode;
} else {
/*
* Set default permissions: r-x for all. The disc
* could be shared with DOS machines so virtually
* anything could be a valid executable.
*/
inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO;
}
set_nlink(inode, 1);
}
inode->i_uid = sbi->s_uid;
inode->i_gid = sbi->s_gid;
inode->i_blocks = 0;
ei->i_format_parm[0] = 0;
ei->i_format_parm[1] = 0;
ei->i_format_parm[2] = 0;
ei->i_section_size = isonum_733(de->size);
if (de->flags[-high_sierra] & 0x80) {
ret = isofs_read_level3_size(inode);
if (ret < 0)
goto fail;
ret = -EIO;
} else {
ei->i_next_section_block = 0;
ei->i_next_section_offset = 0;
inode->i_size = isonum_733(de->size);
}
/*
* Some dipshit decided to store some other bit of information
* in the high byte of the file length. Truncate size in case
* this CDROM was mounted with the cruft option.
*/
if (sbi->s_cruft)
inode->i_size &= 0x00ffffff;
if (de->interleave[0]) {
printk(KERN_DEBUG "ISOFS: Interleaved files not (yet) supported.\n");
inode->i_size = 0;
}
/* I have no idea what file_unit_size is used for, so
we will flag it for now */
if (de->file_unit_size[0] != 0) {
printk(KERN_DEBUG "ISOFS: File unit size != 0 for ISO file (%ld).\n",
inode->i_ino);
}
/* I have no idea what other flag bits are used for, so
we will flag it for now */
#ifdef DEBUG
if((de->flags[-high_sierra] & ~2)!= 0){
printk(KERN_DEBUG "ISOFS: Unusual flag settings for ISO file "
"(%ld %x).\n",
inode->i_ino, de->flags[-high_sierra]);
}
#endif
inode->i_mtime.tv_sec =
inode->i_atime.tv_sec =
inode->i_ctime.tv_sec = iso_date(de->date, high_sierra);
inode->i_mtime.tv_nsec =
inode->i_atime.tv_nsec =
inode->i_ctime.tv_nsec = 0;
ei->i_first_extent = (isonum_733(de->extent) +
isonum_711(de->ext_attr_length));
/* Set the number of blocks for stat() - should be done before RR */
inode->i_blocks = (inode->i_size + 511) >> 9;
/*
* Now test for possible Rock Ridge extensions which will override
* some of these numbers in the inode structure.
*/
if (!high_sierra) {
parse_rock_ridge_inode(de, inode);
/* if we want uid/gid set, override the rock ridge setting */
if (sbi->s_uid_set)
inode->i_uid = sbi->s_uid;
if (sbi->s_gid_set)
inode->i_gid = sbi->s_gid;
}
/* Now set final access rights if overriding rock ridge setting */
if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_fmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFREG | sbi->s_fmode;
/* Install the inode operations vector */
if (S_ISREG(inode->i_mode)) {
inode->i_fop = &generic_ro_fops;
switch (ei->i_file_format) {
#ifdef CONFIG_ZISOFS
case isofs_file_compressed:
inode->i_data.a_ops = &zisofs_aops;
break;
#endif
default:
inode->i_data.a_ops = &isofs_aops;
break;
}
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &isofs_dir_inode_operations;
inode->i_fop = &isofs_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
inode->i_op = &page_symlink_inode_operations;
inode->i_data.a_ops = &isofs_symlink_aops;
} else
/* XXX - parse_rock_ridge_inode() had already set i_rdev. */
init_special_inode(inode, inode->i_mode, inode->i_rdev);
ret = 0;
out:
kfree(tmpde);
if (bh)
brelse(bh);
return ret;
out_badread:
printk(KERN_WARNING "ISOFS: unable to read i-node block\n");
fail:
goto out;
}
Commit Message: isofs: Fix unbounded recursion when processing relocated directories
We did not check relocated directory in any way when processing Rock
Ridge 'CL' tag. Thus a corrupted isofs image can possibly have a CL
entry pointing to another CL entry leading to possibly unbounded
recursion in kernel code and thus stack overflow or deadlocks (if there
is a loop created from CL entries).
Fix the problem by not allowing CL entry to point to a directory entry
with CL entry (such use makes no good sense anyway) and by checking
whether CL entry doesn't point to itself.
CC: [email protected]
Reported-by: Chris Evans <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-20 | static int isofs_read_inode(struct inode *inode)
static int isofs_read_inode(struct inode *inode, int relocated)
{
struct super_block *sb = inode->i_sb;
struct isofs_sb_info *sbi = ISOFS_SB(sb);
unsigned long bufsize = ISOFS_BUFFER_SIZE(inode);
unsigned long block;
int high_sierra = sbi->s_high_sierra;
struct buffer_head *bh = NULL;
struct iso_directory_record *de;
struct iso_directory_record *tmpde = NULL;
unsigned int de_len;
unsigned long offset;
struct iso_inode_info *ei = ISOFS_I(inode);
int ret = -EIO;
block = ei->i_iget5_block;
bh = sb_bread(inode->i_sb, block);
if (!bh)
goto out_badread;
offset = ei->i_iget5_offset;
de = (struct iso_directory_record *) (bh->b_data + offset);
de_len = *(unsigned char *) de;
if (offset + de_len > bufsize) {
int frag1 = bufsize - offset;
tmpde = kmalloc(de_len, GFP_KERNEL);
if (tmpde == NULL) {
printk(KERN_INFO "%s: out of memory\n", __func__);
ret = -ENOMEM;
goto fail;
}
memcpy(tmpde, bh->b_data + offset, frag1);
brelse(bh);
bh = sb_bread(inode->i_sb, ++block);
if (!bh)
goto out_badread;
memcpy((char *)tmpde+frag1, bh->b_data, de_len - frag1);
de = tmpde;
}
inode->i_ino = isofs_get_ino(ei->i_iget5_block,
ei->i_iget5_offset,
ISOFS_BUFFER_BITS(inode));
/* Assume it is a normal-format file unless told otherwise */
ei->i_file_format = isofs_file_normal;
if (de->flags[-high_sierra] & 2) {
if (sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
else
inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO;
set_nlink(inode, 1); /*
* Set to 1. We know there are 2, but
* the find utility tries to optimize
* if it is 2, and it screws up. It is
* easier to give 1 which tells find to
* do it the hard way.
*/
} else {
if (sbi->s_fmode != ISOFS_INVALID_MODE) {
inode->i_mode = S_IFREG | sbi->s_fmode;
} else {
/*
* Set default permissions: r-x for all. The disc
* could be shared with DOS machines so virtually
* anything could be a valid executable.
*/
inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO;
}
set_nlink(inode, 1);
}
inode->i_uid = sbi->s_uid;
inode->i_gid = sbi->s_gid;
inode->i_blocks = 0;
ei->i_format_parm[0] = 0;
ei->i_format_parm[1] = 0;
ei->i_format_parm[2] = 0;
ei->i_section_size = isonum_733(de->size);
if (de->flags[-high_sierra] & 0x80) {
ret = isofs_read_level3_size(inode);
if (ret < 0)
goto fail;
ret = -EIO;
} else {
ei->i_next_section_block = 0;
ei->i_next_section_offset = 0;
inode->i_size = isonum_733(de->size);
}
/*
* Some dipshit decided to store some other bit of information
* in the high byte of the file length. Truncate size in case
* this CDROM was mounted with the cruft option.
*/
if (sbi->s_cruft)
inode->i_size &= 0x00ffffff;
if (de->interleave[0]) {
printk(KERN_DEBUG "ISOFS: Interleaved files not (yet) supported.\n");
inode->i_size = 0;
}
/* I have no idea what file_unit_size is used for, so
we will flag it for now */
if (de->file_unit_size[0] != 0) {
printk(KERN_DEBUG "ISOFS: File unit size != 0 for ISO file (%ld).\n",
inode->i_ino);
}
/* I have no idea what other flag bits are used for, so
we will flag it for now */
#ifdef DEBUG
if((de->flags[-high_sierra] & ~2)!= 0){
printk(KERN_DEBUG "ISOFS: Unusual flag settings for ISO file "
"(%ld %x).\n",
inode->i_ino, de->flags[-high_sierra]);
}
#endif
inode->i_mtime.tv_sec =
inode->i_atime.tv_sec =
inode->i_ctime.tv_sec = iso_date(de->date, high_sierra);
inode->i_mtime.tv_nsec =
inode->i_atime.tv_nsec =
inode->i_ctime.tv_nsec = 0;
ei->i_first_extent = (isonum_733(de->extent) +
isonum_711(de->ext_attr_length));
/* Set the number of blocks for stat() - should be done before RR */
inode->i_blocks = (inode->i_size + 511) >> 9;
/*
* Now test for possible Rock Ridge extensions which will override
* some of these numbers in the inode structure.
*/
if (!high_sierra) {
parse_rock_ridge_inode(de, inode, relocated);
/* if we want uid/gid set, override the rock ridge setting */
if (sbi->s_uid_set)
inode->i_uid = sbi->s_uid;
if (sbi->s_gid_set)
inode->i_gid = sbi->s_gid;
}
/* Now set final access rights if overriding rock ridge setting */
if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_dmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFDIR | sbi->s_dmode;
if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm &&
sbi->s_fmode != ISOFS_INVALID_MODE)
inode->i_mode = S_IFREG | sbi->s_fmode;
/* Install the inode operations vector */
if (S_ISREG(inode->i_mode)) {
inode->i_fop = &generic_ro_fops;
switch (ei->i_file_format) {
#ifdef CONFIG_ZISOFS
case isofs_file_compressed:
inode->i_data.a_ops = &zisofs_aops;
break;
#endif
default:
inode->i_data.a_ops = &isofs_aops;
break;
}
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &isofs_dir_inode_operations;
inode->i_fop = &isofs_dir_operations;
} else if (S_ISLNK(inode->i_mode)) {
inode->i_op = &page_symlink_inode_operations;
inode->i_data.a_ops = &isofs_symlink_aops;
} else
/* XXX - parse_rock_ridge_inode() had already set i_rdev. */
init_special_inode(inode, inode->i_mode, inode->i_rdev);
ret = 0;
out:
kfree(tmpde);
if (bh)
brelse(bh);
return ret;
out_badread:
printk(KERN_WARNING "ISOFS: unable to read i-node block\n");
fail:
goto out;
}
| 166,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: static void destroy_server_connect(SERVER_CONNECT_REC *conn)
{
IRC_SERVER_CONNECT_REC *ircconn;
ircconn = IRC_SERVER_CONNECT(conn);
if (ircconn == NULL)
return;
g_free_not_null(ircconn->usermode);
g_free_not_null(ircconn->alternate_nick);
}
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values
CWE ID: CWE-416 | static void destroy_server_connect(SERVER_CONNECT_REC *conn)
{
IRC_SERVER_CONNECT_REC *ircconn;
ircconn = IRC_SERVER_CONNECT(conn);
if (ircconn == NULL)
return;
g_free_not_null(ircconn->usermode);
g_free_not_null(ircconn->alternate_nick);
g_free_not_null(ircconn->sasl_username);
g_free_not_null(ircconn->sasl_password);
}
| 169,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id)
{
struct k_itimer *timr;
int overrun;
unsigned long flags;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
overrun = timr->it_overrun_last;
unlock_timer(timr, flags);
return overrun;
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Acked-by: John Stultz <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190 | SYSCALL_DEFINE1(timer_getoverrun, timer_t, timer_id)
{
struct k_itimer *timr;
int overrun;
unsigned long flags;
timr = lock_timer(timer_id, &flags);
if (!timr)
return -EINVAL;
overrun = timer_overrun_to_int(timr, 0);
unlock_timer(timr, flags);
return overrun;
}
| 169,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
Commit Message: CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes.
Probably a copy-and-pasteo.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
| 167,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: COMPAT_SYSCALL_DEFINE5(waitid,
int, which, compat_pid_t, pid,
struct compat_siginfo __user *, infop, int, options,
struct compat_rusage __user *, uru)
{
struct rusage ru;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err && uru) {
/* kernel_waitid() overwrites everything in ru */
if (COMPAT_USE_64BIT_TIME)
err = copy_to_user(uru, &ru, sizeof(ru));
else
err = put_compat_rusage(&ru, uru);
if (err)
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user(info.cause, &infop->si_code, Efault);
unsafe_put_user(info.pid, &infop->si_pid, Efault);
unsafe_put_user(info.uid, &infop->si_uid, Efault);
unsafe_put_user(info.status, &infop->si_status, Efault);
user_access_end();
return err;
Efault:
user_access_end();
return -EFAULT;
}
Commit Message: fix infoleak in waitid(2)
kernel_waitid() can return a PID, an error or 0. rusage is filled in the first
case and waitid(2) rusage should've been copied out exactly in that case, *not*
whenever kernel_waitid() has not returned an error. Compat variant shares that
braino; none of kernel_wait4() callers do, so the below ought to fix it.
Reported-and-tested-by: Alexander Potapenko <[email protected]>
Fixes: ce72a16fa705 ("wait4(2)/waitid(2): separate copying rusage to userland")
Cc: [email protected] # v4.13
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-200 | COMPAT_SYSCALL_DEFINE5(waitid,
int, which, compat_pid_t, pid,
struct compat_siginfo __user *, infop, int, options,
struct compat_rusage __user *, uru)
{
struct rusage ru;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
if (uru) {
/* kernel_waitid() overwrites everything in ru */
if (COMPAT_USE_64BIT_TIME)
err = copy_to_user(uru, &ru, sizeof(ru));
else
err = put_compat_rusage(&ru, uru);
if (err)
return -EFAULT;
}
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user(info.cause, &infop->si_code, Efault);
unsafe_put_user(info.pid, &infop->si_pid, Efault);
unsafe_put_user(info.uid, &infop->si_uid, Efault);
unsafe_put_user(info.status, &infop->si_status, Efault);
user_access_end();
return err;
Efault:
user_access_end();
return -EFAULT;
}
| 167,742 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
params->scale_factor = settings.scale_factor();
params->rasterize_pdf = settings.rasterize_pdf();
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->display_header_footer = settings.display_header_footer();
params->title = settings.title();
params->url = settings.url();
params->printed_doc_type = SkiaDocumentType::PDF;
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | void RenderParamsFromPrintSettings(const PrintSettings& settings,
PrintMsg_Print_Params* params) {
params->page_size = settings.page_setup_device_units().physical_size();
params->content_size.SetSize(
settings.page_setup_device_units().content_area().width(),
settings.page_setup_device_units().content_area().height());
params->printable_area.SetRect(
settings.page_setup_device_units().printable_area().x(),
settings.page_setup_device_units().printable_area().y(),
settings.page_setup_device_units().printable_area().width(),
settings.page_setup_device_units().printable_area().height());
params->margin_top = settings.page_setup_device_units().content_area().y();
params->margin_left = settings.page_setup_device_units().content_area().x();
params->dpi = settings.dpi();
params->scale_factor = settings.scale_factor();
params->rasterize_pdf = settings.rasterize_pdf();
params->document_cookie = 0;
params->selection_only = settings.selection_only();
params->supports_alpha_blend = settings.supports_alpha_blend();
params->should_print_backgrounds = settings.should_print_backgrounds();
params->display_header_footer = settings.display_header_footer();
params->title = settings.title();
params->url = settings.url();
params->printed_doc_type =
IsOopifEnabled() ? SkiaDocumentType::MSKP : SkiaDocumentType::PDF;
}
| 171,895 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) {
RConfigNode *node = NULL;
char *ov = NULL;
ut64 oi;
if (!cfg || STRNULL (name)) {
return NULL;
}
node = r_config_node_get (cfg, name);
if (node) {
if (node->flags & CN_RO) {
eprintf ("(error: '%s' config key is read only)\n", name);
return node;
}
oi = node->i_value;
if (node->value) {
ov = strdup (node->value);
if (!ov) {
goto beach;
}
} else {
free (node->value);
node->value = strdup ("");
}
if (node->flags & CN_BOOL) {
bool b = is_true (value);
node->i_value = (ut64) b? 1: 0;
char *value = strdup (r_str_bool (b));
if (value) {
free (node->value);
node->value = value;
}
} else {
if (!value) {
free (node->value);
node->value = strdup ("");
node->i_value = 0;
} else {
if (node->value == value) {
goto beach;
}
free (node->value);
node->value = strdup (value);
if (IS_DIGIT (*value)) {
if (strchr (value, '/')) {
node->i_value = r_num_get (cfg->num, value);
} else {
node->i_value = r_num_math (cfg->num, value);
}
} else {
node->i_value = 0;
}
node->flags |= CN_INT;
}
}
} else { // Create a new RConfigNode
oi = UT64_MAX;
if (!cfg->lock) {
node = r_config_node_new (name, value);
if (node) {
if (value && is_bool (value)) {
node->flags |= CN_BOOL;
node->i_value = is_true (value)? 1: 0;
}
if (cfg->ht) {
ht_insert (cfg->ht, node->name, node);
r_list_append (cfg->nodes, node);
cfg->n_nodes++;
}
} else {
eprintf ("r_config_set: unable to create a new RConfigNode\n");
}
} else {
eprintf ("r_config_set: variable '%s' not found\n", name);
}
}
if (node && node->setter) {
int ret = node->setter (cfg->user, node);
if (ret == false) {
if (oi != UT64_MAX) {
node->i_value = oi;
}
free (node->value);
node->value = strdup (ov? ov: "");
}
}
beach:
free (ov);
return node;
}
Commit Message: Fix #7698 - UAF in r_config_set when loading a dex
CWE ID: CWE-416 | R_API RConfigNode* r_config_set(RConfig *cfg, const char *name, const char *value) {
RConfigNode *node = NULL;
char *ov = NULL;
ut64 oi;
if (!cfg || STRNULL (name)) {
return NULL;
}
node = r_config_node_get (cfg, name);
if (node) {
if (node->flags & CN_RO) {
eprintf ("(error: '%s' config key is read only)\n", name);
return node;
}
oi = node->i_value;
if (node->value) {
ov = strdup (node->value);
if (!ov) {
goto beach;
}
} else {
free (node->value);
node->value = strdup ("");
}
if (node->flags & CN_BOOL) {
bool b = is_true (value);
node->i_value = (ut64) b? 1: 0;
char *value = strdup (r_str_bool (b));
if (value) {
free (node->value);
node->value = value;
}
} else {
if (!value) {
free (node->value);
node->value = strdup ("");
node->i_value = 0;
} else {
if (node->value == value) {
goto beach;
}
char *tmp = node->value;
node->value = strdup (value);
free (tmp);
if (IS_DIGIT (*value)) {
if (strchr (value, '/')) {
node->i_value = r_num_get (cfg->num, value);
} else {
node->i_value = r_num_math (cfg->num, value);
}
} else {
node->i_value = 0;
}
node->flags |= CN_INT;
}
}
} else { // Create a new RConfigNode
oi = UT64_MAX;
if (!cfg->lock) {
node = r_config_node_new (name, value);
if (node) {
if (value && is_bool (value)) {
node->flags |= CN_BOOL;
node->i_value = is_true (value)? 1: 0;
}
if (cfg->ht) {
ht_insert (cfg->ht, node->name, node);
r_list_append (cfg->nodes, node);
cfg->n_nodes++;
}
} else {
eprintf ("r_config_set: unable to create a new RConfigNode\n");
}
} else {
eprintf ("r_config_set: variable '%s' not found\n", name);
}
}
if (node && node->setter) {
int ret = node->setter (cfg->user, node);
if (ret == false) {
if (oi != UT64_MAX) {
node->i_value = oi;
}
free (node->value);
node->value = strdup (ov? ov: "");
}
}
beach:
free (ov);
return node;
}
| 168,095 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476 | static int jp2_pclr_getdata(jp2_box_t *box, jas_stream_t *in)
{
jp2_pclr_t *pclr = &box->data.pclr;
int lutsize;
unsigned int i;
unsigned int j;
int_fast32_t x;
pclr->lutdata = 0;
pclr->bpc = 0;
if (jp2_getuint16(in, &pclr->numlutents) ||
jp2_getuint8(in, &pclr->numchans)) {
return -1;
}
lutsize = pclr->numlutents * pclr->numchans;
if (!(pclr->lutdata = jas_alloc2(lutsize, sizeof(int_fast32_t)))) {
return -1;
}
if (!(pclr->bpc = jas_alloc2(pclr->numchans, sizeof(uint_fast8_t)))) {
return -1;
}
for (i = 0; i < pclr->numchans; ++i) {
if (jp2_getuint8(in, &pclr->bpc[i])) {
return -1;
}
}
for (i = 0; i < pclr->numlutents; ++i) {
for (j = 0; j < pclr->numchans; ++j) {
if (jp2_getint(in, (pclr->bpc[j] & 0x80) != 0,
(pclr->bpc[j] & 0x7f) + 1, &x)) {
return -1;
}
pclr->lutdata[i * pclr->numchans + j] = x;
}
}
return 0;
}
| 168,323 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
static char temp[NFSX_V3FHMAX+1];
/* Make sure string is null-terminated */
strncpy(temp, sfsname, NFSX_V3FHMAX);
temp[sizeof(temp) - 1] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
Commit Message: CVE-2017-13001/NFS: Don't copy more data than is in the file handle.
Also, put the buffer on the stack; no reason to make it static. (65
bytes isn't a lot.)
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | nfs_printfh(netdissect_options *ndo,
register const uint32_t *dp, const u_int len)
{
my_fsid fsid;
uint32_t ino;
const char *sfsname = NULL;
char *spacep;
if (ndo->ndo_uflag) {
u_int i;
char const *sep = "";
ND_PRINT((ndo, " fh["));
for (i=0; i<len; i++) {
ND_PRINT((ndo, "%s%x", sep, dp[i]));
sep = ":";
}
ND_PRINT((ndo, "]"));
return;
}
Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0);
if (sfsname) {
/* file system ID is ASCII, not numeric, for this server OS */
char temp[NFSX_V3FHMAX+1];
u_int stringlen;
/* Make sure string is null-terminated */
stringlen = len;
if (stringlen > NFSX_V3FHMAX)
stringlen = NFSX_V3FHMAX;
strncpy(temp, sfsname, stringlen);
temp[stringlen] = '\0';
/* Remove trailing spaces */
spacep = strchr(temp, ' ');
if (spacep)
*spacep = '\0';
ND_PRINT((ndo, " fh %s/", temp));
} else {
ND_PRINT((ndo, " fh %d,%d/",
fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor));
}
if(fsid.Fsid_dev.Minor == 257)
/* Print the undecoded handle */
ND_PRINT((ndo, "%s", fsid.Opaque_Handle));
else
ND_PRINT((ndo, "%ld", (long) ino));
}
| 167,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) {
if (!GetTabEntry(contents->web_contents())) {
return;
}
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(
ExtensionTabUtil::GetTabId(contents->web_contents())));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(contents->web_contents())));
object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue(
index));
args->Append(object_args);
DispatchEvent(contents->profile(), events::kOnTabDetached, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserEventRouter::TabDetachedAt(TabContents* contents, int index) {
void BrowserEventRouter::TabDetachedAt(WebContents* contents, int index) {
if (!GetTabEntry(contents)) {
return;
}
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(ExtensionTabUtil::GetTabId(contents)));
DictionaryValue* object_args = new DictionaryValue();
object_args->Set(tab_keys::kOldWindowIdKey, Value::CreateIntegerValue(
ExtensionTabUtil::GetWindowIdOfTab(contents)));
object_args->Set(tab_keys::kOldPositionKey, Value::CreateIntegerValue(
index));
args->Append(object_args);
Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
DispatchEvent(profile, events::kOnTabDetached, args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
}
| 171,505 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return error;
else {
if (error == 0)
acl = NULL;
}
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285 | __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode,
int type, struct posix_acl *acl)
{
char *name;
void *value = NULL;
size_t size = 0;
int error;
switch (type) {
case ACL_TYPE_ACCESS:
name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
error = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (error)
return error;
}
break;
case ACL_TYPE_DEFAULT:
name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
value = reiserfs_posix_acl_to_disk(acl, &size);
if (IS_ERR(value))
return (int)PTR_ERR(value);
}
error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0);
/*
* Ensure that the inode gets dirtied if we're only using
* the mode bits and an old ACL didn't exist. We don't need
* to check if the inode is hashed here since we won't get
* called by reiserfs_inherit_default_acl().
*/
if (error == -ENODATA) {
error = 0;
if (type == ACL_TYPE_ACCESS) {
inode->i_ctime = CURRENT_TIME_SEC;
mark_inode_dirty(inode);
}
}
kfree(value);
if (!error)
set_cached_acl(inode, type, acl);
return error;
}
| 166,978 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
struct address_space *mapping = inode->i_mapping;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + len - 1);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Now release the pages and zero block aligned part of pages*/
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have
* released from page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
/* Now release the pages and zero block aligned part of pages */
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
up_write(&EXT4_I(inode)->i_mmap_sem);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
| 167,485 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
Commit Message:
CWE ID: | static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param && param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
| 164,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void m_stop(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
vma_stop(priv, vma);
if (priv->task)
put_task_struct(priv->task);
}
Commit Message: proc: fix oops on invalid /proc/<pid>/maps access
When m_start returns an error, the seq_file logic will still call m_stop
with that error entry, so we'd better make sure that we check it before
using it as a vma.
Introduced by commit ec6fd8a4355c ("report errors in /proc/*/*map*
sanely"), which replaced NULL with various ERR_PTR() cases.
(On ia64, you happen to get a unaligned fault instead of a page fault,
since the address used is generally some random error code like -EPERM)
Reported-by: Anca Emanuel <[email protected]>
Reported-by: Tony Luck <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Américo Wang <[email protected]>
Cc: Stephen Wilson <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20 | static void m_stop(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
if (!IS_ERR(vma))
vma_stop(priv, vma);
if (priv->task)
put_task_struct(priv->task);
}
| 165,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: long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const {
const long status = GetFirst(pResult);
if (status < 0) // buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi) {
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS()) // found a keyframe
return 0;
while (lo != i) {
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
#if 0
pResult = pCluster->GetMaxKey(this);
#else
pResult = pCluster->GetEntry(this, time_ns);
#endif
if ((pResult != 0) && !pResult->EOS())
return 0;
}
pResult = GetEOS();
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const {
const long status = GetFirst(pResult);
if (status < 0) // buffer underflow, etc
return status;
assert(pResult);
if (pResult->EOS())
return 0;
const Cluster* pCluster = pResult->GetCluster();
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
if (time_ns <= pResult->GetBlock()->GetTime(pCluster))
return 0;
Cluster** const clusters = m_pSegment->m_clusters;
assert(clusters);
const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded
assert(count > 0);
Cluster** const i = clusters + pCluster->GetIndex();
assert(i);
assert(*i == pCluster);
assert(pCluster->GetTime() <= time_ns);
Cluster** const j = clusters + count;
Cluster** lo = i;
Cluster** hi = j;
while (lo < hi) {
Cluster** const mid = lo + (hi - lo) / 2;
assert(mid < hi);
pCluster = *mid;
assert(pCluster);
assert(pCluster->GetIndex() >= 0);
assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters));
const long long t = pCluster->GetTime();
if (t <= time_ns)
lo = mid + 1;
else
hi = mid;
assert(lo <= hi);
}
assert(lo == hi);
assert(lo > i);
assert(lo <= j);
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS()) // found a keyframe
return 0;
while (lo != i) {
pCluster = *--lo;
assert(pCluster);
assert(pCluster->GetTime() <= time_ns);
pResult = pCluster->GetEntry(this, time_ns);
if ((pResult != 0) && !pResult->EOS())
return 0;
}
pResult = GetEOS();
return 0;
}
| 173,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this,
image_transform_png_set_palette_to_rgb_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
this->next->mod(this->next, that, pp, display);
}
| 173,639 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_context_time(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
OM_uint32 *time_rec)
{
OM_uint32 ret;
ret = gss_context_time(minor_status,
context_handle,
time_rec);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_context_time(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
OM_uint32 *time_rec)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_context_time(minor_status,
sc->ctx_handle,
time_rec);
return (ret);
}
| 166,653 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
{
/*-
* (0) check whether the desired fragment is available
* if so:
* (1) copy over the fragment to s->init_buf->data[]
* (2) update s->init_num
*/
pitem *item;
hm_fragment *frag;
int al;
*ok = 0;
item = pqueue_peek(s->d1->buffered_messages);
if (item == NULL)
return 0;
frag = (hm_fragment *)item->data;
/* Don't return if reassembly still in progress */
if (frag->reassembly != NULL)
frag->msg_header.frag_len);
}
Commit Message:
CWE ID: CWE-399 | static int dtls1_retrieve_buffered_fragment(SSL *s, int *ok)
{
/*-
* (0) check whether the desired fragment is available
* if so:
* (1) copy over the fragment to s->init_buf->data[]
* (2) update s->init_num
*/
pitem *item;
hm_fragment *frag;
int al;
*ok = 0;
do {
item = pqueue_peek(s->d1->buffered_messages);
if (item == NULL)
return 0;
frag = (hm_fragment *)item->data;
if (frag->msg_header.seq < s->d1->handshake_read_seq) {
/* This is a stale message that has been buffered so clear it */
pqueue_pop(s->d1->buffered_messages);
dtls1_hm_fragment_free(frag);
pitem_free(item);
item = NULL;
frag = NULL;
}
} while (item == NULL);
/* Don't return if reassembly still in progress */
if (frag->reassembly != NULL)
frag->msg_header.frag_len);
}
| 165,197 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShellWindowFrameView::ButtonPressed(views::Button* sender,
const views::Event& event) {
if (sender == close_button_)
frame_->Close();
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | void ShellWindowFrameView::ButtonPressed(views::Button* sender,
const views::Event& event) {
DCHECK(!is_frameless_);
if (sender == close_button_)
frame_->Close();
}
| 170,709 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long Block::GetDiscardPadding() const
{
return m_discard_padding;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long Block::GetDiscardPadding() const
| 174,303 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
int i, j;
int w, h;
int leftbyte, rightbyte;
int shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = (x + w < dst->width) ? w : dst->width - x;
h = (y + h < dst->height) ? h : dst->height - y;
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = x >> 3;
rightbyte = (x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
Commit Message:
CWE ID: CWE-119 | jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t i, j;
uint32_t w, h;
uint32_t leftbyte, rightbyte;
uint32_t shift;
uint8_t *s, *ss;
uint8_t *d, *dd;
uint8_t mask, rightmask;
if (op != JBIG2_COMPOSE_OR) {
/* hand off the the general routine */
return jbig2_image_compose_unopt(ctx, dst, src, x, y, op);
}
/* clip */
w = src->width;
h = src->height;
ss = src->data;
if (x < 0) {
w += x;
x = 0;
}
if (y < 0) {
h += y;
y = 0;
}
w = ((uint32_t)x + w < dst->width) ? w : ((dst->width >= (uint32_t)x) ? dst->width - (uint32_t)x : 0);
h = ((uint32_t)y + h < dst->height) ? h : ((dst->height >= (uint32_t)y) ? dst->height - (uint32_t)y : 0);
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping\n", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
#if 0
/* special case complete/strip replacement */
/* disabled because it's only safe to do when the destination
buffer is all-blank. */
if ((x == 0) && (w == src->width)) {
memcpy(dst->data + y * dst->stride, src->data, h * src->stride);
return 0;
}
#endif
leftbyte = (uint32_t)x >> 3;
rightbyte = ((uint32_t)x + w - 1) >> 3;
shift = x & 7;
/* general OR case */
s = ss;
d = dd = dst->data + y * dst->stride + leftbyte;
if (d < dst->data || leftbyte > dst->stride || h * dst->stride < 0 || d - leftbyte + h * dst->stride > dst->data + dst->height * dst->stride) {
return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "preventing heap overflow in jbig2_image_compose");
}
if (leftbyte == rightbyte) {
mask = 0x100 - (0x100 >> w);
for (j = 0; j < h; j++) {
*d |= (*s & mask) >> shift;
d += dst->stride;
s += src->stride;
}
} else if (shift == 0) {
rightmask = (w & 7) ? 0x100 - (1 << (8 - (w & 7))) : 0xFF;
for (j = 0; j < h; j++) {
for (i = leftbyte; i < rightbyte; i++)
*d++ |= *s++;
*d |= *s & rightmask;
d = (dd += dst->stride);
s = (ss += src->stride);
}
} else {
bool overlap = (((w + 7) >> 3) < ((x + w + 7) >> 3) - (x >> 3));
mask = 0x100 - (1 << shift);
if (overlap)
rightmask = (0x100 - (0x100 >> ((x + w) & 7))) >> (8 - shift);
else
rightmask = 0x100 - (0x100 >> (w & 7));
for (j = 0; j < h; j++) {
*d++ |= (*s & mask) >> shift;
for (i = leftbyte; i < rightbyte - 1; i++) {
*d |= ((*s++ & ~mask) << (8 - shift));
*d++ |= ((*s & mask) >> shift);
}
if (overlap)
*d |= (*s & rightmask) << (8 - shift);
else
*d |= ((s[0] & ~mask) << (8 - shift)) | ((s[1] & rightmask) >> shift);
d = (dd += dst->stride);
s = (ss += src->stride);
}
}
return 0;
}
| 165,489 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringCase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringCase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringCase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringCase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringCase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringCase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | AriaCurrentState AXNodeObject::ariaCurrentState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent);
if (attributeValue.isNull())
return AriaCurrentStateUndefined;
if (attributeValue.isEmpty() ||
equalIgnoringASCIICase(attributeValue, "false"))
return AriaCurrentStateFalse;
if (equalIgnoringASCIICase(attributeValue, "true"))
return AriaCurrentStateTrue;
if (equalIgnoringASCIICase(attributeValue, "page"))
return AriaCurrentStatePage;
if (equalIgnoringASCIICase(attributeValue, "step"))
return AriaCurrentStateStep;
if (equalIgnoringASCIICase(attributeValue, "location"))
return AriaCurrentStateLocation;
if (equalIgnoringASCIICase(attributeValue, "date"))
return AriaCurrentStateDate;
if (equalIgnoringASCIICase(attributeValue, "time"))
return AriaCurrentStateTime;
if (!attributeValue.isEmpty())
return AriaCurrentStateTrue;
return AXObject::ariaCurrentState();
}
| 171,908 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintWebViewHelper::OnPrintingDone(bool success) {
notify_browser_of_print_failure_ = false;
if (!success)
LOG(ERROR) << "Failure in OnPrintingDone";
DidFinishPrinting(success ? OK : FAIL_PRINT);
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID: | void PrintWebViewHelper::OnPrintingDone(bool success) {
CHECK_LE(ipc_nesting_level_, 1);
notify_browser_of_print_failure_ = false;
if (!success)
LOG(ERROR) << "Failure in OnPrintingDone";
DidFinishPrinting(success ? OK : FAIL_PRINT);
}
| 171,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode) {
SplashBitmap *scaledMask;
SplashClipResult clipRes, clipRes2;
SplashPipe pipe;
int scaledWidth, scaledHeight, t0, t1;
SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
SplashCoord vx[4], vy[4];
int xMin, yMin, xMax, yMax;
ImageSection section[3];
int nSections;
int y, xa, xb, x, i, xx, yy;
vx[0] = mat[4]; vy[0] = mat[5];
vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5];
vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5];
vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5];
xMin = imgCoordMungeLowerC(vx[0], glyphMode);
xMax = imgCoordMungeUpperC(vx[0], glyphMode);
yMin = imgCoordMungeLowerC(vy[0], glyphMode);
yMax = imgCoordMungeUpperC(vy[0], glyphMode);
for (i = 1; i < 4; ++i) {
t0 = imgCoordMungeLowerC(vx[i], glyphMode);
if (t0 < xMin) {
xMin = t0;
}
t0 = imgCoordMungeUpperC(vx[i], glyphMode);
if (t0 > xMax) {
xMax = t0;
}
t1 = imgCoordMungeLowerC(vy[i], glyphMode);
if (t1 < yMin) {
yMin = t1;
}
t1 = imgCoordMungeUpperC(vy[i], glyphMode);
if (t1 > yMax) {
yMax = t1;
}
}
clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
opClipRes = clipRes;
if (clipRes == splashClipAllOutside) {
return;
}
if (mat[0] >= 0) {
t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
}
if (mat[1] >= 0) {
t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
}
scaledWidth = t0 > t1 ? t0 : t1;
if (mat[2] >= 0) {
t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
}
if (mat[3] >= 0) {
t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
}
scaledHeight = t0 > t1 ? t0 : t1;
if (scaledWidth == 0) {
scaledWidth = 1;
}
if (scaledHeight == 0) {
scaledHeight = 1;
}
r00 = mat[0] / scaledWidth;
r01 = mat[1] / scaledWidth;
r10 = mat[2] / scaledHeight;
r11 = mat[3] / scaledHeight;
det = r00 * r11 - r01 * r10;
if (splashAbs(det) < 1e-6) {
return;
}
ir00 = r11 / det;
ir01 = -r01 / det;
ir10 = -r10 / det;
ir11 = r00 / det;
scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
scaledWidth, scaledHeight);
i = (vy[2] <= vy[3]) ? 2 : 3;
}
Commit Message:
CWE ID: | void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData,
int srcWidth, int srcHeight,
SplashCoord *mat, GBool glyphMode) {
SplashBitmap *scaledMask;
SplashClipResult clipRes, clipRes2;
SplashPipe pipe;
int scaledWidth, scaledHeight, t0, t1;
SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11;
SplashCoord vx[4], vy[4];
int xMin, yMin, xMax, yMax;
ImageSection section[3];
int nSections;
int y, xa, xb, x, i, xx, yy;
vx[0] = mat[4]; vy[0] = mat[5];
vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5];
vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5];
vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5];
xMin = imgCoordMungeLowerC(vx[0], glyphMode);
xMax = imgCoordMungeUpperC(vx[0], glyphMode);
yMin = imgCoordMungeLowerC(vy[0], glyphMode);
yMax = imgCoordMungeUpperC(vy[0], glyphMode);
for (i = 1; i < 4; ++i) {
t0 = imgCoordMungeLowerC(vx[i], glyphMode);
if (t0 < xMin) {
xMin = t0;
}
t0 = imgCoordMungeUpperC(vx[i], glyphMode);
if (t0 > xMax) {
xMax = t0;
}
t1 = imgCoordMungeLowerC(vy[i], glyphMode);
if (t1 < yMin) {
yMin = t1;
}
t1 = imgCoordMungeUpperC(vy[i], glyphMode);
if (t1 > yMax) {
yMax = t1;
}
}
clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1);
opClipRes = clipRes;
if (clipRes == splashClipAllOutside) {
return;
}
if (mat[0] >= 0) {
t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[0] + mat[4], glyphMode);
}
if (mat[1] >= 0) {
t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[1] + mat[5], glyphMode);
}
scaledWidth = t0 > t1 ? t0 : t1;
if (mat[2] >= 0) {
t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) -
imgCoordMungeLowerC(mat[4], glyphMode);
} else {
t0 = imgCoordMungeUpperC(mat[4], glyphMode) -
imgCoordMungeLowerC(mat[2] + mat[4], glyphMode);
}
if (mat[3] >= 0) {
t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) -
imgCoordMungeLowerC(mat[5], glyphMode);
} else {
t1 = imgCoordMungeUpperC(mat[5], glyphMode) -
imgCoordMungeLowerC(mat[3] + mat[5], glyphMode);
}
scaledHeight = t0 > t1 ? t0 : t1;
if (scaledWidth == 0) {
scaledWidth = 1;
}
if (scaledHeight == 0) {
scaledHeight = 1;
}
r00 = mat[0] / scaledWidth;
r01 = mat[1] / scaledWidth;
r10 = mat[2] / scaledHeight;
r11 = mat[3] / scaledHeight;
det = r00 * r11 - r01 * r10;
if (splashAbs(det) < 1e-6) {
return;
}
ir00 = r11 / det;
ir01 = -r01 / det;
ir10 = -r10 / det;
ir11 = r00 / det;
scaledMask = scaleMask(src, srcData, srcWidth, srcHeight,
scaledWidth, scaledHeight);
if (scaledMask->data == NULL) {
error(errInternal, -1, "scaledMask->data is NULL in Splash::scaleMaskYuXu");
delete scaledMask;
return;
}
i = (vy[2] <= vy[3]) ? 2 : 3;
}
| 164,733 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContextualSearchParams()
: version(-1),
start(base::string16::npos),
end(base::string16::npos),
now_on_tap_version(0) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | ContextualSearchParams()
: version(-1),
start(base::string16::npos),
end(base::string16::npos),
| 171,645 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) {
if (p_buf->len == 0)
return SENT_ALL;
ssize_t sent = send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT);
if (sent == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
return SENT_NONE;
LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno));
return SENT_FAILED;
}
if (sent == 0)
return SENT_FAILED;
if (sent == p_buf->len)
return SENT_ALL;
p_buf->offset += sent;
p_buf->len -= sent;
return SENT_PARTIAL;
}
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 sent_status_t send_data_to_app(int fd, BT_HDR *p_buf) {
if (p_buf->len == 0)
return SENT_ALL;
ssize_t sent = TEMP_FAILURE_RETRY(send(fd, p_buf->data + p_buf->offset, p_buf->len, MSG_DONTWAIT));
if (sent == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
return SENT_NONE;
LOG_ERROR("%s error writing RFCOMM data back to app: %s", __func__, strerror(errno));
return SENT_FAILED;
}
if (sent == 0)
return SENT_FAILED;
if (sent == p_buf->len)
return SENT_ALL;
p_buf->offset += sent;
p_buf->len -= sent;
return SENT_PARTIAL;
}
| 173,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
const char *userp,
const char *passwdp,
char **outptr, size_t *outlen)
{
CURLcode result;
char *plainauth;
size_t ulen;
size_t plen;
size_t plainlen;
*outlen = 0;
*outptr = NULL;
ulen = strlen(userp);
plen = strlen(passwdp);
/* Compute binary message length. Check for overflows. */
if((ulen > SIZE_T_MAX/2) || (plen > (SIZE_T_MAX/2 - 2)))
return CURLE_OUT_OF_MEMORY;
plainlen = 2 * ulen + plen + 2;
plainauth = malloc(plainlen);
if(!plainauth)
return CURLE_OUT_OF_MEMORY;
/* Calculate the reply */
memcpy(plainauth, userp, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, userp, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
/* Base64 encode the reply */
result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);
free(plainauth);
return result;
}
Commit Message: Curl_auth_create_plain_message: fix too-large-input-check
CVE-2018-16839
Reported-by: Harry Sintonen
Bug: https://curl.haxx.se/docs/CVE-2018-16839.html
CWE ID: CWE-119 | CURLcode Curl_auth_create_plain_message(struct Curl_easy *data,
const char *userp,
const char *passwdp,
char **outptr, size_t *outlen)
{
CURLcode result;
char *plainauth;
size_t ulen;
size_t plen;
size_t plainlen;
*outlen = 0;
*outptr = NULL;
ulen = strlen(userp);
plen = strlen(passwdp);
/* Compute binary message length. Check for overflows. */
if((ulen > SIZE_T_MAX/4) || (plen > (SIZE_T_MAX/2 - 2)))
return CURLE_OUT_OF_MEMORY;
plainlen = 2 * ulen + plen + 2;
plainauth = malloc(plainlen);
if(!plainauth)
return CURLE_OUT_OF_MEMORY;
/* Calculate the reply */
memcpy(plainauth, userp, ulen);
plainauth[ulen] = '\0';
memcpy(plainauth + ulen + 1, userp, ulen);
plainauth[2 * ulen + 1] = '\0';
memcpy(plainauth + 2 * ulen + 2, passwdp, plen);
/* Base64 encode the reply */
result = Curl_base64_encode(data, plainauth, plainlen, outptr, outlen);
free(plainauth);
return result;
}
| 169,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SignatureUtil::CheckSignature(
const FilePath& file_path,
ClientDownloadRequest_SignatureInfo* signature_info) {
VLOG(2) << "Checking signature for " << file_path.value();
WINTRUST_FILE_INFO file_info;
file_info.cbStruct = sizeof(file_info);
file_info.pcwszFilePath = file_path.value().c_str();
file_info.hFile = NULL;
file_info.pgKnownSubject = NULL;
WINTRUST_DATA wintrust_data;
wintrust_data.cbStruct = sizeof(wintrust_data);
wintrust_data.pPolicyCallbackData = NULL;
wintrust_data.pSIPClientData = NULL;
wintrust_data.dwUIChoice = WTD_UI_NONE;
wintrust_data.fdwRevocationChecks = WTD_REVOKE_NONE;
wintrust_data.dwUnionChoice = WTD_CHOICE_FILE;
wintrust_data.pFile = &file_info;
wintrust_data.dwStateAction = WTD_STATEACTION_VERIFY;
wintrust_data.hWVTStateData = NULL;
wintrust_data.pwszURLReference = NULL;
wintrust_data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
wintrust_data.dwUIContext = WTD_UICONTEXT_EXECUTE;
GUID policy_guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG result = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid,
&wintrust_data);
CRYPT_PROVIDER_DATA* prov_data = WTHelperProvDataFromStateData(
wintrust_data.hWVTStateData);
if (prov_data) {
if (prov_data->csSigners > 0) {
signature_info->set_trusted(result == ERROR_SUCCESS);
}
for (DWORD i = 0; i < prov_data->csSigners; ++i) {
const CERT_CHAIN_CONTEXT* cert_chain_context =
prov_data->pasSigners[i].pChainContext;
for (DWORD j = 0; j < cert_chain_context->cChain; ++j) {
CERT_SIMPLE_CHAIN* simple_chain = cert_chain_context->rgpChain[j];
ClientDownloadRequest_CertificateChain* chain =
signature_info->add_certificate_chain();
for (DWORD k = 0; k < simple_chain->cElement; ++k) {
CERT_CHAIN_ELEMENT* element = simple_chain->rgpElement[k];
chain->add_element()->set_certificate(
element->pCertContext->pbCertEncoded,
element->pCertContext->cbCertEncoded);
}
}
}
wintrust_data.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid, &wintrust_data);
}
}
Commit Message: Fix null deref when walking cert chain.
BUG=109664
TEST=N/A
Review URL: http://codereview.chromium.org/9150013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@117080 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void SignatureUtil::CheckSignature(
const FilePath& file_path,
ClientDownloadRequest_SignatureInfo* signature_info) {
VLOG(2) << "Checking signature for " << file_path.value();
WINTRUST_FILE_INFO file_info;
file_info.cbStruct = sizeof(file_info);
file_info.pcwszFilePath = file_path.value().c_str();
file_info.hFile = NULL;
file_info.pgKnownSubject = NULL;
WINTRUST_DATA wintrust_data;
wintrust_data.cbStruct = sizeof(wintrust_data);
wintrust_data.pPolicyCallbackData = NULL;
wintrust_data.pSIPClientData = NULL;
wintrust_data.dwUIChoice = WTD_UI_NONE;
wintrust_data.fdwRevocationChecks = WTD_REVOKE_NONE;
wintrust_data.dwUnionChoice = WTD_CHOICE_FILE;
wintrust_data.pFile = &file_info;
wintrust_data.dwStateAction = WTD_STATEACTION_VERIFY;
wintrust_data.hWVTStateData = NULL;
wintrust_data.pwszURLReference = NULL;
wintrust_data.dwProvFlags = WTD_CACHE_ONLY_URL_RETRIEVAL;
wintrust_data.dwUIContext = WTD_UICONTEXT_EXECUTE;
GUID policy_guid = WINTRUST_ACTION_GENERIC_VERIFY_V2;
LONG result = WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid,
&wintrust_data);
CRYPT_PROVIDER_DATA* prov_data = WTHelperProvDataFromStateData(
wintrust_data.hWVTStateData);
if (prov_data) {
if (prov_data->csSigners > 0) {
signature_info->set_trusted(result == ERROR_SUCCESS);
}
for (DWORD i = 0; i < prov_data->csSigners; ++i) {
const CERT_CHAIN_CONTEXT* cert_chain_context =
prov_data->pasSigners[i].pChainContext;
if (!cert_chain_context)
break;
for (DWORD j = 0; j < cert_chain_context->cChain; ++j) {
CERT_SIMPLE_CHAIN* simple_chain = cert_chain_context->rgpChain[j];
ClientDownloadRequest_CertificateChain* chain =
signature_info->add_certificate_chain();
if (!simple_chain)
break;
for (DWORD k = 0; k < simple_chain->cElement; ++k) {
CERT_CHAIN_ELEMENT* element = simple_chain->rgpElement[k];
chain->add_element()->set_certificate(
element->pCertContext->pbCertEncoded,
element->pCertContext->cbCertEncoded);
}
}
}
wintrust_data.dwStateAction = WTD_STATEACTION_CLOSE;
WinVerifyTrust(static_cast<HWND>(INVALID_HANDLE_VALUE),
&policy_guid, &wintrust_data);
}
}
| 170,974 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_png(FILE *fp)
{
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
png_infop info_ptr = NULL;
png_bytep row = NULL, display = NULL;
if (png_ptr == NULL)
return 0;
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
if (row != NULL) free(row);
if (display != NULL) free(display);
return 0;
}
png_init_io(png_ptr, fp);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0);
png_read_info(png_ptr, info_ptr);
{
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = malloc(rowbytes);
display = malloc(rowbytes);
if (row == NULL || display == NULL)
png_error(png_ptr, "OOM allocating row buffers");
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
/* NOTE: this trashes the row each time; interlace handling won't
* work, but this avoids memory thrashing for speed testing.
*/
while (y-- > 0)
png_read_row(png_ptr, row, display);
}
}
}
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(row);
free(display);
return 1;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | read_png(FILE *fp)
{
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,0,0,0);
png_infop info_ptr = NULL;
png_bytep row = NULL, display = NULL;
if (png_ptr == NULL)
return 0;
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
if (row != NULL) free(row);
if (display != NULL) free(display);
return 0;
}
png_init_io(png_ptr, fp);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_ALWAYS, NULL, 0);
png_read_info(png_ptr, info_ptr);
{
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
/* Failure to initialize these is harmless */
row = malloc(rowbytes);
display = malloc(rowbytes);
if (row == NULL || display == NULL)
png_error(png_ptr, "OOM allocating row buffers");
{
png_uint_32 height = png_get_image_height(png_ptr, info_ptr);
# ifdef PNG_READ_INTERLACING_SUPPORTED
int passes = png_set_interlace_handling(png_ptr);
# else /* !READ_INTERLACING */
int passes = png_get_interlace_type(png_ptr, info_ptr) ==
PNG_INTERLACE_ADAM7 ? PNG_INTERLACE_ADAM7_PASSES : 1;
# endif /* !READ_INTERLACING */
int pass;
png_start_read_image(png_ptr);
for (pass = 0; pass < passes; ++pass)
{
png_uint_32 y = height;
# ifndef PNG_READ_INTERLACING_SUPPORTED
if (passes == PNG_INTERLACE_ADAM7_PASSES)
y = PNG_PASS_ROWS(y, pass);
# endif /* READ_INTERLACING */
/* NOTE: this trashes the row each time; interlace handling won't
* work, but this avoids memory thrashing for speed testing.
*/
while (y-- > 0)
png_read_row(png_ptr, row, display);
}
}
}
/* Make sure to read to the end of the file: */
png_read_end(png_ptr, info_ptr);
png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
free(row);
free(display);
return 1;
}
| 173,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 StringSize(const uint8_t *start, uint8_t encoding) {
//// return includes terminator; if unterminated, returns > limit
if (encoding == 0x00 || encoding == 0x03) {
return strlen((const char *)start) + 1;
}
size_t n = 0;
while (start[n] != '\0' || start[n + 1] != '\0') {
n += 2;
}
return n + 2;
}
Commit Message: DO NOT MERGE: defensive parsing of mp3 album art information
several points in stagefrights mp3 album art code
used strlen() to parse user-supplied strings that may be
unterminated, resulting in reading beyond the end of a buffer.
This changes the code to use strnlen() for 8-bit encodings and
strengthens the parsing of 16-bit encodings similarly. It also
reworks how we watch for the end-of-buffer to avoid all over-reads.
Bug: 32377688
Test: crafted mp3's w/ good/bad cover art. See what showed in play music
Change-Id: Ia9f526d71b21ef6a61acacf616b573753cd21df6
(cherry picked from commit fa0806b594e98f1aed3ebcfc6a801b4c0056f9eb)
CWE ID: CWE-200 | static size_t StringSize(const uint8_t *start, uint8_t encoding) {
//// return includes terminator; if unterminated, returns > limit
static size_t StringSize(const uint8_t *start, size_t limit, uint8_t encoding) {
if (encoding == 0x00 || encoding == 0x03) {
return strnlen((const char *)start, limit) + 1;
}
size_t n = 0;
while ((n+1 < limit) && (start[n] != '\0' || start[n + 1] != '\0')) {
n += 2;
}
n += 2;
return n;
}
| 174,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult,
long long& pos, long& len) {
assert(pCurr);
assert(!pCurr->EOS());
assert(m_clusters);
pResult = 0;
if (pCurr->m_index >= 0) { // loaded (not merely preloaded)
assert(m_clusters[pCurr->m_index] == pCurr);
const long next_idx = pCurr->m_index + 1;
if (next_idx < m_clusterCount) {
pResult = m_clusters[next_idx];
return 0; // success
}
const long result = LoadCluster(pos, len);
if (result < 0) // error or underflow
return result;
if (result > 0) // no more clusters
{
return 1;
}
pResult = GetLast();
return 0; // success
}
assert(m_pos > 0);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
pos = pCurr->m_element_start;
if (pCurr->m_element_size >= 0)
pos += pCurr->m_element_size;
else {
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(m_pReader, pos, len);
if (id != 0x0F43B675) // weird: not Cluster ID
return -1;
pos += len; // consume ID
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume size field
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size) // TODO: should never happen
return E_FILE_FORMAT_INVALID; // TODO: resolve this
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
pos += size; // consume payload (that is, the current cluster)
assert((segment_stop < 0) || (pos <= segment_stop));
}
for (;;) {
const long status = DoParseNext(pResult, pos, len);
if (status <= 1)
return status;
}
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult,
long long& pos, long& len) {
assert(pCurr);
assert(!pCurr->EOS());
assert(m_clusters);
pResult = 0;
if (pCurr->m_index >= 0) { // loaded (not merely preloaded)
assert(m_clusters[pCurr->m_index] == pCurr);
const long next_idx = pCurr->m_index + 1;
if (next_idx < m_clusterCount) {
pResult = m_clusters[next_idx];
return 0; // success
}
const long result = LoadCluster(pos, len);
if (result < 0) // error or underflow
return result;
if (result > 0) // no more clusters
{
return 1;
}
pResult = GetLast();
return 0; // success
}
assert(m_pos > 0);
long long total, avail;
long status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
pos = pCurr->m_element_start;
if (pCurr->m_element_size >= 0)
pos += pCurr->m_element_size;
else {
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(m_pReader, pos, len);
if (id != 0x0F43B675) // weird: not Cluster ID
return -1;
pos += len; // consume ID
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
pos += len; // consume size field
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size) // TODO: should never happen
return E_FILE_FORMAT_INVALID; // TODO: resolve this
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
pos += size; // consume payload (that is, the current cluster)
if (segment_stop >= 0 && pos > segment_stop)
return E_FILE_FORMAT_INVALID;
}
for (;;) {
const long status = DoParseNext(pResult, pos, len);
if (status <= 1)
return status;
}
}
| 173,857 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() {
Profile* profile =
Profile::FromBrowserContext(GetWebContents()->GetBrowserContext());
Profile* original_profile = profile->GetOriginalProfile();
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(original_profile->GetPrefs()));
TranslateAcceptLanguages* accept_languages =
TranslateTabHelper::GetTranslateAcceptLanguages(original_profile);
return translate_prefs->CanTranslateLanguage(accept_languages,
original_language_code());
}
Commit Message: Remove dependency of TranslateInfobarDelegate on profile
This CL uses TranslateTabHelper instead of Profile and also cleans up
some unused code and irrelevant dependencies.
BUG=371845
Review URL: https://codereview.chromium.org/286973003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@270758 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | bool TranslateInfoBarDelegate::IsTranslatableLanguageByPrefs() {
TranslateTabHelper* translate_tab_helper =
TranslateTabHelper::FromWebContents(GetWebContents());
scoped_ptr<TranslatePrefs> translate_prefs(
TranslateTabHelper::CreateTranslatePrefs(
translate_tab_helper->GetPrefs()));
TranslateAcceptLanguages* accept_languages =
translate_tab_helper->GetTranslateAcceptLanguages();
return translate_prefs->CanTranslateLanguage(accept_languages,
original_language_code());
}
| 171,174 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::getParameter(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getParameter, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing
- Prohibit direct set/getParam/Settings for extensions meant for
OMXNodeInstance alone. This disallows enabling metadata mode
without the knowledge of OMXNodeInstance.
- Use a backup buffer for metadata mode buffers and do not directly
share with clients.
- Disallow setting up metadata mode/tunneling/input surface
after first sendCommand.
- Disallow store-meta for input cross process.
- Disallow emptyBuffer for surface input (via IOMX).
- Fix checking for input surface.
Bug: 29422020
Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e
(cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8)
CWE ID: CWE-200 | status_t OMXNodeInstance::getParameter(
OMX_INDEXTYPE index, void *params, size_t /* size */) {
Mutex::Autolock autoLock(mLock);
if (isProhibitedIndex_l(index)) {
android_errorWriteLog(0x534e4554, "29422020");
return BAD_INDEX;
}
OMX_ERRORTYPE err = OMX_GetParameter(mHandle, index, params);
OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index;
if (err != OMX_ErrorNoMore) {
CLOG_IF_ERROR(getParameter, err, "%s(%#x)", asString(extIndex), index);
}
return StatusFromOMXError(err);
}
| 174,135 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 const char *parse_array( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '[' ) {
/* Not an array! */
ep = value;
return 0;
}
item->type = cJSON_Array;
value = skip( value + 1 );
if ( *value == ']' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! ( value = skip( parse_value( child, skip( value ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_value( child, skip( value+1 ) ) ) ) )
return 0; /* memory fail */
}
if ( *value == ']' )
return value + 1; /* end of array */
/* Malformed. */
ep = value;
return 0;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static const char *parse_array( cJSON *item, const char *value )
static const char *parse_array(cJSON *item,const char *value,const char **ep)
{
cJSON *child;
if (*value!='[') {*ep=value;return 0;} /* not an array! */
item->type=cJSON_Array;
value=skip(value+1);
if (*value==']') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0; /* memory fail */
value=skip(parse_value(child,skip(value),ep)); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_value(child,skip(value+1),ep));
if (!value) return 0; /* memory fail */
}
if (*value==']') return value+1; /* end of array */
*ep=value;return 0; /* malformed. */
}
| 167,301 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (1 << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
Commit Message: Fixed an integral type promotion problem by adding a JAS_CAST.
Modified the jpc_tsfb_synthesize function so that it will be a noop for
an empty sequence (in order to avoid dereferencing a null pointer).
CWE ID: CWE-476 | static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps)
{
int i;
int j;
int thresh;
jpc_fix_t val;
jpc_fix_t mag;
bool warn;
uint_fast32_t mask;
if (roishift < 0) {
/* We could instead return an error here. */
/* I do not think it matters much. */
jas_eprintf("warning: forcing negative ROI shift to zero "
"(bitstream is probably corrupt)\n");
roishift = 0;
}
if (roishift == 0 && bgshift == 0) {
return;
}
thresh = 1 << roishift;
warn = false;
for (i = 0; i < jas_matrix_numrows(x); ++i) {
for (j = 0; j < jas_matrix_numcols(x); ++j) {
val = jas_matrix_get(x, i, j);
mag = JAS_ABS(val);
if (mag >= thresh) {
/* We are dealing with ROI data. */
mag >>= roishift;
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
} else {
/* We are dealing with non-ROI (i.e., background) data. */
mag <<= bgshift;
mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1;
/* Perform a basic sanity check on the sample value. */
/* Some implementations write garbage in the unused
most-significant bit planes introduced by ROI shifting.
Here we ensure that any such bits are masked off. */
if (mag & (~mask)) {
if (!warn) {
jas_eprintf("warning: possibly corrupt code stream\n");
warn = true;
}
mag &= mask;
}
val = (val < 0) ? (-mag) : mag;
jas_matrix_set(x, i, j, val);
}
}
}
}
| 168,477 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 use_conf(char *test_path)
{
int ret;
size_t flags = 0;
char filename[1024], errstr[1024];
char *buffer;
FILE *infile, *conffile;
json_t *json;
json_error_t error;
sprintf(filename, "%s%cinput", test_path, dir_sep);
if (!(infile = fopen(filename, "rb"))) {
fprintf(stderr, "Could not open \"%s\"\n", filename);
return 2;
}
sprintf(filename, "%s%cenv", test_path, dir_sep);
conffile = fopen(filename, "rb");
if (conffile) {
read_conf(conffile);
fclose(conffile);
}
if (conf.indent < 0 || conf.indent > 255) {
fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent);
return 2;
}
if (conf.indent)
flags |= JSON_INDENT(conf.indent);
if (conf.compact)
flags |= JSON_COMPACT;
if (conf.ensure_ascii)
flags |= JSON_ENSURE_ASCII;
if (conf.preserve_order)
flags |= JSON_PRESERVE_ORDER;
if (conf.sort_keys)
flags |= JSON_SORT_KEYS;
if (conf.strip) {
/* Load to memory, strip leading and trailing whitespace */
buffer = loadfile(infile);
json = json_loads(strip(buffer), 0, &error);
free(buffer);
}
else
json = json_loadf(infile, 0, &error);
fclose(infile);
if (!json) {
sprintf(errstr, "%d %d %d\n%s\n",
error.line, error.column, error.position,
error.text);
ret = cmpfile(errstr, test_path, "error");
return ret;
}
buffer = json_dumps(json, flags);
ret = cmpfile(buffer, test_path, "output");
free(buffer);
json_decref(json);
return ret;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | int use_conf(char *test_path)
{
int ret;
size_t flags = 0;
char filename[1024], errstr[1024];
char *buffer;
FILE *infile, *conffile;
json_t *json;
json_error_t error;
sprintf(filename, "%s%cinput", test_path, dir_sep);
if (!(infile = fopen(filename, "rb"))) {
fprintf(stderr, "Could not open \"%s\"\n", filename);
return 2;
}
sprintf(filename, "%s%cenv", test_path, dir_sep);
conffile = fopen(filename, "rb");
if (conffile) {
read_conf(conffile);
fclose(conffile);
}
if (conf.indent < 0 || conf.indent > 255) {
fprintf(stderr, "invalid value for JSON_INDENT: %d\n", conf.indent);
return 2;
}
if (conf.indent)
flags |= JSON_INDENT(conf.indent);
if (conf.compact)
flags |= JSON_COMPACT;
if (conf.ensure_ascii)
flags |= JSON_ENSURE_ASCII;
if (conf.preserve_order)
flags |= JSON_PRESERVE_ORDER;
if (conf.sort_keys)
flags |= JSON_SORT_KEYS;
if (conf.have_hashseed)
json_object_seed(conf.hashseed);
if (conf.strip) {
/* Load to memory, strip leading and trailing whitespace */
buffer = loadfile(infile);
json = json_loads(strip(buffer), 0, &error);
free(buffer);
}
else
json = json_loadf(infile, 0, &error);
fclose(infile);
if (!json) {
sprintf(errstr, "%d %d %d\n%s\n",
error.line, error.column, error.position,
error.text);
ret = cmpfile(errstr, test_path, "error");
return ret;
}
buffer = json_dumps(json, flags);
ret = cmpfile(buffer, test_path, "output");
free(buffer);
json_decref(json);
return ret;
}
| 166,537 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas,
const SkPath& clip) const {
bool has_custom_image;
int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image);
if (!has_custom_image)
fill_id = 0;
PaintTabBackground(canvas, false /* active */, fill_id, 0,
tab_->controller()->MaySetClip() ? &clip : nullptr);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | void GM2TabStyle::PaintInactiveTabBackground(gfx::Canvas* canvas,
const SkPath& clip) const {
bool has_custom_image;
int fill_id = tab_->controller()->GetBackgroundResourceId(&has_custom_image);
if (!has_custom_image)
fill_id = 0;
PaintTabBackground(canvas, TAB_INACTIVE, fill_id, 0,
tab_->controller()->MaySetClip() ? &clip : nullptr);
}
| 172,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
pipe_buf_get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
out:
kvfree(bufs);
return ret;
}
Commit Message: Merge branch 'page-refs' (page ref overflow)
Merge page ref overflow branch.
Jann Horn reported that he can overflow the page ref count with
sufficient memory (and a filesystem that is intentionally extremely
slow).
Admittedly it's not exactly easy. To have more than four billion
references to a page requires a minimum of 32GB of kernel memory just
for the pointers to the pages, much less any metadata to keep track of
those pointers. Jann needed a total of 140GB of memory and a specially
crafted filesystem that leaves all reads pending (in order to not ever
free the page references and just keep adding more).
Still, we have a fairly straightforward way to limit the two obvious
user-controllable sources of page references: direct-IO like page
references gotten through get_user_pages(), and the splice pipe page
duplication. So let's just do that.
* branch page-refs:
fs: prevent page refcount overflow in pipe_buf_get
mm: prevent get_user_pages() from overflowing page refcount
mm: add 'try_get_page()' helper function
mm: make page ref count overflow check tighter and more explicit
CWE ID: CWE-416 | static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
pipe_lock(pipe);
bufs = kvmalloc_array(pipe->nrbufs, sizeof(struct pipe_buffer),
GFP_KERNEL);
if (!bufs) {
pipe_unlock(pipe);
return -ENOMEM;
}
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len)
goto out_free;
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
if (!pipe_buf_get(pipe, ibuf))
goto out_free;
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
pipe_lock(pipe);
out_free:
for (idx = 0; idx < nbuf; idx++)
pipe_buf_release(pipe, &bufs[idx]);
pipe_unlock(pipe);
kvfree(bufs);
return ret;
}
| 170,217 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pop_decoder_state (DECODER_STATE ds)
{
if (!ds->idx)
{
fprintf (stderr, "ERROR: decoder stack underflow!\n");
abort ();
}
ds->cur = ds->stack[--ds->idx];
}
Commit Message:
CWE ID: CWE-20 | pop_decoder_state (DECODER_STATE ds)
{
if (!ds->idx)
{
fprintf (stderr, "ksba: ber-decoder: stack underflow!\n");
return gpg_error (GPG_ERR_INTERNAL);
}
ds->cur = ds->stack[--ds->idx];
return 0;
}
| 165,051 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ndp_sock_recv(struct ndp *ndp)
{
struct ndp_msg *msg;
enum ndp_msg_type msg_type;
size_t len;
int err;
msg = ndp_msg_alloc();
if (!msg)
return -ENOMEM;
len = ndp_msg_payload_maxlen(msg);
err = myrecvfrom6(ndp->sock, msg->buf, &len, 0,
&msg->addrto, &msg->ifindex);
if (err) {
err(ndp, "Failed to receive message");
goto free_msg;
}
dbg(ndp, "rcvd from: %s, ifindex: %u",
str_in6_addr(&msg->addrto), msg->ifindex);
if (len < sizeof(*msg->icmp6_hdr)) {
warn(ndp, "rcvd icmp6 packet too short (%luB)", len);
err = 0;
goto free_msg;
}
err = ndp_msg_type_by_raw_type(&msg_type, msg->icmp6_hdr->icmp6_type);
if (err) {
err = 0;
goto free_msg;
}
ndp_msg_init(msg, msg_type);
ndp_msg_payload_len_set(msg, len);
if (!ndp_msg_check_valid(msg)) {
warn(ndp, "rcvd invalid ND message");
err = 0;
goto free_msg;
}
dbg(ndp, "rcvd %s, len: %zuB",
ndp_msg_type_info(msg_type)->strabbr, len);
if (!ndp_msg_check_opts(msg)) {
err = 0;
goto free_msg;
}
err = ndp_call_handlers(ndp, msg);;
free_msg:
ndp_msg_destroy(msg);
return err;
}
Commit Message: libndp: validate the IPv6 hop limit
None of the NDP messages should ever come from a non-local network; as
stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA),
and 8.1. (redirect):
- The IP Hop Limit field has a value of 255, i.e., the packet
could not possibly have been forwarded by a router.
This fixes CVE-2016-3698.
Reported by: Julien BERNARD <[email protected]>
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284 | static int ndp_sock_recv(struct ndp *ndp)
{
struct ndp_msg *msg;
enum ndp_msg_type msg_type;
size_t len;
int err;
msg = ndp_msg_alloc();
if (!msg)
return -ENOMEM;
len = ndp_msg_payload_maxlen(msg);
err = myrecvfrom6(ndp->sock, msg->buf, &len, 0,
&msg->addrto, &msg->ifindex, &msg->hoplimit);
if (err) {
err(ndp, "Failed to receive message");
goto free_msg;
}
dbg(ndp, "rcvd from: %s, ifindex: %u, hoplimit: %d",
str_in6_addr(&msg->addrto), msg->ifindex, msg->hoplimit);
if (msg->hoplimit != 255) {
warn(ndp, "ignoring packet with bad hop limit (%d)", msg->hoplimit);
err = 0;
goto free_msg;
}
if (len < sizeof(*msg->icmp6_hdr)) {
warn(ndp, "rcvd icmp6 packet too short (%luB)", len);
err = 0;
goto free_msg;
}
err = ndp_msg_type_by_raw_type(&msg_type, msg->icmp6_hdr->icmp6_type);
if (err) {
err = 0;
goto free_msg;
}
ndp_msg_init(msg, msg_type);
ndp_msg_payload_len_set(msg, len);
if (!ndp_msg_check_valid(msg)) {
warn(ndp, "rcvd invalid ND message");
err = 0;
goto free_msg;
}
dbg(ndp, "rcvd %s, len: %zuB",
ndp_msg_type_info(msg_type)->strabbr, len);
if (!ndp_msg_check_opts(msg)) {
err = 0;
goto free_msg;
}
err = ndp_call_handlers(ndp, msg);;
free_msg:
ndp_msg_destroy(msg);
return err;
}
| 167,350 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 QuotaTask::DeleteSoon() {
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
Commit Message: Quota double-delete fix
BUG=142310
Review URL: https://chromiumcodereview.appspot.com/10832407
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void QuotaTask::DeleteSoon() {
DCHECK(original_task_runner_->BelongsToCurrentThread());
if (delete_scheduled_)
return;
delete_scheduled_ = true;
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
| 170,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static void readpng2_warning_handler(png_structp png_ptr, png_const_charp msg)
{
fprintf(stderr, "readpng2 libpng warning: %s\n", msg);
fflush(stderr);
(void)png_ptr; /* Unused */
}
| 173,571 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = l2t_send(tdev, skb, l2e);
if (error < 0)
kfree_skb(skb);
return error;
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: | static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_entry *l2e)
{
int error = 0;
struct cxio_rdev *rdev;
rdev = (struct cxio_rdev *)tdev->ulp;
if (cxio_fatal_error(rdev)) {
kfree_skb(skb);
return -EIO;
}
error = l2t_send(tdev, skb, l2e);
if (error < 0)
kfree_skb(skb);
return error < 0 ? error : 0;
}
| 167,496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.