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: add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
Commit Message:
CWE ID: CWE-416 | add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many)
{
int current;
cmap_splay *tree;
if (low > high)
{
fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name);
return;
}
tree = cmap->tree;
if (cmap->tlen)
{
unsigned int move = cmap->ttop;
unsigned int gt = EMPTY;
unsigned int lt = EMPTY;
if (check_for_overlap)
{
/* Check for collision with the current node */
do
{
current = move;
/* Cases we might meet:
* tree[i]: <----->
* case 0: <->
* case 1: <------->
* case 2: <------------->
* case 3: <->
* case 4: <------->
* case 5: <->
*/
if (low <= tree[current].low && tree[current].low <= high)
{
/* case 1, reduces to case 0 */
/* or case 2, deleting the node */
tree[current].out += high + 1 - tree[current].low;
tree[current].low = high + 1;
if (tree[current].low > tree[current].high)
{
move = delete_node(cmap, current);
current = EMPTY;
continue;
}
}
else if (low <= tree[current].high && tree[current].high <= high)
{
/* case 4, reduces to case 5 */
tree[current].high = low - 1;
assert(tree[current].low <= tree[current].high);
}
else if (tree[current].low < low && high < tree[current].high)
{
/* case 3, reduces to case 5 */
int new_high = tree[current].high;
tree[current].high = low-1;
add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many);
tree = cmap->tree;
}
/* Now look for where to move to next (left for case 0, right for case 5) */
if (tree[current].low > high) {
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
}
while (move != EMPTY);
}
else
{
do
{
current = move;
if (tree[current].low > high)
{
move = tree[current].left;
gt = current;
}
else
{
move = tree[current].right;
lt = current;
}
} while (move != EMPTY);
}
/* current is now the node to which we would be adding the new node */
/* lt is the last node we traversed which is lt the new node. */
/* gt is the last node we traversed which is gt the new node. */
if (!many)
{
/* Check for the 'merge' cases. */
if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low)
{
tree[lt].high = high;
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[lt].high = tree[gt].high;
delete_node(cmap, gt);
}
goto exit;
}
if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low)
{
tree[gt].low = low;
tree[gt].out = out;
goto exit;
}
}
}
else
current = EMPTY;
if (cmap->tlen == cmap->tcap)
{
int new_cap = cmap->tcap ? cmap->tcap * 2 : 256;
tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree);
cmap->tcap = new_cap;
}
tree[cmap->tlen].low = low;
tree[cmap->tlen].high = high;
tree[cmap->tlen].out = out;
tree[cmap->tlen].parent = current;
tree[cmap->tlen].left = EMPTY;
tree[cmap->tlen].right = EMPTY;
tree[cmap->tlen].many = many;
cmap->tlen++;
if (current == EMPTY)
cmap->ttop = 0;
else if (tree[current].low > high)
tree[current].left = cmap->tlen-1;
else
{
assert(tree[current].high < low);
tree[current].right = cmap->tlen-1;
}
move_to_root(tree, cmap->tlen-1);
cmap->ttop = cmap->tlen-1;
exit:
{}
#ifdef CHECK_SPLAY
check_splay(cmap->tree, cmap->ttop, 0);
#endif
#ifdef DUMP_SPLAY
dump_splay(cmap->tree, cmap->ttop, 0, "");
#endif
}
| 164,577 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ih264d_parse_islice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ih264d_init_cabac_contexts(I_SLICE, ps_dec);
ps_dec->i1_prev_mb_qp_delta = 0;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD16 u2_mbx;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
{
UWORD8 u1_mb_type;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
u2_mbx = ps_dec->u2_mbx;
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(
ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type
| D_INTRA_MB;
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_intra_cabac(0, ps_dec);
if(u1_mb_type > 25)
return ERROR_MB_TYPE;
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/* Parse Macroblock Data */
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cabac(ps_dec, ps_cur_mb_info, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(
ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1),
4, 4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
}
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Decoder Update mb count after mb map is set.
Bug: 25928803
Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37
CWE ID: CWE-119 | WORD32 ih264d_parse_islice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD8 uc_more_data_flag;
UWORD8 u1_num_mbs, u1_mb_idx;
dec_mb_info_t *ps_cur_mb_info;
deblk_mb_t *ps_cur_deblk_mb;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
WORD16 i2_cur_mb_addr;
UWORD8 u1_mbaff;
UWORD8 u1_num_mbs_next, u1_end_of_row, u1_tfr_n_mb;
WORD32 ret = OK;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ih264d_init_cabac_contexts(I_SLICE, ps_dec);
ps_dec->i1_prev_mb_qp_delta = 0;
/* initializations */
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
uc_more_data_flag = 1;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
do
{
UWORD16 u2_mbx;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
{
UWORD8 u1_mb_type;
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_mb_info->u1_end_of_slice = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 0);
u2_mbx = ps_dec->u2_mbx;
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(
ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
ps_cur_deblk_mb->u1_mb_type = ps_cur_deblk_mb->u1_mb_type
| D_INTRA_MB;
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_intra_cabac(0, ps_dec);
if(u1_mb_type > 25)
return ERROR_MB_TYPE;
ps_cur_mb_info->u1_mb_type = u1_mb_type;
COPYTHECONTEXT("u1_mb_type", u1_mb_type);
/* Parse Macroblock Data */
if(25 == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
ret = ih264d_parse_imb_cabac(ps_dec, ps_cur_mb_info, u1_mb_type);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
/* Store the colocated information */
{
mv_pred_t *ps_mv_nmb_start = ps_dec->ps_mv_cur + (u1_num_mbs << 4);
mv_pred_t s_mvPred =
{
{ 0, 0, 0, 0 },
{ -1, -1 }, 0, 0};
ih264d_rep_mv_colz(
ps_dec, &s_mvPred, ps_mv_nmb_start, 0,
(UWORD8)(ps_dec->u1_cur_mb_fld_dec_flag << 1),
4, 4);
}
/*if num _cores is set to 3,compute bs will be done in another thread*/
if(ps_dec->u4_num_cores < 3)
{
if(ps_dec->u4_app_disable_deblk_frm == 0)
ps_dec->pf_compute_bs(ps_dec, ps_cur_mb_info,
(UWORD16)(u1_num_mbs >> u1_mbaff));
}
u1_num_mbs++;
}
/****************************************************************/
/* Check for End Of Row */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| (!uc_more_data_flag);
ps_cur_mb_info->u1_end_of_slice = (!uc_more_data_flag);
if(u1_tfr_n_mb || (!uc_more_data_flag))
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
while(uc_more_data_flag);
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 173,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
}
Commit Message: Fix an integer overflow issue (#809)
Prevent an integer overflow issue in function opj_pi_create_decode of
pi.c.
CWE ID: CWE-125 | opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
}
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
}
| 166,943 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ScreenOrientationDispatcherHost::OnLockRequest(
RenderFrameHost* render_frame_host,
blink::WebScreenOrientationLockType orientation,
int request_id) {
if (current_lock_) {
NotifyLockError(current_lock_->request_id,
blink::WebLockOrientationErrorCanceled);
}
current_lock_ = new LockInformation(request_id,
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID());
if (!provider_) {
NotifyLockError(request_id,
blink::WebLockOrientationErrorNotAvailable);
return;
}
provider_->LockOrientation(request_id, orientation);
}
Commit Message: Cleanups in ScreenOrientationDispatcherHost.
BUG=None
Review URL: https://codereview.chromium.org/408213003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void ScreenOrientationDispatcherHost::OnLockRequest(
RenderFrameHost* render_frame_host,
blink::WebScreenOrientationLockType orientation,
int request_id) {
if (current_lock_) {
NotifyLockError(current_lock_->request_id,
blink::WebLockOrientationErrorCanceled);
}
if (!provider_) {
NotifyLockError(request_id,
blink::WebLockOrientationErrorNotAvailable);
return;
}
current_lock_ = new LockInformation(request_id,
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID());
provider_->LockOrientation(request_id, orientation);
}
| 171,177 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebMediaPlayerImpl::DidGetOpaqueResponseFromServiceWorker() const {
if (data_source_)
return data_source_->DidGetOpaqueResponseViaServiceWorker();
return false;
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool WebMediaPlayerImpl::DidGetOpaqueResponseFromServiceWorker() const {
| 172,630 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IntRect PopupContainer::layoutAndCalculateWidgetRect(int targetControlHeight, const IntPoint& popupInitialCoordinate)
{
m_listBox->setMaxHeight(kMaxHeight);
m_listBox->setMaxWidth(std::numeric_limits<int>::max());
int rtlOffset = layoutAndGetRTLOffset();
bool isRTL = this->isRTL();
int rightOffset = isRTL ? rtlOffset : 0;
IntSize targetSize(m_listBox->width() + kBorderSize * 2,
m_listBox->height() + kBorderSize * 2);
IntRect widgetRect;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
FloatRect screen = screenAvailableRect(m_frameView.get());
widgetRect = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + rightOffset, popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
FloatRect windowRect = chromeClient->windowRect();
if (windowRect.x() >= screen.x() && windowRect.maxX() <= screen.maxX() && (widgetRect.x() < screen.x() || widgetRect.maxX() > screen.maxX())) {
IntRect inverseWidgetRect = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + (isRTL ? 0 : rtlOffset), popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
IntRect enclosingScreen = enclosingIntRect(screen);
unsigned originalCutoff = max(enclosingScreen.x() - widgetRect.x(), 0) + max(widgetRect.maxX() - enclosingScreen.maxX(), 0);
unsigned inverseCutoff = max(enclosingScreen.x() - inverseWidgetRect.x(), 0) + max(inverseWidgetRect.maxX() - enclosingScreen.maxX(), 0);
if (inverseCutoff < originalCutoff)
widgetRect = inverseWidgetRect;
if (widgetRect.x() < screen.x()) {
unsigned widgetRight = widgetRect.maxX();
widgetRect.setWidth(widgetRect.maxX() - screen.x());
widgetRect.setX(widgetRight - widgetRect.width());
listBox()->setMaxWidthAndLayout(max(widgetRect.width() - kBorderSize * 2, 0));
} else if (widgetRect.maxX() > screen.maxX()) {
widgetRect.setWidth(screen.maxX() - widgetRect.x());
listBox()->setMaxWidthAndLayout(max(widgetRect.width() - kBorderSize * 2, 0));
}
}
if (widgetRect.maxY() > static_cast<int>(screen.maxY())) {
if (widgetRect.y() - widgetRect.height() - targetControlHeight > 0) {
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
} else {
int spaceAbove = widgetRect.y() - targetControlHeight;
int spaceBelow = screen.maxY() - widgetRect.y();
if (spaceAbove > spaceBelow)
m_listBox->setMaxHeight(spaceAbove);
else
m_listBox->setMaxHeight(spaceBelow);
layoutAndGetRTLOffset();
IntRect frameInScreen = chromeClient->rootViewToScreen(frameRect());
widgetRect.setY(frameInScreen.y());
widgetRect.setHeight(frameInScreen.height());
if (spaceAbove > spaceBelow)
widgetRect.move(0, -(widgetRect.height() + targetControlHeight));
}
}
}
return widgetRect;
}
Commit Message: [REGRESSION] Refreshed autofill popup renders garbage
https://bugs.webkit.org/show_bug.cgi?id=83255
http://code.google.com/p/chromium/issues/detail?id=118374
The code used to update only the PopupContainer coordinates as if they were the coordinates relative
to the root view. Instead, a WebWidget positioned relative to the screen origin holds the PopupContainer,
so it is the WebWidget that should be positioned in PopupContainer::refresh(), and the PopupContainer's
location should be (0, 0) (and their sizes should always be equal).
Reviewed by Kent Tamura.
No new tests, as the popup appearance is not testable in WebKit.
* platform/chromium/PopupContainer.cpp:
(WebCore::PopupContainer::layoutAndCalculateWidgetRect): Variable renamed.
(WebCore::PopupContainer::showPopup): Use m_originalFrameRect rather than frameRect()
for passing into chromeClient.
(WebCore::PopupContainer::showInRect): Set up the correct frameRect() for the container.
(WebCore::PopupContainer::refresh): Resize the container and position the WebWidget correctly.
* platform/chromium/PopupContainer.h:
(PopupContainer):
git-svn-id: svn://svn.chromium.org/blink/trunk@113418 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | IntRect PopupContainer::layoutAndCalculateWidgetRect(int targetControlHeight, const IntPoint& popupInitialCoordinate)
{
m_listBox->setMaxHeight(kMaxHeight);
m_listBox->setMaxWidth(std::numeric_limits<int>::max());
int rtlOffset = layoutAndGetRTLOffset();
bool isRTL = this->isRTL();
int rightOffset = isRTL ? rtlOffset : 0;
IntSize targetSize(m_listBox->width() + kBorderSize * 2,
m_listBox->height() + kBorderSize * 2);
IntRect widgetRectInScreen;
ChromeClientChromium* chromeClient = chromeClientChromium();
if (chromeClient) {
FloatRect screen = screenAvailableRect(m_frameView.get());
widgetRectInScreen = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + rightOffset, popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
FloatRect windowRect = chromeClient->windowRect();
if (windowRect.x() >= screen.x() && windowRect.maxX() <= screen.maxX() && (widgetRectInScreen.x() < screen.x() || widgetRectInScreen.maxX() > screen.maxX())) {
IntRect inverseWidgetRectInScreen = chromeClient->rootViewToScreen(IntRect(popupInitialCoordinate.x() + (isRTL ? 0 : rtlOffset), popupInitialCoordinate.y(), targetSize.width(), targetSize.height()));
IntRect enclosingScreen = enclosingIntRect(screen);
unsigned originalCutoff = max(enclosingScreen.x() - widgetRectInScreen.x(), 0) + max(widgetRectInScreen.maxX() - enclosingScreen.maxX(), 0);
unsigned inverseCutoff = max(enclosingScreen.x() - inverseWidgetRectInScreen.x(), 0) + max(inverseWidgetRectInScreen.maxX() - enclosingScreen.maxX(), 0);
if (inverseCutoff < originalCutoff)
widgetRectInScreen = inverseWidgetRectInScreen;
if (widgetRectInScreen.x() < screen.x()) {
unsigned widgetRight = widgetRectInScreen.maxX();
widgetRectInScreen.setWidth(widgetRectInScreen.maxX() - screen.x());
widgetRectInScreen.setX(widgetRight - widgetRectInScreen.width());
listBox()->setMaxWidthAndLayout(max(widgetRectInScreen.width() - kBorderSize * 2, 0));
} else if (widgetRectInScreen.maxX() > screen.maxX()) {
widgetRectInScreen.setWidth(screen.maxX() - widgetRectInScreen.x());
listBox()->setMaxWidthAndLayout(max(widgetRectInScreen.width() - kBorderSize * 2, 0));
}
}
if (widgetRectInScreen.maxY() > static_cast<int>(screen.maxY())) {
if (widgetRectInScreen.y() - widgetRectInScreen.height() - targetControlHeight > 0) {
widgetRectInScreen.move(0, -(widgetRectInScreen.height() + targetControlHeight));
} else {
int spaceAbove = widgetRectInScreen.y() - targetControlHeight;
int spaceBelow = screen.maxY() - widgetRectInScreen.y();
if (spaceAbove > spaceBelow)
m_listBox->setMaxHeight(spaceAbove);
else
m_listBox->setMaxHeight(spaceBelow);
layoutAndGetRTLOffset();
IntRect frameInScreen = chromeClient->rootViewToScreen(frameRect());
widgetRectInScreen.setY(frameInScreen.y());
widgetRectInScreen.setHeight(frameInScreen.height());
if (spaceAbove > spaceBelow)
widgetRectInScreen.move(0, -(widgetRectInScreen.height() + targetControlHeight));
}
}
}
return widgetRectInScreen;
}
| 171,026 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int jas_iccputsint(jas_stream_t *out, int n, longlong val)
{
ulonglong tmp;
tmp = (val < 0) ? (abort(), 0) : val;
return jas_iccputuint(out, n, tmp);
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jas_iccputsint(jas_stream_t *out, int n, longlong val)
static int jas_iccputsint(jas_stream_t *out, int n, jas_longlong val)
{
jas_ulonglong tmp;
tmp = (val < 0) ? (abort(), 0) : val;
return jas_iccputuint(out, n, tmp);
}
| 168,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: StorageHandler::GetCacheStorageObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!cache_storage_observer_) {
cache_storage_observer_ = std::make_unique<CacheStorageObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<CacheStorageContextImpl*>(
process_->GetStoragePartition()->GetCacheStorageContext()));
}
return cache_storage_observer_.get();
}
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 | StorageHandler::GetCacheStorageObserver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!cache_storage_observer_) {
cache_storage_observer_ = std::make_unique<CacheStorageObserver>(
weak_ptr_factory_.GetWeakPtr(),
static_cast<CacheStorageContextImpl*>(
storage_partition_->GetCacheStorageContext()));
}
return cache_storage_observer_.get();
}
| 172,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
Commit Message:
CWE ID: CWE-119 | tt_sbit_decoder_load_image( TT_SBitDecoder decoder,
FT_UInt glyph_index,
FT_Int x_pos,
FT_Int y_pos )
{
/*
* First, we find the correct strike range that applies to this
* glyph index.
*/
FT_Byte* p = decoder->eblc_base + decoder->strike_index_array;
FT_Byte* p_limit = decoder->eblc_limit;
FT_ULong num_ranges = decoder->strike_index_count;
FT_UInt start, end, index_format, image_format;
FT_ULong image_start = 0, image_end = 0, image_offset;
for ( ; num_ranges > 0; num_ranges-- )
{
start = FT_NEXT_USHORT( p );
end = FT_NEXT_USHORT( p );
if ( glyph_index >= start && glyph_index <= end )
goto FoundRange;
p += 4; /* ignore index offset */
}
goto NoBitmap;
FoundRange:
image_offset = FT_NEXT_ULONG( p );
/* overflow check */
p = decoder->eblc_base + decoder->strike_index_array;
if ( image_offset > (FT_ULong)( p_limit - p ) )
goto Failure;
p += image_offset;
if ( p + 8 > p_limit )
goto NoBitmap;
/* now find the glyph's location and extend within the ebdt table */
index_format = FT_NEXT_USHORT( p );
image_format = FT_NEXT_USHORT( p );
image_offset = FT_NEXT_ULONG ( p );
switch ( index_format )
{
case 1: /* 4-byte offsets relative to `image_offset' */
p += 4 * ( glyph_index - start );
if ( p + 8 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_ULONG( p );
image_end = FT_NEXT_ULONG( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 2: /* big metrics, constant image size */
{
FT_ULong image_size;
if ( p + 12 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
image_start = image_size * ( glyph_index - start );
image_end = image_start + image_size;
}
break;
case 3: /* 2-byte offsets relative to 'image_offset' */
p += 2 * ( glyph_index - start );
if ( p + 4 > p_limit )
goto NoBitmap;
image_start = FT_NEXT_USHORT( p );
image_end = FT_NEXT_USHORT( p );
if ( image_start == image_end ) /* missing glyph */
goto NoBitmap;
break;
case 4: /* sparse glyph array with (glyph,offset) pairs */
{
FT_ULong mm, num_glyphs;
if ( p + 4 > p_limit )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + ( num_glyphs + 1 ) * 4 */
if ( p + 4 > p_limit ||
num_glyphs > (FT_ULong)( ( ( p_limit - p ) >> 2 ) - 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
{
image_start = FT_NEXT_USHORT( p );
p += 2;
image_end = FT_PEEK_USHORT( p );
break;
}
p += 2;
}
if ( mm >= num_glyphs )
goto NoBitmap;
}
break;
case 5: /* constant metrics with sparse glyph codes */
case 19:
{
FT_ULong image_size, mm, num_glyphs;
if ( p + 16 > p_limit )
goto NoBitmap;
image_size = FT_NEXT_ULONG( p );
if ( tt_sbit_decoder_load_metrics( decoder, &p, p_limit, 1 ) )
goto NoBitmap;
num_glyphs = FT_NEXT_ULONG( p );
/* overflow check for p + 2 * num_glyphs */
if ( num_glyphs > (FT_ULong)( ( p_limit - p ) >> 1 ) )
goto NoBitmap;
for ( mm = 0; mm < num_glyphs; mm++ )
{
FT_UInt gindex = FT_NEXT_USHORT( p );
if ( gindex == glyph_index )
break;
}
if ( mm >= num_glyphs )
goto NoBitmap;
image_start = image_size * mm;
image_end = image_start + image_size;
}
break;
default:
goto NoBitmap;
}
| 164,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual void SetUp() {
svc_.encoding_mode = INTER_LAYER_PREDICTION_IP;
svc_.log_level = SVC_LOG_DEBUG;
svc_.log_print = 0;
codec_iface_ = vpx_codec_vp9_cx();
const vpx_codec_err_t res =
vpx_codec_enc_config_default(codec_iface_, &codec_enc_, 0);
EXPECT_EQ(VPX_CODEC_OK, res);
codec_enc_.g_w = kWidth;
codec_enc_.g_h = kHeight;
codec_enc_.g_timebase.num = 1;
codec_enc_.g_timebase.den = 60;
codec_enc_.kf_min_dist = 100;
codec_enc_.kf_max_dist = 100;
vpx_codec_dec_cfg_t dec_cfg = {0};
VP9CodecFactory codec_factory;
decoder_ = codec_factory.CreateDecoder(dec_cfg, 0);
}
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 | virtual void SetUp() {
svc_.log_level = SVC_LOG_DEBUG;
svc_.log_print = 0;
codec_iface_ = vpx_codec_vp9_cx();
const vpx_codec_err_t res =
vpx_codec_enc_config_default(codec_iface_, &codec_enc_, 0);
EXPECT_EQ(VPX_CODEC_OK, res);
codec_enc_.g_w = kWidth;
codec_enc_.g_h = kHeight;
codec_enc_.g_timebase.num = 1;
codec_enc_.g_timebase.den = 60;
codec_enc_.kf_min_dist = 100;
codec_enc_.kf_max_dist = 100;
vpx_codec_dec_cfg_t dec_cfg = vpx_codec_dec_cfg_t();
VP9CodecFactory codec_factory;
decoder_ = codec_factory.CreateDecoder(dec_cfg, 0);
tile_columns_ = 0;
tile_rows_ = 0;
}
| 174,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
const char *cap_dst, struct wtap_pkthdr *phdr, Buffer* buf,
int *err, gchar **err_info)
{
guint8 *pd;
gchar line[NETSCREEN_LINE_LENGTH];
gchar *p;
int n, i = 0, offset = 0;
gchar dststr[13];
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, NETSCREEN_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if(n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if(offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12396
Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f
Reviewed-on: https://code.wireshark.org/review/15176
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if (n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if (offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
| 167,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: checked_xmalloc (size_t size)
{
alloc_limit_assert ("checked_xmalloc", size);
return xmalloc (size);
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190 | checked_xmalloc (size_t size)
checked_xmalloc (size_t num, size_t size)
{
size_t res;
if (check_mul_overflow(num, size, &res))
abort();
alloc_limit_assert ("checked_xmalloc", res);
return xmalloc (num, size);
}
| 168,357 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void hashtable_clear(hashtable_t *hashtable)
{
size_t i;
hashtable_do_clear(hashtable);
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list_init(&hashtable->list);
hashtable->size = 0;
}
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 | void hashtable_clear(hashtable_t *hashtable)
{
size_t i;
hashtable_do_clear(hashtable);
for(i = 0; i < hashsize(hashtable->order); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list_init(&hashtable->list);
hashtable->size = 0;
}
| 166,527 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
return false;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
return false;
}
| 170,506 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParse3986Port(xmlURIPtr uri, const char **str)
{
const char *cur = *str;
unsigned port = 0; /* unsigned for defined overflow behavior */
if (ISA_DIGIT(cur)) {
while (ISA_DIGIT(cur)) {
port = port * 10 + (*cur - '0');
cur++;
}
if (uri != NULL)
uri->port = port & INT_MAX; /* port value modulo INT_MAX+1 */
*str = cur;
return(0);
}
return(1);
}
Commit Message: DO NOT MERGE: Use correct limit for port values
no upstream report yet, add it here when we have it
issue found & patch by nmehta@
Bug: 36555370
Change-Id: Ibf1efea554b95f514e23e939363d608021de4614
(cherry picked from commit b62884fb49fe92081e414966d9b5fe58250ae53c)
CWE ID: CWE-119 | xmlParse3986Port(xmlURIPtr uri, const char **str)
{
const char *cur = *str;
unsigned port = 0; /* unsigned for defined overflow behavior */
if (ISA_DIGIT(cur)) {
while (ISA_DIGIT(cur)) {
port = port * 10 + (*cur - '0');
cur++;
}
if (uri != NULL)
uri->port = port & USHRT_MAX; /* port value modulo INT_MAX+1 */
*str = cur;
return(0);
}
return(1);
}
| 174,119 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
{
struct fsck_gitmodules_data *data = vdata;
const char *subsection, *key;
int subsection_len;
char *name;
if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
!subsection)
return 0;
name = xmemdupz(subsection, subsection_len);
if (check_submodule_name(name) < 0)
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_NAME,
"disallowed submodule name: %s",
name);
free(name);
return 0;
}
Commit Message: fsck: detect submodule urls starting with dash
Urls with leading dashes can cause mischief on older
versions of Git. We should detect them so that they can be
rejected by receive.fsckObjects, preventing modern versions
of git from being a vector by which attacks can spread.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-20 | static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
{
struct fsck_gitmodules_data *data = vdata;
const char *subsection, *key;
int subsection_len;
char *name;
if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
!subsection)
return 0;
name = xmemdupz(subsection, subsection_len);
if (check_submodule_name(name) < 0)
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_NAME,
"disallowed submodule name: %s",
name);
if (!strcmp(key, "url") && value &&
looks_like_command_line_option(value))
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_URL,
"disallowed submodule url: %s",
value);
free(name);
return 0;
}
| 169,019 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb_cache_entry_release(ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache;
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb2_cache_entry_find_first(ext2_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
ext2_error(inode->i_sb, "ext2_xattr_cache_find",
"inode %ld: block %ld read error",
inode->i_ino, (unsigned long) ce->e_block);
} else {
lock_buffer(bh);
/*
* We have to be careful about races with freeing or
* rehashing of xattr block. Once we hold buffer lock
* xattr block's state is stable so we can check
* whether the block got freed / rehashed or not.
* Since we unhash mbcache entry under buffer lock when
* freeing / rehashing xattr block, checking whether
* entry is still hashed is reliable.
*/
if (hlist_bl_unhashed(&ce->e_hash_list)) {
mb2_cache_entry_put(ext2_mb_cache, ce);
unlock_buffer(bh);
brelse(bh);
goto again;
} else if (le32_to_cpu(HDR(bh)->h_refcount) >
EXT2_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %ld refcount %d>%d",
(unsigned long) ce->e_block,
le32_to_cpu(HDR(bh)->h_refcount),
EXT2_XATTR_REFCOUNT_MAX);
} else if (!ext2_xattr_cmp(header, HDR(bh))) {
ea_bdebug(bh, "b_count=%d",
atomic_read(&(bh->b_count)));
mb2_cache_entry_touch(ext2_mb_cache, ce);
mb2_cache_entry_put(ext2_mb_cache, ce);
return bh;
}
unlock_buffer(bh);
brelse(bh);
}
ce = mb2_cache_entry_find_next(ext2_mb_cache, ce);
}
return NULL;
}
| 169,977 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
asocket* s;
asocket* result = NULL;
adb_mutex_lock(&socket_list_lock);
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->id != local_id) {
continue;
}
if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
result = s;
}
break;
}
adb_mutex_unlock(&socket_list_lock);
return result;
}
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 | asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
asocket* s;
asocket* result = NULL;
std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock);
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->id != local_id) {
continue;
}
if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
result = s;
}
break;
}
return result;
}
| 174,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long keyctl_set_reqkey_keyring(int reqkey_defl)
{
struct cred *new;
int ret, old_setting;
old_setting = current_cred_xxx(jit_keyring);
if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE)
return old_setting;
new = prepare_creds();
if (!new)
return -ENOMEM;
switch (reqkey_defl) {
case KEY_REQKEY_DEFL_THREAD_KEYRING:
ret = install_thread_keyring_to_cred(new);
if (ret < 0)
goto error;
goto set;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
ret = install_process_keyring_to_cred(new);
if (ret < 0) {
if (ret != -EEXIST)
goto error;
ret = 0;
}
goto set;
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_SESSION_KEYRING:
case KEY_REQKEY_DEFL_USER_KEYRING:
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
goto set;
case KEY_REQKEY_DEFL_NO_CHANGE:
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
ret = -EINVAL;
goto error;
}
set:
new->jit_keyring = reqkey_defl;
commit_creds(new);
return old_setting;
error:
abort_creds(new);
return ret;
}
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: [email protected] # 2.6.29+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-404 | long keyctl_set_reqkey_keyring(int reqkey_defl)
{
struct cred *new;
int ret, old_setting;
old_setting = current_cred_xxx(jit_keyring);
if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE)
return old_setting;
new = prepare_creds();
if (!new)
return -ENOMEM;
switch (reqkey_defl) {
case KEY_REQKEY_DEFL_THREAD_KEYRING:
ret = install_thread_keyring_to_cred(new);
if (ret < 0)
goto error;
goto set;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
ret = install_process_keyring_to_cred(new);
if (ret < 0)
goto error;
goto set;
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_SESSION_KEYRING:
case KEY_REQKEY_DEFL_USER_KEYRING:
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
goto set;
case KEY_REQKEY_DEFL_NO_CHANGE:
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
ret = -EINVAL;
goto error;
}
set:
new->jit_keyring = reqkey_defl;
commit_creds(new);
return old_setting;
error:
abort_creds(new);
return ret;
}
| 168,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Encoder::Flush() {
const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0,
deadline_);
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void Encoder::Flush() {
const vpx_codec_err_t res = vpx_codec_encode(&encoder_, NULL, 0, 0, 0,
deadline_);
if (!encoder_.priv)
ASSERT_EQ(VPX_CODEC_ERROR, res) << EncoderError();
else
ASSERT_EQ(VPX_CODEC_OK, res) << EncoderError();
}
| 174,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: static void *listen_fn_(UNUSED_ATTR void *context) {
prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0);
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == -1) {
LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno));
goto cleanup;
}
int enable = 1;
if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
goto cleanup;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(LOCALHOST_);
addr.sin_port = htons(LISTEN_PORT_);
if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno));
goto cleanup;
}
if (listen(listen_socket_, 10) == -1) {
LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno));
goto cleanup;
}
for (;;) {
int client_socket = accept(listen_socket_, NULL, NULL);
if (client_socket == -1) {
if (errno == EINVAL || errno == EBADF) {
break;
}
LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno));
continue;
}
/* When a new client connects, we have to send the btsnoop file header. This allows
a decoder to treat the session as a new, valid btsnoop file. */
pthread_mutex_lock(&client_socket_lock_);
safe_close_(&client_socket_);
client_socket_ = client_socket;
send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0);
pthread_mutex_unlock(&client_socket_lock_);
}
cleanup:
safe_close_(&listen_socket_);
return NULL;
}
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 void *listen_fn_(UNUSED_ATTR void *context) {
prctl(PR_SET_NAME, (unsigned long)LISTEN_THREAD_NAME_, 0, 0, 0);
listen_socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_socket_ == -1) {
LOG_ERROR("%s socket creation failed: %s", __func__, strerror(errno));
goto cleanup;
}
int enable = 1;
if (setsockopt(listen_socket_, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == -1) {
LOG_ERROR("%s unable to set SO_REUSEADDR: %s", __func__, strerror(errno));
goto cleanup;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(LOCALHOST_);
addr.sin_port = htons(LISTEN_PORT_);
if (bind(listen_socket_, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
LOG_ERROR("%s unable to bind listen socket: %s", __func__, strerror(errno));
goto cleanup;
}
if (listen(listen_socket_, 10) == -1) {
LOG_ERROR("%s unable to listen: %s", __func__, strerror(errno));
goto cleanup;
}
for (;;) {
int client_socket = TEMP_FAILURE_RETRY(accept(listen_socket_, NULL, NULL));
if (client_socket == -1) {
if (errno == EINVAL || errno == EBADF) {
break;
}
LOG_WARN("%s error accepting socket: %s", __func__, strerror(errno));
continue;
}
/* When a new client connects, we have to send the btsnoop file header. This allows
a decoder to treat the session as a new, valid btsnoop file. */
pthread_mutex_lock(&client_socket_lock_);
safe_close_(&client_socket_);
client_socket_ = client_socket;
TEMP_FAILURE_RETRY(send(client_socket_, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16, 0));
pthread_mutex_unlock(&client_socket_lock_);
}
cleanup:
safe_close_(&listen_socket_);
return NULL;
}
| 173,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebsiteSettingsPopupView::WebsiteSettingsPopupView(
views::View* anchor_view,
gfx::NativeView parent_window,
Profile* profile,
content::WebContents* web_contents,
const GURL& url,
const content::SSLStatus& ssl)
: BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT),
web_contents_(web_contents),
header_(nullptr),
tabbed_pane_(nullptr),
permissions_tab_(nullptr),
site_data_content_(nullptr),
cookie_dialog_link_(nullptr),
permissions_content_(nullptr),
connection_tab_(nullptr),
identity_info_content_(nullptr),
certificate_dialog_link_(nullptr),
reset_decisions_button_(nullptr),
help_center_content_(nullptr),
cert_id_(0),
help_center_link_(nullptr),
connection_info_content_(nullptr),
weak_factory_(this) {
set_parent_window(parent_window);
set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0,
kLocationIconVerticalMargin, 0));
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
const int content_column = 0;
views::ColumnSet* column_set = layout->AddColumnSet(content_column);
column_set->AddColumn(views::GridLayout::FILL,
views::GridLayout::FILL,
1,
views::GridLayout::USE_PREF,
0,
0);
header_ = new PopupHeaderView(this);
layout->StartRow(1, content_column);
layout->AddView(header_);
layout->AddPaddingRow(1, kHeaderMarginBottom);
tabbed_pane_ = new views::TabbedPane();
layout->StartRow(1, content_column);
layout->AddView(tabbed_pane_);
permissions_tab_ = CreatePermissionsTab();
tabbed_pane_->AddTabAtIndex(
TAB_ID_PERMISSIONS,
l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS),
permissions_tab_);
connection_tab_ = CreateConnectionTab();
tabbed_pane_->AddTabAtIndex(
TAB_ID_CONNECTION,
l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION),
connection_tab_);
DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS);
tabbed_pane_->set_listener(this);
set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft,
kPopupMarginBottom, kPopupMarginRight));
views::BubbleDelegateView::CreateBubble(this);
presenter_.reset(new WebsiteSettings(
this, profile,
TabSpecificContentSettings::FromWebContents(web_contents),
InfoBarService::FromWebContents(web_contents), url, ssl,
content::CertStore::GetInstance()));
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
CWE ID: | WebsiteSettingsPopupView::WebsiteSettingsPopupView(
views::View* anchor_view,
gfx::NativeView parent_window,
Profile* profile,
content::WebContents* web_contents,
const GURL& url,
const content::SSLStatus& ssl)
: content::WebContentsObserver(web_contents),
BubbleDelegateView(anchor_view, views::BubbleBorder::TOP_LEFT),
web_contents_(web_contents),
header_(nullptr),
tabbed_pane_(nullptr),
permissions_tab_(nullptr),
site_data_content_(nullptr),
cookie_dialog_link_(nullptr),
permissions_content_(nullptr),
connection_tab_(nullptr),
identity_info_content_(nullptr),
certificate_dialog_link_(nullptr),
reset_decisions_button_(nullptr),
help_center_content_(nullptr),
cert_id_(0),
help_center_link_(nullptr),
connection_info_content_(nullptr),
weak_factory_(this) {
set_parent_window(parent_window);
set_anchor_view_insets(gfx::Insets(kLocationIconVerticalMargin, 0,
kLocationIconVerticalMargin, 0));
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
const int content_column = 0;
views::ColumnSet* column_set = layout->AddColumnSet(content_column);
column_set->AddColumn(views::GridLayout::FILL,
views::GridLayout::FILL,
1,
views::GridLayout::USE_PREF,
0,
0);
header_ = new PopupHeaderView(this);
layout->StartRow(1, content_column);
layout->AddView(header_);
layout->AddPaddingRow(1, kHeaderMarginBottom);
tabbed_pane_ = new views::TabbedPane();
layout->StartRow(1, content_column);
layout->AddView(tabbed_pane_);
permissions_tab_ = CreatePermissionsTab();
tabbed_pane_->AddTabAtIndex(
TAB_ID_PERMISSIONS,
l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_PERMISSIONS),
permissions_tab_);
connection_tab_ = CreateConnectionTab();
tabbed_pane_->AddTabAtIndex(
TAB_ID_CONNECTION,
l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_TAB_LABEL_CONNECTION),
connection_tab_);
DCHECK_EQ(tabbed_pane_->GetTabCount(), NUM_TAB_IDS);
tabbed_pane_->set_listener(this);
set_margins(gfx::Insets(kPopupMarginTop, kPopupMarginLeft,
kPopupMarginBottom, kPopupMarginRight));
views::BubbleDelegateView::CreateBubble(this);
presenter_.reset(new WebsiteSettings(
this, profile, TabSpecificContentSettings::FromWebContents(web_contents),
web_contents, url, ssl, content::CertStore::GetInstance()));
}
void WebsiteSettingsPopupView::RenderFrameDeleted(
content::RenderFrameHost* render_frame_host) {
if (render_frame_host == web_contents_->GetMainFrame()) {
GetWidget()->Close();
}
}
| 171,779 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
Commit Message: ...
CWE ID: CWE-119 | static int format8BIM(Image *ifile, Image *ofile)
{
char
temp[MagickPathExtent];
unsigned int
foundOSType;
int
ID,
resCount,
i,
c;
ssize_t
count;
unsigned char
*PString,
*str;
resCount=0;
foundOSType=0; /* found the OSType */
(void) foundOSType;
c=ReadBlobByte(ifile);
while (c != EOF)
{
if (c == '8')
{
unsigned char
buffer[5];
buffer[0]=(unsigned char) c;
for (i=1; i<4; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
buffer[i] = (unsigned char) c;
}
buffer[4]=0;
if (strcmp((const char *)buffer, "8BIM") == 0)
foundOSType=1;
else
continue;
}
else
{
c=ReadBlobByte(ifile);
continue;
}
/*
We found the OSType (8BIM) and now grab the ID, PString, and Size fields.
*/
ID=ReadBlobMSBSignedShort(ifile);
if (ID < 0)
return(-1);
{
unsigned char
plen;
c=ReadBlobByte(ifile);
if (c == EOF)
return(-1);
plen = (unsigned char) c;
PString=(unsigned char *) AcquireQuantumMemory((size_t) (plen+
MagickPathExtent),sizeof(*PString));
if (PString == (unsigned char *) NULL)
return 0;
for (i=0; i<plen; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
PString[i] = (unsigned char) c;
}
PString[ plen ] = 0;
if ((plen & 0x01) == 0)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
}
}
count=(ssize_t) ReadBlobMSBSignedLong(ifile);
if ((count < 0) || (count > GetBlobSize(ifile)))
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
/* make a buffer to hold the data and snag it from the input stream */
str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str));
if (str == (unsigned char *) NULL)
{
PString=(unsigned char *) RelinquishMagickMemory(PString);
return 0;
}
for (i=0; i < (ssize_t) count; i++)
{
c=ReadBlobByte(ifile);
if (c == EOF)
{
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
return -1;
}
str[i]=(unsigned char) c;
}
/* we currently skip thumbnails, since it does not make
* any sense preserving them in a real world application
*/
if (ID != THUMBNAIL_ID)
{
/* now finish up by formatting this binary data into
* ASCII equivalent
*/
if (strlen((const char *)PString) > 0)
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d#%s=",ID,
PString);
else
(void) FormatLocaleString(temp,MagickPathExtent,"8BIM#%d=",ID);
(void) WriteBlobString(ofile,temp);
if (ID == IPTC_ID)
{
formatString(ofile, "IPTC", 4);
formatIPTCfromBuffer(ofile, (char *)str, (ssize_t) count);
}
else
formatString(ofile, (char *)str, (ssize_t) count);
}
str=(unsigned char *) RelinquishMagickMemory(str);
PString=(unsigned char *) RelinquishMagickMemory(PString);
resCount++;
c=ReadBlobByte(ifile);
}
return resCount;
}
| 169,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadManagerImpl::CreateNewDownloadItemToStart(
std::unique_ptr<download::DownloadCreateInfo> info,
const download::DownloadUrlParameters::OnStartedCallback& on_started,
download::InProgressDownloadManager::StartDownloadItemCallback callback,
uint32_t id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
download::DownloadItemImpl* download = CreateActiveItem(id, *info);
std::move(callback).Run(std::move(info), download,
should_persist_new_download_);
for (auto& observer : observers_)
observer.OnDownloadCreated(this, download);
OnNewDownloadCreated(download);
OnDownloadStarted(download, on_started);
}
Commit Message: Early return if a download Id is already used when creating a download
This is protect against download Id overflow and use-after-free
issue.
BUG=958533
Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485
Reviewed-by: Xing Liu <[email protected]>
Commit-Queue: Min Qin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#656910}
CWE ID: CWE-416 | void DownloadManagerImpl::CreateNewDownloadItemToStart(
std::unique_ptr<download::DownloadCreateInfo> info,
const download::DownloadUrlParameters::OnStartedCallback& on_started,
download::InProgressDownloadManager::StartDownloadItemCallback callback,
uint32_t id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
download::DownloadItemImpl* download = CreateActiveItem(id, *info);
std::move(callback).Run(std::move(info), download,
should_persist_new_download_);
if (download) {
// For new downloads, we notify here, rather than earlier, so that
// the download_file is bound to download and all the usual
// setters (e.g. Cancel) work.
for (auto& observer : observers_)
observer.OnDownloadCreated(this, download);
OnNewDownloadCreated(download);
}
OnDownloadStarted(download, on_started);
}
| 172,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_stream_temp_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
size_t got;
assert(ts != NULL);
if (!ts->innerstream) {
return -1;
}
got = php_stream_read(ts->innerstream, buf, count);
stream->eof = ts->innerstream->eof;
return got;
}
Commit Message:
CWE ID: CWE-20 | static size_t php_stream_temp_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
size_t got;
assert(ts != NULL);
if (!ts->innerstream) {
return -1;
}
got = php_stream_read(ts->innerstream, buf, count);
stream->eof = ts->innerstream->eof;
return got;
}
| 165,480 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u, max_error)
<< "Error: 16x16 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block , total_error)
<< "Error: 16x16 FHT/IHT has average round trip error > 1 per block";
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const uint32_t diff = dst[j] - src[j];
#endif
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u << 2 * (bit_depth_ - 8), max_error)
<< "Error: 16x16 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block << 2 * (bit_depth_ - 8), total_error)
<< "Error: 16x16 FHT/IHT has average round trip error > 1 per block";
}
| 174,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **retval;
char *key;
uint len;
long index;
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!offset) {
return &EG(uninitialized_zval_ptr);
}
if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return &EG(error_zval_ptr);;
}
switch (Z_TYPE_P(offset)) {
case IS_STRING:
key = Z_STRVAL_P(offset);
len = Z_STRLEN_P(offset) + 1;
string_offest:
if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined index: %s", key);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE,"Undefined index: %s", key);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
case IS_NULL:
key = "";
len = 1;
goto string_offest;
case IS_RESOURCE:
zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset));
case IS_DOUBLE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
default:
zend_error(E_WARNING, "Illegal offset type");
return (type == BP_VAR_W || type == BP_VAR_RW) ?
&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);
}
} /* }}} */
Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray
CWE ID: CWE-20 | static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */
{
spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC);
zval **retval;
char *key;
uint len;
long index;
HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC);
if (!offset || !ht) {
return &EG(uninitialized_zval_ptr);
}
if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) {
zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited");
return &EG(error_zval_ptr);;
}
switch (Z_TYPE_P(offset)) {
case IS_STRING:
key = Z_STRVAL_P(offset);
len = Z_STRLEN_P(offset) + 1;
string_offest:
if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined index: %s", key);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE,"Undefined index: %s", key);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
case IS_NULL:
key = "";
len = 1;
goto string_offest;
case IS_RESOURCE:
zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset));
case IS_DOUBLE:
case IS_BOOL:
case IS_LONG:
if (offset->type == IS_DOUBLE) {
index = (long)Z_DVAL_P(offset);
} else {
index = Z_LVAL_P(offset);
}
if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) {
switch (type) {
case BP_VAR_R:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_UNSET:
case BP_VAR_IS:
retval = &EG(uninitialized_zval_ptr);
break;
case BP_VAR_RW:
zend_error(E_NOTICE, "Undefined offset: %ld", index);
case BP_VAR_W: {
zval *value;
ALLOC_INIT_ZVAL(value);
zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval);
}
}
}
return retval;
default:
zend_error(E_WARNING, "Illegal offset type");
return (type == BP_VAR_W || type == BP_VAR_RW) ?
&EG(error_zval_ptr) : &EG(uninitialized_zval_ptr);
}
} /* }}} */
| 166,931 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeNetworkDelegate::AccumulateContentLength(
int64 received_content_length, int64 original_content_length,
bool via_data_reduction_proxy) {
DCHECK_GE(received_content_length, 0);
DCHECK_GE(original_content_length, 0);
StoreAccumulatedContentLength(received_content_length,
original_content_length,
via_data_reduction_proxy);
received_content_length_ += received_content_length;
original_content_length_ += original_content_length;
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void ChromeNetworkDelegate::AccumulateContentLength(
int64 received_content_length, int64 original_content_length,
chrome_browser_net::DataReductionRequestType data_reduction_type) {
DCHECK_GE(received_content_length, 0);
DCHECK_GE(original_content_length, 0);
StoreAccumulatedContentLength(received_content_length,
original_content_length,
data_reduction_type);
received_content_length_ += received_content_length;
original_content_length_ += original_content_length;
}
| 171,331 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Track::EOSBlock::EOSBlock() :
BlockEntry(NULL, LONG_MIN)
{
}
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 | Track::EOSBlock::EOSBlock() :
| 174,272 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!asoc->temp) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
Commit Message: sctp: Fix sk_ack_backlog wrap-around problem
Consider the scenario:
For a TCP-style socket, while processing the COOKIE_ECHO chunk in
sctp_sf_do_5_1D_ce(), after it has passed a series of sanity check,
a new association would be created in sctp_unpack_cookie(), but afterwards,
some processing maybe failed, and sctp_association_free() will be called to
free the previously allocated association, in sctp_association_free(),
sk_ack_backlog value is decremented for this socket, since the initial
value for sk_ack_backlog is 0, after the decrement, it will be 65535,
a wrap-around problem happens, and if we want to establish new associations
afterward in the same socket, ABORT would be triggered since sctp deem the
accept queue as full.
Fix this issue by only decrementing sk_ack_backlog for associations in
the endpoint's list.
Fix-suggested-by: Neil Horman <[email protected]>
Signed-off-by: Xufeng Zhang <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | void sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!list_empty(&asoc->asocs)) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
| 166,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ComponentControllerImpl::OnNavigationStateChanged(
chromium::web::NavigationStateChangeDetails change,
OnNavigationStateChangedCallback callback) {}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | void ComponentControllerImpl::OnNavigationStateChanged(
| 172,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: pimv1_join_prune_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int ngroups, njoin, nprune;
int njp;
/* If it's a single group and a single source, use 1-line output. */
if (ND_TTEST2(bp[0], 30) && bp[11] == 1 &&
((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) {
int hold;
ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp)));
hold = EXTRACT_16BITS(&bp[6]);
if (hold != 180) {
ND_PRINT((ndo, "Hold "));
unsigned_relts_print(ndo, hold);
}
ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune",
ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f,
ipaddr_string(ndo, &bp[12])));
if (EXTRACT_32BITS(&bp[16]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16])));
ND_PRINT((ndo, ") %s%s %s",
(bp[24] & 0x01) ? "Sparse" : "Dense",
(bp[25] & 0x80) ? " WC" : "",
(bp[25] & 0x40) ? "RP" : "SPT"));
return;
}
ND_TCHECK2(bp[0], sizeof(struct in_addr));
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[6], 2);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Hold time: "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6]));
if (ndo->ndo_vflag < 2)
return;
bp += 8;
len -= 8;
ND_TCHECK2(bp[0], 4);
ngroups = bp[3];
bp += 4;
len -= 4;
while (ngroups--) {
/*
* XXX - does the address have length "addrlen" and the
* mask length "maddrlen"?
*/
ND_TCHECK2(bp[0], sizeof(struct in_addr));
ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp)));
ND_TCHECK2(bp[4], sizeof(struct in_addr));
if (EXTRACT_32BITS(&bp[4]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[4])));
ND_TCHECK2(bp[8], 4);
njoin = EXTRACT_16BITS(&bp[8]);
nprune = EXTRACT_16BITS(&bp[10]);
ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune));
bp += 12;
len -= 12;
for (njp = 0; njp < (njoin + nprune); njp++) {
const char *type;
if (njp < njoin)
type = "Join ";
else
type = "Prune";
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type,
(bp[0] & 0x01) ? "Sparse " : "Dense ",
(bp[1] & 0x80) ? "WC " : "",
(bp[1] & 0x40) ? "RP " : "SPT ",
ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f));
bp += 6;
len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125 | pimv1_join_prune_print(netdissect_options *ndo,
register const u_char *bp, register u_int len)
{
int ngroups, njoin, nprune;
int njp;
/* If it's a single group and a single source, use 1-line output. */
if (ND_TTEST2(bp[0], 30) && bp[11] == 1 &&
((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) {
int hold;
ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp)));
hold = EXTRACT_16BITS(&bp[6]);
if (hold != 180) {
ND_PRINT((ndo, "Hold "));
unsigned_relts_print(ndo, hold);
}
ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune",
ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f,
ipaddr_string(ndo, &bp[12])));
if (EXTRACT_32BITS(&bp[16]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16])));
ND_PRINT((ndo, ") %s%s %s",
(bp[24] & 0x01) ? "Sparse" : "Dense",
(bp[25] & 0x80) ? " WC" : "",
(bp[25] & 0x40) ? "RP" : "SPT"));
return;
}
if (len < sizeof(struct in_addr))
goto trunc;
ND_TCHECK2(bp[0], sizeof(struct in_addr));
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp)));
bp += 4;
len -= 4;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[2], 2);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n"));
ND_PRINT((ndo, " Hold time: "));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
if (ndo->ndo_vflag < 2)
return;
bp += 4;
len -= 4;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], 4);
ngroups = bp[3];
bp += 4;
len -= 4;
while (ngroups--) {
/*
* XXX - does the address have length "addrlen" and the
* mask length "maddrlen"?
*/
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], sizeof(struct in_addr));
ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp)));
bp += 4;
len -= 4;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], sizeof(struct in_addr));
if (EXTRACT_32BITS(&bp[0]) != 0xffffffff)
ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[0])));
bp += 4;
len -= 4;
if (len < 4)
goto trunc;
ND_TCHECK2(bp[0], 4);
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune));
bp += 4;
len -= 4;
for (njp = 0; njp < (njoin + nprune); njp++) {
const char *type;
if (njp < njoin)
type = "Join ";
else
type = "Prune";
if (len < 6)
goto trunc;
ND_TCHECK2(bp[0], 6);
ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type,
(bp[0] & 0x01) ? "Sparse " : "Dense ",
(bp[1] & 0x80) ? "WC " : "",
(bp[1] & 0x40) ? "RP " : "SPT ",
ipaddr_string(ndo, &bp[2]),
bp[1] & 0x3f));
bp += 6;
len -= 6;
}
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
return;
}
| 167,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 transport_accept_nla(rdpTransport* transport)
{
freerdp* instance;
rdpSettings* settings;
if (transport->TlsIn == NULL)
transport->TlsIn = tls_new(transport->settings);
if (transport->TlsOut == NULL)
transport->TlsOut = transport->TlsIn;
transport->layer = TRANSPORT_LAYER_TLS;
transport->TlsIn->sockfd = transport->TcpIn->sockfd;
if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE)
return FALSE;
/* Network Level Authentication */
if (transport->settings->Authentication != TRUE)
return TRUE;
settings = transport->settings;
instance = (freerdp*) settings->instance;
if (transport->credssp == NULL)
transport->credssp = credssp_new(instance, transport, settings);
if (credssp_authenticate(transport->credssp) < 0)
{
fprintf(stderr, "client authentication failure\n");
credssp_free(transport->credssp);
return FALSE;
}
/* don't free credssp module yet, we need to copy the credentials from it first */
return TRUE;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | BOOL transport_accept_nla(rdpTransport* transport)
{
freerdp* instance;
rdpSettings* settings;
if (transport->TlsIn == NULL)
transport->TlsIn = tls_new(transport->settings);
if (transport->TlsOut == NULL)
transport->TlsOut = transport->TlsIn;
transport->layer = TRANSPORT_LAYER_TLS;
transport->TlsIn->sockfd = transport->TcpIn->sockfd;
if (tls_accept(transport->TlsIn, transport->settings->CertificateFile, transport->settings->PrivateKeyFile) != TRUE)
return FALSE;
/* Network Level Authentication */
if (transport->settings->Authentication != TRUE)
return TRUE;
settings = transport->settings;
instance = (freerdp*) settings->instance;
if (transport->credssp == NULL)
transport->credssp = credssp_new(instance, transport, settings);
if (credssp_authenticate(transport->credssp) < 0)
{
fprintf(stderr, "client authentication failure\n");
credssp_free(transport->credssp);
transport->credssp = NULL;
return FALSE;
}
/* don't free credssp module yet, we need to copy the credentials from it first */
return TRUE;
}
| 167,601 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest(
std::unique_ptr<net::URLRequest> url_request,
ResourceContext* resource_context,
download::DownloadUrlParameters* params) {
if (ResourceDispatcherHostImpl::Get()->is_shutdown())
return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN;
ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
url_request.get(),
Referrer(params->referrer(),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
params->referrer_policy())),
true, // download.
params->render_process_host_id(), params->render_view_host_routing_id(),
params->render_frame_host_routing_id(), PREVIEWS_OFF, resource_context);
url_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
const GURL& url = url_request->original_url();
const net::URLRequestContext* request_context = url_request->context();
if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) {
DVLOG(1) << "Download request for unsupported protocol: "
<< url.possibly_invalid_spec();
return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST;
}
std::unique_ptr<ResourceHandler> handler(
DownloadResourceHandler::CreateForNewRequest(
url_request.get(), params->request_origin(),
params->download_source(), params->follow_cross_origin_redirects()));
ResourceDispatcherHostImpl::Get()->BeginURLRequest(
std::move(url_request), std::move(handler), true, // download
params->content_initiated(), params->do_not_prompt_for_login(),
resource_context);
return download::DOWNLOAD_INTERRUPT_REASON_NONE;
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
CWE ID: CWE-284 | download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest(
std::unique_ptr<net::URLRequest> url_request,
ResourceContext* resource_context,
download::DownloadUrlParameters* params) {
if (ResourceDispatcherHostImpl::Get()->is_shutdown())
return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN;
ResourceDispatcherHostImpl::Get()->InitializeURLRequest(
url_request.get(),
Referrer(params->referrer(),
Referrer::NetReferrerPolicyToBlinkReferrerPolicy(
params->referrer_policy())),
true, // download.
params->render_process_host_id(), params->render_view_host_routing_id(),
params->render_frame_host_routing_id(), params->frame_tree_node_id(),
PREVIEWS_OFF, resource_context);
url_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
const GURL& url = url_request->original_url();
const net::URLRequestContext* request_context = url_request->context();
if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) {
DVLOG(1) << "Download request for unsupported protocol: "
<< url.possibly_invalid_spec();
return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST;
}
std::unique_ptr<ResourceHandler> handler(
DownloadResourceHandler::CreateForNewRequest(
url_request.get(), params->request_origin(),
params->download_source(), params->follow_cross_origin_redirects()));
ResourceDispatcherHostImpl::Get()->BeginURLRequest(
std::move(url_request), std::move(handler), true, // download
params->content_initiated(), params->do_not_prompt_for_login(),
resource_context);
return download::DOWNLOAD_INTERRUPT_REASON_NONE;
}
| 173,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Platform::IntPoint InRegionScrollableArea::calculateMinimumScrollPosition(const Platform::IntSize& viewportSize, float overscrollLimitFactor) const
{
ASSERT(!allowsOverscroll());
return Platform::IntPoint(-(viewportSize.width() * overscrollLimitFactor),
-(viewportSize.height() * overscrollLimitFactor));
}
Commit Message: Remove minimum and maximum scroll position as they are no
longer required due to changes in ScrollViewBase.
https://bugs.webkit.org/show_bug.cgi?id=87298
Patch by Genevieve Mak <[email protected]> on 2012-05-23
Reviewed by Antonio Gomes.
* WebKitSupport/InRegionScrollableArea.cpp:
(BlackBerry::WebKit::InRegionScrollableArea::InRegionScrollableArea):
* WebKitSupport/InRegionScrollableArea.h:
(InRegionScrollableArea):
git-svn-id: svn://svn.chromium.org/blink/trunk@118233 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | Platform::IntPoint InRegionScrollableArea::calculateMinimumScrollPosition(const Platform::IntSize& viewportSize, float overscrollLimitFactor) const
| 170,433 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf)
{
if (do_search(pat, 0) == 0)
return 0;
if (pat->not)
mutt_buffer_addstr(buf, "NOT ");
if (pat->child)
{
int clauses;
clauses = do_search(pat->child, 1);
if (clauses > 0)
{
const struct Pattern *clause = pat->child;
mutt_buffer_addch(buf, '(');
while (clauses)
{
if (do_search(clause, 0))
{
if (pat->op == MUTT_OR && clauses > 1)
mutt_buffer_addstr(buf, "OR ");
clauses--;
if (compile_search(ctx, clause, buf) < 0)
return -1;
if (clauses)
mutt_buffer_addch(buf, ' ');
}
clause = clause->next;
}
mutt_buffer_addch(buf, ')');
}
}
else
{
char term[STRING];
char *delim = NULL;
switch (pat->op)
{
case MUTT_HEADER:
mutt_buffer_addstr(buf, "HEADER ");
/* extract header name */
delim = strchr(pat->p.str, ':');
if (!delim)
{
mutt_error(_("Header search without header name: %s"), pat->p.str);
return -1;
}
*delim = '\0';
imap_quote_string(term, sizeof(term), pat->p.str);
mutt_buffer_addstr(buf, term);
mutt_buffer_addch(buf, ' ');
/* and field */
*delim = ':';
delim++;
SKIPWS(delim);
imap_quote_string(term, sizeof(term), delim);
mutt_buffer_addstr(buf, term);
break;
case MUTT_BODY:
mutt_buffer_addstr(buf, "BODY ");
imap_quote_string(term, sizeof(term), pat->p.str);
mutt_buffer_addstr(buf, term);
break;
case MUTT_WHOLE_MSG:
mutt_buffer_addstr(buf, "TEXT ");
imap_quote_string(term, sizeof(term), pat->p.str);
mutt_buffer_addstr(buf, term);
break;
case MUTT_SERVERSEARCH:
{
struct ImapData *idata = ctx->data;
if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1))
{
mutt_error(_("Server-side custom search not supported: %s"), pat->p.str);
return -1;
}
}
mutt_buffer_addstr(buf, "X-GM-RAW ");
imap_quote_string(term, sizeof(term), pat->p.str);
mutt_buffer_addstr(buf, term);
break;
}
}
return 0;
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-77 | static int compile_search(struct Context *ctx, const struct Pattern *pat, struct Buffer *buf)
{
if (do_search(pat, 0) == 0)
return 0;
if (pat->not)
mutt_buffer_addstr(buf, "NOT ");
if (pat->child)
{
int clauses;
clauses = do_search(pat->child, 1);
if (clauses > 0)
{
const struct Pattern *clause = pat->child;
mutt_buffer_addch(buf, '(');
while (clauses)
{
if (do_search(clause, 0))
{
if (pat->op == MUTT_OR && clauses > 1)
mutt_buffer_addstr(buf, "OR ");
clauses--;
if (compile_search(ctx, clause, buf) < 0)
return -1;
if (clauses)
mutt_buffer_addch(buf, ' ');
}
clause = clause->next;
}
mutt_buffer_addch(buf, ')');
}
}
else
{
char term[STRING];
char *delim = NULL;
switch (pat->op)
{
case MUTT_HEADER:
mutt_buffer_addstr(buf, "HEADER ");
/* extract header name */
delim = strchr(pat->p.str, ':');
if (!delim)
{
mutt_error(_("Header search without header name: %s"), pat->p.str);
return -1;
}
*delim = '\0';
imap_quote_string(term, sizeof(term), pat->p.str, false);
mutt_buffer_addstr(buf, term);
mutt_buffer_addch(buf, ' ');
/* and field */
*delim = ':';
delim++;
SKIPWS(delim);
imap_quote_string(term, sizeof(term), delim, false);
mutt_buffer_addstr(buf, term);
break;
case MUTT_BODY:
mutt_buffer_addstr(buf, "BODY ");
imap_quote_string(term, sizeof(term), pat->p.str, false);
mutt_buffer_addstr(buf, term);
break;
case MUTT_WHOLE_MSG:
mutt_buffer_addstr(buf, "TEXT ");
imap_quote_string(term, sizeof(term), pat->p.str, false);
mutt_buffer_addstr(buf, term);
break;
case MUTT_SERVERSEARCH:
{
struct ImapData *idata = ctx->data;
if (!mutt_bit_isset(idata->capabilities, X_GM_EXT1))
{
mutt_error(_("Server-side custom search not supported: %s"), pat->p.str);
return -1;
}
}
mutt_buffer_addstr(buf, "X-GM-RAW ");
imap_quote_string(term, sizeof(term), pat->p.str, false);
mutt_buffer_addstr(buf, term);
break;
}
}
return 0;
}
| 169,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: void FindBarController::Show() {
FindManager* find_manager = tab_contents_->GetFindManager();
if (!find_manager->find_ui_active()) {
MaybeSetPrepopulateText();
find_manager->set_find_ui_active(true);
find_bar_->Show(true);
}
find_bar_->SetFocusAndSelection();
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::Show() {
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
if (!find_tab_helper->find_ui_active()) {
MaybeSetPrepopulateText();
find_tab_helper->set_find_ui_active(true);
find_bar_->Show(true);
}
find_bar_->SetFocusAndSelection();
}
| 170,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InitSkBitmapFromData(SkBitmap* bitmap,
const char* pixels,
size_t pixels_size) const {
if (!bitmap->tryAllocPixels(
SkImageInfo::Make(width, height, color_type, alpha_type)))
return false;
if (pixels_size != bitmap->computeByteSize())
return false;
memcpy(bitmap->getPixels(), pixels, pixels_size);
return true;
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125 | bool InitSkBitmapFromData(SkBitmap* bitmap,
bool ParamTraits<SkImageInfo>::Read(const base::Pickle* m,
base::PickleIterator* iter,
SkImageInfo* r) {
SkColorType color_type;
SkAlphaType alpha_type;
uint32_t width;
uint32_t height;
if (!ReadParam(m, iter, &color_type) || !ReadParam(m, iter, &alpha_type) ||
!ReadParam(m, iter, &width) || !ReadParam(m, iter, &height)) {
return false;
}
| 172,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: cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
Commit Message: CVE-2017-13052/CFM: refine decoding of the Sender ID TLV
In cfm_network_addr_print() add a length argument and use it to validate
the input buffer.
In cfm_print() add a length check for MAC address chassis ID. Supply
cfm_network_addr_print() with the length of its buffer and a correct
pointer to the buffer (it was off-by-one before). Change some error
handling blocks to skip to the next TLV in the current PDU rather than to
stop decoding the PDU. Print the management domain and address contents,
although in hex only so far.
Add some comments to clarify the code flow and to tell exact sections in
IEEE standard documents. Add new error messages and make some existing
messages more specific.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | cfm_network_addr_print(netdissect_options *ndo,
register const u_char *tptr, const u_int length)
{
u_int network_addr_type;
u_int hexdump = FALSE;
/*
* Altough AFIs are tpically 2 octects wide,
* 802.1ab specifies that this field width
* is only once octet
*/
if (length < 1) {
ND_PRINT((ndo, "\n\t Network Address Type (invalid, no data"));
return hexdump;
}
/* The calling function must make any due ND_TCHECK calls. */
network_addr_type = *tptr;
ND_PRINT((ndo, "\n\t Network Address Type %s (%u)",
tok2str(af_values, "Unknown", network_addr_type),
network_addr_type));
/*
* Resolve the passed in Address.
*/
switch(network_addr_type) {
case AFNUM_INET:
if (length != 1 + 4) {
ND_PRINT((ndo, "(invalid IPv4 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr + 1)));
break;
case AFNUM_INET6:
if (length != 1 + 16) {
ND_PRINT((ndo, "(invalid IPv6 address length %u)", length - 1));
hexdump = TRUE;
break;
}
ND_PRINT((ndo, ", %s", ip6addr_string(ndo, tptr + 1)));
break;
default:
hexdump = TRUE;
break;
}
return hexdump;
}
| 167,821 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY ||
(policy == POLICY_NOT_SET &&
profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW)) {
return false;
}
}
return true;
}
Commit Message: Make the content setting for webcam/mic sticky for Pepper requests.
This makes the content setting sticky for webcam/mic requests from Pepper from non-https origins.
BUG=249335
[email protected], [email protected]
Review URL: https://codereview.chromium.org/17060006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@206479 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool MediaStreamDevicesController::IsRequestAllowedByDefault() const {
if (ShouldAlwaysAllowOrigin())
return true;
struct {
bool has_capability;
const char* policy_name;
const char* list_policy_name;
ContentSettingsType settings_type;
} device_checks[] = {
{ microphone_requested_, prefs::kAudioCaptureAllowed,
prefs::kAudioCaptureAllowedUrls, CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC },
{ webcam_requested_, prefs::kVideoCaptureAllowed,
prefs::kVideoCaptureAllowedUrls,
CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(device_checks); ++i) {
if (!device_checks[i].has_capability)
continue;
DevicePolicy policy = GetDevicePolicy(device_checks[i].policy_name,
device_checks[i].list_policy_name);
if (policy == ALWAYS_DENY)
return false;
if (policy == POLICY_NOT_SET) {
// Only load content settings from secure origins unless it is a
// content::MEDIA_OPEN_DEVICE (Pepper) request.
if (!IsSchemeSecure() &&
request_.request_type != content::MEDIA_OPEN_DEVICE) {
return false;
}
if (profile_->GetHostContentSettingsMap()->GetContentSetting(
request_.security_origin, request_.security_origin,
device_checks[i].settings_type, NO_RESOURCE_IDENTIFIER) !=
CONTENT_SETTING_ALLOW) {
return false;
}
}
}
return true;
}
| 171,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 inode_change_ok(const struct inode *inode, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
/*
* First check size constraints. These can't be overriden using
* ATTR_FORCE.
*/
if (ia_valid & ATTR_SIZE) {
int error = inode_newsize_ok(inode, attr->ia_size);
if (error)
return error;
}
/* If force is set do it anyway. */
if (ia_valid & ATTR_FORCE)
return 0;
/* Make sure a caller can chown. */
if ((ia_valid & ATTR_UID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
!uid_eq(attr->ia_uid, inode->i_uid)) &&
!inode_capable(inode, CAP_CHOWN))
return -EPERM;
/* Make sure caller can chgrp. */
if ((ia_valid & ATTR_GID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
(!in_group_p(attr->ia_gid) && !gid_eq(attr->ia_gid, inode->i_gid))) &&
!inode_capable(inode, CAP_CHOWN))
return -EPERM;
/* Make sure a caller can chmod. */
if (ia_valid & ATTR_MODE) {
if (!inode_owner_or_capable(inode))
return -EPERM;
/* Also check the setgid bit! */
if (!in_group_p((ia_valid & ATTR_GID) ? attr->ia_gid :
inode->i_gid) &&
!inode_capable(inode, CAP_FSETID))
attr->ia_mode &= ~S_ISGID;
}
/* Check for setting the inode time. */
if (ia_valid & (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)) {
if (!inode_owner_or_capable(inode))
return -EPERM;
}
return 0;
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | int inode_change_ok(const struct inode *inode, struct iattr *attr)
{
unsigned int ia_valid = attr->ia_valid;
/*
* First check size constraints. These can't be overriden using
* ATTR_FORCE.
*/
if (ia_valid & ATTR_SIZE) {
int error = inode_newsize_ok(inode, attr->ia_size);
if (error)
return error;
}
/* If force is set do it anyway. */
if (ia_valid & ATTR_FORCE)
return 0;
/* Make sure a caller can chown. */
if ((ia_valid & ATTR_UID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
!uid_eq(attr->ia_uid, inode->i_uid)) &&
!capable_wrt_inode_uidgid(inode, CAP_CHOWN))
return -EPERM;
/* Make sure caller can chgrp. */
if ((ia_valid & ATTR_GID) &&
(!uid_eq(current_fsuid(), inode->i_uid) ||
(!in_group_p(attr->ia_gid) && !gid_eq(attr->ia_gid, inode->i_gid))) &&
!capable_wrt_inode_uidgid(inode, CAP_CHOWN))
return -EPERM;
/* Make sure a caller can chmod. */
if (ia_valid & ATTR_MODE) {
if (!inode_owner_or_capable(inode))
return -EPERM;
/* Also check the setgid bit! */
if (!in_group_p((ia_valid & ATTR_GID) ? attr->ia_gid :
inode->i_gid) &&
!capable_wrt_inode_uidgid(inode, CAP_FSETID))
attr->ia_mode &= ~S_ISGID;
}
/* Check for setting the inode time. */
if (ia_valid & (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET)) {
if (!inode_owner_or_capable(inode))
return -EPERM;
}
return 0;
}
| 166,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: int cipso_v4_req_setattr(struct request_sock *req,
const struct cipso_v4_doi *doi_def,
const struct netlbl_lsm_secattr *secattr)
{
int ret_val = -EPERM;
unsigned char *buf = NULL;
u32 buf_len;
u32 opt_len;
struct ip_options *opt = NULL;
struct inet_request_sock *req_inet;
/* We allocate the maximum CIPSO option size here so we are probably
* being a little wasteful, but it makes our life _much_ easier later
* on and after all we are only talking about 40 bytes. */
buf_len = CIPSO_V4_OPT_LEN_MAX;
buf = kmalloc(buf_len, GFP_ATOMIC);
if (buf == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
if (ret_val < 0)
goto req_setattr_failure;
buf_len = ret_val;
/* We can't use ip_options_get() directly because it makes a call to
* ip_options_get_alloc() which allocates memory with GFP_KERNEL and
* we won't always have CAP_NET_RAW even though we _always_ want to
* set the IPOPT_CIPSO option. */
opt_len = (buf_len + 3) & ~3;
opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
if (opt == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
memcpy(opt->__data, buf, buf_len);
opt->optlen = opt_len;
opt->cipso = sizeof(struct iphdr);
kfree(buf);
buf = NULL;
req_inet = inet_rsk(req);
opt = xchg(&req_inet->opt, opt);
kfree(opt);
return 0;
req_setattr_failure:
kfree(buf);
kfree(opt);
return ret_val;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int cipso_v4_req_setattr(struct request_sock *req,
const struct cipso_v4_doi *doi_def,
const struct netlbl_lsm_secattr *secattr)
{
int ret_val = -EPERM;
unsigned char *buf = NULL;
u32 buf_len;
u32 opt_len;
struct ip_options_rcu *opt = NULL;
struct inet_request_sock *req_inet;
/* We allocate the maximum CIPSO option size here so we are probably
* being a little wasteful, but it makes our life _much_ easier later
* on and after all we are only talking about 40 bytes. */
buf_len = CIPSO_V4_OPT_LEN_MAX;
buf = kmalloc(buf_len, GFP_ATOMIC);
if (buf == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr);
if (ret_val < 0)
goto req_setattr_failure;
buf_len = ret_val;
/* We can't use ip_options_get() directly because it makes a call to
* ip_options_get_alloc() which allocates memory with GFP_KERNEL and
* we won't always have CAP_NET_RAW even though we _always_ want to
* set the IPOPT_CIPSO option. */
opt_len = (buf_len + 3) & ~3;
opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC);
if (opt == NULL) {
ret_val = -ENOMEM;
goto req_setattr_failure;
}
memcpy(opt->opt.__data, buf, buf_len);
opt->opt.optlen = opt_len;
opt->opt.cipso = sizeof(struct iphdr);
kfree(buf);
buf = NULL;
req_inet = inet_rsk(req);
opt = xchg(&req_inet->opt, opt);
if (opt)
call_rcu(&opt->rcu, opt_kfree_rcu);
return 0;
req_setattr_failure:
kfree(buf);
kfree(opt);
return ret_val;
}
| 165,548 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_expand_16_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
/* Expect expand_16 to expand everything to 16 bits as a result of also
* causing 'expand' to happen.
*/
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
if (that->have_tRNS)
image_pixel_add_alpha(that, &display->this);
if (that->bit_depth < 16)
that->sample_depth = that->bit_depth = 16;
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_expand_16_mod(PNG_CONST image_transform *this,
image_transform_png_set_expand_16_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* Expect expand_16 to expand everything to 16 bits as a result of also
* causing 'expand' to happen.
*/
if (that->colour_type == PNG_COLOR_TYPE_PALETTE)
image_pixel_convert_PLTE(that);
if (that->have_tRNS)
image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
if (that->bit_depth < 16)
that->sample_depth = that->bit_depth = 16;
this->next->mod(this->next, that, pp, display);
}
| 173,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Block::IsKey() const
{
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | bool Block::IsKey() const
void Block::SetKey(bool bKey) {
if (bKey)
m_flags |= static_cast<unsigned char>(1 << 7);
else
m_flags &= 0x7F;
}
| 174,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DECLAREwriteFunc(writeBufferToContigTiles)
{
uint32 imagew = TIFFScanlineSize(out);
uint32 tilew = TIFFTileRowSize(out);
int iskew = imagew - tilew;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
(void) spp;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
for (row = 0; row < imagelength; row += tilelength) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth; col += tw) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = imagew - colb;
int oskew = tilew - width;
cpStripToTile(obuf, bufp + colb, nrow, width,
oskew, oskew + iskew);
} else
cpStripToTile(obuf, bufp + colb, nrow, tilew,
0, iskew);
if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
_TIFFfree(obuf);
return 0;
}
colb += tilew;
}
bufp += nrow * imagew;
}
_TIFFfree(obuf);
return 1;
}
Commit Message: * tools/tiffcp.c: fix out-of-bounds write on tiled images with odd
tile width vs image width. Reported as MSVR 35103
by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
CWE ID: CWE-787 | DECLAREwriteFunc(writeBufferToContigTiles)
{
uint32 imagew = TIFFScanlineSize(out);
uint32 tilew = TIFFTileRowSize(out);
int iskew = imagew - tilew;
tsize_t tilesize = TIFFTileSize(out);
tdata_t obuf;
uint8* bufp = (uint8*) buf;
uint32 tl, tw;
uint32 row;
(void) spp;
obuf = _TIFFmalloc(TIFFTileSize(out));
if (obuf == NULL)
return 0;
_TIFFmemset(obuf, 0, tilesize);
(void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl);
(void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw);
for (row = 0; row < imagelength; row += tilelength) {
uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl;
uint32 colb = 0;
uint32 col;
for (col = 0; col < imagewidth && colb < imagew; col += tw) {
/*
* Tile is clipped horizontally. Calculate
* visible portion and skewing factors.
*/
if (colb + tilew > imagew) {
uint32 width = imagew - colb;
int oskew = tilew - width;
cpStripToTile(obuf, bufp + colb, nrow, width,
oskew, oskew + iskew);
} else
cpStripToTile(obuf, bufp + colb, nrow, tilew,
0, iskew);
if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) {
TIFFError(TIFFFileName(out),
"Error, can't write tile at %lu %lu",
(unsigned long) col,
(unsigned long) row);
_TIFFfree(obuf);
return 0;
}
colb += tilew;
}
bufp += nrow * imagew;
}
_TIFFfree(obuf);
return 1;
}
| 166,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: static sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) {
SkImageInfo info = SkImageInfo::Make(input->width(), input->height(),
kN32_SkColorType, kUnpremul_SkAlphaType);
RefPtr<Uint8Array> dstPixels = copySkImageData(input, info);
if (!dstPixels)
return nullptr;
return newSkImageFromRaster(
info, std::move(dstPixels),
static_cast<size_t>(input->width()) * info.bytesPerPixel());
}
Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull
Currently when ImageBitmap's constructor is invoked, we check whether
dstSize will overflow size_t or not. The problem comes when we call
ArrayBuffer::createOrNull some times in the code.
Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap
when we call this method, the first parameter is usually width * height.
This could overflow unsigned even if it has been checked safe with size_t,
the reason is that unsigned is a 32-bit value on 64-bit systems, while
size_t is a 64-bit value.
This CL makes a change such that we check whether the dstSize will overflow
unsigned or not. In this case, we can guarantee that createOrNull will not have
any crash.
BUG=664139
Review-Url: https://codereview.chromium.org/2500493002
Cr-Commit-Position: refs/heads/master@{#431936}
CWE ID: CWE-787 | static sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) {
SkImageInfo info = SkImageInfo::Make(input->width(), input->height(),
kN32_SkColorType, kUnpremul_SkAlphaType);
RefPtr<Uint8Array> dstPixels = copySkImageData(input, info);
if (!dstPixels)
return nullptr;
return newSkImageFromRaster(
info, std::move(dstPixels),
static_cast<unsigned>(input->width()) * info.bytesPerPixel());
}
| 172,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintPreviewUI::OnCancelPendingPreviewRequest() {
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewUI::OnCancelPendingPreviewRequest() {
g_print_preview_request_id_map.Get().Set(id_, -1);
}
| 170,836 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CMD_FUNC(m_authenticate)
{
aClient *agent_p = NULL;
/* Failing to use CAP REQ for sasl is a protocol violation. */
if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL))
return 0;
if (sptr->local->sasl_complete)
{
sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (strlen(parv[1]) > 400)
{
sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (*sptr->local->sasl_agent)
agent_p = find_client(sptr->local->sasl_agent, NULL);
if (agent_p == NULL)
{
char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip;
char *certfp = moddata_client_get(sptr, "certfp");
sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s",
me.name, SASL_SERVER, encode_puid(sptr), addr, addr);
if (certfp)
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp);
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1]);
}
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s",
me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]);
sptr->local->sasl_out++;
return 0;
}
Commit Message: Fix AUTHENTICATE bug
CWE ID: CWE-287 | CMD_FUNC(m_authenticate)
{
aClient *agent_p = NULL;
/* Failing to use CAP REQ for sasl is a protocol violation. */
if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL))
return 0;
if (sptr->local->sasl_complete)
{
sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if ((parv[1][0] == ':') || strchr(parv[1], ' '))
{
sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, "*", "AUTHENTICATE", "Invalid parameter");
return 0;
}
if (strlen(parv[1]) > 400)
{
sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (*sptr->local->sasl_agent)
agent_p = find_client(sptr->local->sasl_agent, NULL);
if (agent_p == NULL)
{
char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip;
char *certfp = moddata_client_get(sptr, "certfp");
sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s",
me.name, SASL_SERVER, encode_puid(sptr), addr, addr);
if (certfp)
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp);
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1]);
}
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s",
me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]);
sptr->local->sasl_out++;
return 0;
}
| 168,814 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sk_buff **udp_gro_receive(struct sk_buff **head, struct sk_buff *skb,
struct udphdr *uh)
{
struct udp_offload_priv *uo_priv;
struct sk_buff *p, **pp = NULL;
struct udphdr *uh2;
unsigned int off = skb_gro_offset(skb);
int flush = 1;
if (NAPI_GRO_CB(skb)->udp_mark ||
(skb->ip_summed != CHECKSUM_PARTIAL &&
NAPI_GRO_CB(skb)->csum_cnt == 0 &&
!NAPI_GRO_CB(skb)->csum_valid))
goto out;
/* mark that this skb passed once through the udp gro layer */
NAPI_GRO_CB(skb)->udp_mark = 1;
rcu_read_lock();
uo_priv = rcu_dereference(udp_offload_base);
for (; uo_priv != NULL; uo_priv = rcu_dereference(uo_priv->next)) {
if (net_eq(read_pnet(&uo_priv->net), dev_net(skb->dev)) &&
uo_priv->offload->port == uh->dest &&
uo_priv->offload->callbacks.gro_receive)
goto unflush;
}
goto out_unlock;
unflush:
flush = 0;
for (p = *head; p; p = p->next) {
if (!NAPI_GRO_CB(p)->same_flow)
continue;
uh2 = (struct udphdr *)(p->data + off);
/* Match ports and either checksums are either both zero
* or nonzero.
*/
if ((*(u32 *)&uh->source != *(u32 *)&uh2->source) ||
(!uh->check ^ !uh2->check)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
skb_gro_pull(skb, sizeof(struct udphdr)); /* pull encapsulating udp header */
skb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr));
NAPI_GRO_CB(skb)->proto = uo_priv->offload->ipproto;
pp = uo_priv->offload->callbacks.gro_receive(head, skb,
uo_priv->offload);
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400 | struct sk_buff **udp_gro_receive(struct sk_buff **head, struct sk_buff *skb,
struct udphdr *uh)
{
struct udp_offload_priv *uo_priv;
struct sk_buff *p, **pp = NULL;
struct udphdr *uh2;
unsigned int off = skb_gro_offset(skb);
int flush = 1;
if (NAPI_GRO_CB(skb)->encap_mark ||
(skb->ip_summed != CHECKSUM_PARTIAL &&
NAPI_GRO_CB(skb)->csum_cnt == 0 &&
!NAPI_GRO_CB(skb)->csum_valid))
goto out;
/* mark that this skb passed once through the tunnel gro layer */
NAPI_GRO_CB(skb)->encap_mark = 1;
rcu_read_lock();
uo_priv = rcu_dereference(udp_offload_base);
for (; uo_priv != NULL; uo_priv = rcu_dereference(uo_priv->next)) {
if (net_eq(read_pnet(&uo_priv->net), dev_net(skb->dev)) &&
uo_priv->offload->port == uh->dest &&
uo_priv->offload->callbacks.gro_receive)
goto unflush;
}
goto out_unlock;
unflush:
flush = 0;
for (p = *head; p; p = p->next) {
if (!NAPI_GRO_CB(p)->same_flow)
continue;
uh2 = (struct udphdr *)(p->data + off);
/* Match ports and either checksums are either both zero
* or nonzero.
*/
if ((*(u32 *)&uh->source != *(u32 *)&uh2->source) ||
(!uh->check ^ !uh2->check)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
skb_gro_pull(skb, sizeof(struct udphdr)); /* pull encapsulating udp header */
skb_gro_postpull_rcsum(skb, uh, sizeof(struct udphdr));
NAPI_GRO_CB(skb)->proto = uo_priv->offload->ipproto;
pp = uo_priv->offload->callbacks.gro_receive(head, skb,
uo_priv->offload);
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
| 166,907 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
return touchpad_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | TouchpadLibrary* CrosLibrary::GetTouchpadLibrary() {
| 170,633 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
bool result = m->ReadData(iter, &data, &data_size);
if (result && data_size == sizeof(LOGFONT)) {
memcpy(r, data, sizeof(LOGFONT));
} else {
result = false;
NOTREACHED();
}
return result;
}
Commit Message: Verify lfFaceName is NUL terminated in IPC deserializer.
BUG=162066
Review URL: https://chromiumcodereview.appspot.com/11416115
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168937 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ParamTraits<LOGFONT>::Read(const Message* m, PickleIterator* iter,
param_type* r) {
const char *data;
int data_size = 0;
if (m->ReadData(iter, &data, &data_size) && data_size == sizeof(LOGFONT)) {
const LOGFONT *font = reinterpret_cast<LOGFONT*>(const_cast<char*>(data));
if (_tcsnlen(font->lfFaceName, LF_FACESIZE) < LF_FACESIZE) {
memcpy(r, data, sizeof(LOGFONT));
return true;
}
}
NOTREACHED();
return false;
}
| 171,588 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
lock_mount_hash();
mnt_flags |= mnt->mnt.mnt_flags & MNT_PROPAGATION_MASK;
mnt->mnt.mnt_flags = mnt_flags;
touch_mnt_namespace(mnt->mnt_ns);
unlock_mount_hash();
}
up_write(&sb->s_umount);
return err;
}
Commit Message: mnt: Only change user settable mount flags in remount
Kenton Varda <[email protected]> discovered that by remounting a
read-only bind mount read-only in a user namespace the
MNT_LOCK_READONLY bit would be cleared, allowing an unprivileged user
to the remount a read-only mount read-write.
Correct this by replacing the mask of mount flags to preserve
with a mask of mount flags that may be changed, and preserve
all others. This ensures that any future bugs with this mask and
remount will fail in an easy to detect way where new mount flags
simply won't change.
Cc: [email protected]
Acked-by: Serge E. Hallyn <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-264 | static int do_remount(struct path *path, int flags, int mnt_flags,
void *data)
{
int err;
struct super_block *sb = path->mnt->mnt_sb;
struct mount *mnt = real_mount(path->mnt);
if (!check_mnt(mnt))
return -EINVAL;
if (path->dentry != path->mnt->mnt_root)
return -EINVAL;
err = security_sb_remount(sb, data);
if (err)
return err;
down_write(&sb->s_umount);
if (flags & MS_BIND)
err = change_mount_flags(path->mnt, flags);
else if (!capable(CAP_SYS_ADMIN))
err = -EPERM;
else
err = do_remount_sb(sb, flags, data, 0);
if (!err) {
lock_mount_hash();
mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK;
mnt->mnt.mnt_flags = mnt_flags;
touch_mnt_namespace(mnt->mnt_ns);
unlock_mount_hash();
}
up_write(&sb->s_umount);
return err;
}
| 166,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
pthread_mutex_lock(&lock);
config_save(config, CONFIG_FILE_PATH);
pthread_mutex_unlock(&lock);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119 | void btif_config_flush(void) {
assert(config != NULL);
assert(alarm_timer != NULL);
alarm_cancel(alarm_timer);
btif_config_write();
}
| 173,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long cs;
int cpl = ctxt->ops->cpl(ctxt);
rc = emulate_pop(ctxt, &ctxt->_eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
if (ctxt->op_bytes == 4)
ctxt->_eip = (u32)ctxt->_eip;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS);
return rc;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_ret_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned long eip, cs;
u16 old_cs;
int cpl = ctxt->ops->cpl(ctxt);
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_cs, &old_desc, NULL,
VCPU_SREG_CS);
rc = emulate_pop(ctxt, &eip, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = emulate_pop(ctxt, &cs, ctxt->op_bytes);
if (rc != X86EMUL_CONTINUE)
return rc;
/* Outer-privilege level return is not implemented */
if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl)
return X86EMUL_UNHANDLEABLE;
rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, eip, new_desc.l);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64);
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
}
return rc;
}
| 166,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 validation_gamma(int argc, char **argv)
{
double gamma[9] = { 2.2, 1.8, 1.52, 1.45, 1., 1/1.45, 1/1.52, 1/1.8, 1/2.2 };
double maxerr;
int i, silent=0, onlygamma=0;
/* Silence the output with -s, just test the gamma functions with -g: */
while (--argc > 0)
if (strcmp(*++argv, "-s") == 0)
silent = 1;
else if (strcmp(*argv, "-g") == 0)
onlygamma = 1;
else
{
fprintf(stderr, "unknown argument %s\n", *argv);
return 1;
}
if (!onlygamma)
{
/* First validate the log functions: */
maxerr = 0;
for (i=0; i<256; ++i)
{
double correct = -log(i/255.)/log(2.)*65536;
double error = png_log8bit(i) - correct;
if (i != 0 && fabs(error) > maxerr)
maxerr = fabs(error);
if (i == 0 && png_log8bit(i) != 0xffffffff ||
i != 0 && png_log8bit(i) != floor(correct+.5))
{
fprintf(stderr, "8 bit log error: %d: got %u, expected %f\n",
i, png_log8bit(i), correct);
}
}
if (!silent)
printf("maximum 8 bit log error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<65536; ++i)
{
double correct = -log(i/65535.)/log(2.)*65536;
double error = png_log16bit(i) - correct;
if (i != 0 && fabs(error) > maxerr)
maxerr = fabs(error);
if (i == 0 && png_log16bit(i) != 0xffffffff ||
i != 0 && png_log16bit(i) != floor(correct+.5))
{
if (error > .68) /* By experiment error is less than .68 */
{
fprintf(stderr, "16 bit log error: %d: got %u, expected %f"
" error: %f\n", i, png_log16bit(i), correct, error);
}
}
}
if (!silent)
printf("maximum 16 bit log error = %f\n", maxerr);
/* Now exponentiations. */
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * (65536. * 65536);
double error = png_exp(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > 1883) /* By experiment. */
{
fprintf(stderr, "32 bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp(i), correct, error);
}
}
if (!silent)
printf("maximum 32 bit exp error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * 255;
double error = png_exp8bit(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > .50002) /* By experiment */
{
fprintf(stderr, "8 bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp8bit(i), correct, error);
}
}
if (!silent)
printf("maximum 8 bit exp error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * 65535;
double error = png_exp16bit(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > .524) /* By experiment */
{
fprintf(stderr, "16 bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp16bit(i), correct, error);
}
}
if (!silent)
printf("maximum 16 bit exp error = %f\n", maxerr);
} /* !onlygamma */
/* Test the overall gamma correction. */
for (i=0; i<9; ++i)
{
unsigned j;
double g = gamma[i];
png_fixed_point gfp = floor(g * PNG_FP_1 + .5);
if (!silent)
printf("Test gamma %f\n", g);
maxerr = 0;
for (j=0; j<256; ++j)
{
double correct = pow(j/255., g) * 255;
png_byte out = png_gamma_8bit_correct(j, gfp);
double error = out - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (out != floor(correct+.5))
{
fprintf(stderr, "8bit %d ^ %f: got %d expected %f error %f\n",
j, g, out, correct, error);
}
}
if (!silent)
printf("gamma %f: maximum 8 bit error %f\n", g, maxerr);
maxerr = 0;
for (j=0; j<65536; ++j)
{
double correct = pow(j/65535., g) * 65535;
png_uint_16 out = png_gamma_16bit_correct(j, gfp);
double error = out - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > 1.62)
{
fprintf(stderr, "16bit %d ^ %f: got %d expected %f error %f\n",
j, g, out, correct, error);
}
}
if (!silent)
printf("gamma %f: maximum 16 bit error %f\n", g, maxerr);
}
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | int validation_gamma(int argc, char **argv)
{
double gamma[9] = { 2.2, 1.8, 1.52, 1.45, 1., 1/1.45, 1/1.52, 1/1.8, 1/2.2 };
double maxerr;
int i, silent=0, onlygamma=0;
/* Silence the output with -s, just test the gamma functions with -g: */
while (--argc > 0)
if (strcmp(*++argv, "-s") == 0)
silent = 1;
else if (strcmp(*argv, "-g") == 0)
onlygamma = 1;
else
{
fprintf(stderr, "unknown argument %s\n", *argv);
return 1;
}
if (!onlygamma)
{
/* First validate the log functions: */
maxerr = 0;
for (i=0; i<256; ++i)
{
double correct = -log(i/255.)/log(2.)*65536;
double error = png_log8bit(i) - correct;
if (i != 0 && fabs(error) > maxerr)
maxerr = fabs(error);
if (i == 0 && png_log8bit(i) != 0xffffffff ||
i != 0 && png_log8bit(i) != floor(correct+.5))
{
fprintf(stderr, "8-bit log error: %d: got %u, expected %f\n",
i, png_log8bit(i), correct);
}
}
if (!silent)
printf("maximum 8-bit log error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<65536; ++i)
{
double correct = -log(i/65535.)/log(2.)*65536;
double error = png_log16bit(i) - correct;
if (i != 0 && fabs(error) > maxerr)
maxerr = fabs(error);
if (i == 0 && png_log16bit(i) != 0xffffffff ||
i != 0 && png_log16bit(i) != floor(correct+.5))
{
if (error > .68) /* By experiment error is less than .68 */
{
fprintf(stderr, "16-bit log error: %d: got %u, expected %f"
" error: %f\n", i, png_log16bit(i), correct, error);
}
}
}
if (!silent)
printf("maximum 16-bit log error = %f\n", maxerr);
/* Now exponentiations. */
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * (65536. * 65536);
double error = png_exp(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > 1883) /* By experiment. */
{
fprintf(stderr, "32-bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp(i), correct, error);
}
}
if (!silent)
printf("maximum 32-bit exp error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * 255;
double error = png_exp8bit(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > .50002) /* By experiment */
{
fprintf(stderr, "8-bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp8bit(i), correct, error);
}
}
if (!silent)
printf("maximum 8-bit exp error = %f\n", maxerr);
maxerr = 0;
for (i=0; i<=0xfffff; ++i)
{
double correct = exp(-i/65536. * log(2.)) * 65535;
double error = png_exp16bit(i) - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > .524) /* By experiment */
{
fprintf(stderr, "16-bit exp error: %d: got %u, expected %f"
" error: %f\n", i, png_exp16bit(i), correct, error);
}
}
if (!silent)
printf("maximum 16-bit exp error = %f\n", maxerr);
} /* !onlygamma */
/* Test the overall gamma correction. */
for (i=0; i<9; ++i)
{
unsigned j;
double g = gamma[i];
png_fixed_point gfp = floor(g * PNG_FP_1 + .5);
if (!silent)
printf("Test gamma %f\n", g);
maxerr = 0;
for (j=0; j<256; ++j)
{
double correct = pow(j/255., g) * 255;
png_byte out = png_gamma_8bit_correct(j, gfp);
double error = out - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (out != floor(correct+.5))
{
fprintf(stderr, "8bit %d ^ %f: got %d expected %f error %f\n",
j, g, out, correct, error);
}
}
if (!silent)
printf("gamma %f: maximum 8-bit error %f\n", g, maxerr);
maxerr = 0;
for (j=0; j<65536; ++j)
{
double correct = pow(j/65535., g) * 65535;
png_uint_16 out = png_gamma_16bit_correct(j, gfp);
double error = out - correct;
if (fabs(error) > maxerr)
maxerr = fabs(error);
if (fabs(error) > 1.62)
{
fprintf(stderr, "16bit %d ^ %f: got %d expected %f error %f\n",
j, g, out, correct, error);
}
}
if (!silent)
printf("gamma %f: maximum 16-bit error %f\n", g, maxerr);
}
return 0;
}
| 173,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheUpdateJob::OnManifestDataWriteComplete(int result) {
if (result > 0) {
AppCacheEntry entry(AppCacheEntry::MANIFEST,
manifest_response_writer_->response_id(),
manifest_response_writer_->amount_written());
if (!inprogress_cache_->AddOrModifyEntry(manifest_url_, entry))
duplicate_response_ids_.push_back(entry.response_id());
StoreGroupAndCache();
} else {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
"Failed to write the manifest data to storage",
blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(),
0, false /*is_cross_origin*/),
DISKCACHE_ERROR, GURL());
}
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCacheUpdateJob::OnManifestDataWriteComplete(int result) {
if (result > 0) {
// The manifest determines the cache's origin, so the manifest entry is
// always same-origin, and thus does not require padding.
AppCacheEntry entry(AppCacheEntry::MANIFEST,
manifest_response_writer_->response_id(),
manifest_response_writer_->amount_written(),
/*padding_size=*/0);
if (!inprogress_cache_->AddOrModifyEntry(manifest_url_, entry))
duplicate_response_ids_.push_back(entry.response_id());
StoreGroupAndCache();
} else {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
"Failed to write the manifest data to storage",
blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(),
0, false /*is_cross_origin*/),
DISKCACHE_ERROR, GURL());
}
}
| 172,997 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
else
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
else
#endif /* ECP_SHORTWEIERSTRASS */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
cleanup:
if( ret != 0 )
return( ret );
return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_size = ( grp->nbits + 7 ) / 8;
#if defined(ECP_MONTGOMERY)
if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
{
/* [M225] page 5 */
size_t b;
do {
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
} while( mbedtls_mpi_bitlen( d ) == 0);
/* Make sure the most significant bit is nbits */
b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
if( b > grp->nbits )
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
else
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
/* Make sure the last three bits are unset */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
#endif /* ECP_MONTGOMERY */
#if defined(ECP_SHORTWEIERSTRASS)
if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
{
/* SEC1 3.2.1: Generate d such that 1 <= n < N */
int count = 0;
/*
* Match the procedure given in RFC 6979 (deterministic ECDSA):
* - use the same byte ordering;
* - keep the leftmost nbits bits of the generated octet string;
* - try until result is in the desired range.
* This also avoids any biais, which is especially important for ECDSA.
*/
do
{
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
/*
* Each try has at worst a probability 1/2 of failing (the msb has
* a probability 1/2 of being 0, and then the result will be < N),
* so after 30 tries failure probability is a most 2**(-30).
*
* For most curves, 1 try is enough with overwhelming probability,
* since N starts with a lot of 1s in binary, but some curves
* such as secp224k1 are actually very close to the worst case.
*/
if( ++count > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
}
#endif /* ECP_SHORTWEIERSTRASS */
cleanup:
return( ret );
}
/*
* Generate a keypair with configurable base point
*/
int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
cleanup:
return( ret );
}
| 170,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GLboolean WebGL2RenderingContextBase::isVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost() || !vertex_array)
return 0;
if (!vertex_array->HasEverBeenBound())
return 0;
return ContextGL()->IsVertexArrayOES(vertex_array->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119 | GLboolean WebGL2RenderingContextBase::isVertexArray(
WebGLVertexArrayObject* vertex_array) {
if (isContextLost() || !vertex_array ||
!vertex_array->Validate(ContextGroup(), this))
return 0;
if (!vertex_array->HasEverBeenBound())
return 0;
return ContextGL()->IsVertexArrayOES(vertex_array->Object());
}
| 173,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: print_pixel(png_structp png_ptr, png_infop info_ptr, png_const_bytep row,
png_uint_32 x)
{
PNG_CONST unsigned int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
switch (png_get_color_type(png_ptr, info_ptr))
{
case PNG_COLOR_TYPE_GRAY:
printf("GRAY %u\n", component(row, x, 0, bit_depth, 1));
return;
/* The palette case is slightly more difficult - the palette and, if
* present, the tRNS ('transparency', though the values are really
* opacity) data must be read to give the full picture:
*/
case PNG_COLOR_TYPE_PALETTE:
{
PNG_CONST unsigned int index = component(row, x, 0, bit_depth, 1);
png_colorp palette = NULL;
int num_palette = 0;
if ((png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette) &
PNG_INFO_PLTE) && num_palette > 0 && palette != NULL)
{
png_bytep trans_alpha = NULL;
int num_trans = 0;
if ((png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans,
NULL) & PNG_INFO_tRNS) && num_trans > 0 &&
trans_alpha != NULL)
printf("INDEXED %u = %d %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue,
index < num_trans ? trans_alpha[index] : 255);
else /* no transparency */
printf("INDEXED %u = %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue);
}
else
printf("INDEXED %u = invalid index\n", index);
}
return;
case PNG_COLOR_TYPE_RGB:
printf("RGB %u %u %u\n", component(row, x, 0, bit_depth, 3),
component(row, x, 1, bit_depth, 3),
component(row, x, 2, bit_depth, 3));
return;
case PNG_COLOR_TYPE_GRAY_ALPHA:
printf("GRAY+ALPHA %u %u\n", component(row, x, 0, bit_depth, 2),
component(row, x, 1, bit_depth, 2));
return;
case PNG_COLOR_TYPE_RGB_ALPHA:
printf("RGBA %u %u %u %u\n", component(row, x, 0, bit_depth, 4),
component(row, x, 1, bit_depth, 4),
component(row, x, 2, bit_depth, 4),
component(row, x, 3, bit_depth, 4));
return;
default:
png_error(png_ptr, "pngpixel: invalid color type");
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | print_pixel(png_structp png_ptr, png_infop info_ptr, png_const_bytep row,
png_uint_32 x)
{
PNG_CONST unsigned int bit_depth = png_get_bit_depth(png_ptr, info_ptr);
switch (png_get_color_type(png_ptr, info_ptr))
{
case PNG_COLOR_TYPE_GRAY:
printf("GRAY %u\n", component(row, x, 0, bit_depth, 1));
return;
/* The palette case is slightly more difficult - the palette and, if
* present, the tRNS ('transparency', though the values are really
* opacity) data must be read to give the full picture:
*/
case PNG_COLOR_TYPE_PALETTE:
{
PNG_CONST int index = component(row, x, 0, bit_depth, 1);
png_colorp palette = NULL;
int num_palette = 0;
if ((png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette) &
PNG_INFO_PLTE) && num_palette > 0 && palette != NULL)
{
png_bytep trans_alpha = NULL;
int num_trans = 0;
if ((png_get_tRNS(png_ptr, info_ptr, &trans_alpha, &num_trans,
NULL) & PNG_INFO_tRNS) && num_trans > 0 &&
trans_alpha != NULL)
printf("INDEXED %u = %d %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue,
index < num_trans ? trans_alpha[index] : 255);
else /* no transparency */
printf("INDEXED %u = %d %d %d\n", index,
palette[index].red, palette[index].green,
palette[index].blue);
}
else
printf("INDEXED %u = invalid index\n", index);
}
return;
case PNG_COLOR_TYPE_RGB:
printf("RGB %u %u %u\n", component(row, x, 0, bit_depth, 3),
component(row, x, 1, bit_depth, 3),
component(row, x, 2, bit_depth, 3));
return;
case PNG_COLOR_TYPE_GRAY_ALPHA:
printf("GRAY+ALPHA %u %u\n", component(row, x, 0, bit_depth, 2),
component(row, x, 1, bit_depth, 2));
return;
case PNG_COLOR_TYPE_RGB_ALPHA:
printf("RGBA %u %u %u %u\n", component(row, x, 0, bit_depth, 4),
component(row, x, 1, bit_depth, 4),
component(row, x, 2, bit_depth, 4),
component(row, x, 3, bit_depth, 4));
return;
default:
png_error(png_ptr, "pngpixel: invalid color type");
}
}
| 173,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tower_probe (struct usb_interface *interface, const struct usb_device_id *id)
{
struct device *idev = &interface->dev;
struct usb_device *udev = interface_to_usbdev(interface);
struct lego_usb_tower *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor* endpoint;
struct tower_get_version_reply get_version_reply;
int i;
int retval = -ENOMEM;
int result;
/* allocate memory for our device state and initialize it */
dev = kmalloc (sizeof(struct lego_usb_tower), GFP_KERNEL);
if (!dev)
goto exit;
mutex_init(&dev->lock);
dev->udev = udev;
dev->open_count = 0;
dev->read_buffer = NULL;
dev->read_buffer_length = 0;
dev->read_packet_length = 0;
spin_lock_init (&dev->read_buffer_lock);
dev->packet_timeout_jiffies = msecs_to_jiffies(packet_timeout);
dev->read_last_arrival = jiffies;
init_waitqueue_head (&dev->read_wait);
init_waitqueue_head (&dev->write_wait);
dev->interrupt_in_buffer = NULL;
dev->interrupt_in_endpoint = NULL;
dev->interrupt_in_urb = NULL;
dev->interrupt_in_running = 0;
dev->interrupt_in_done = 0;
dev->interrupt_out_buffer = NULL;
dev->interrupt_out_endpoint = NULL;
dev->interrupt_out_urb = NULL;
dev->interrupt_out_busy = 0;
iface_desc = interface->cur_altsetting;
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_xfer_int(endpoint)) {
if (usb_endpoint_dir_in(endpoint))
dev->interrupt_in_endpoint = endpoint;
else
dev->interrupt_out_endpoint = endpoint;
}
}
if(dev->interrupt_in_endpoint == NULL) {
dev_err(idev, "interrupt in endpoint not found\n");
goto error;
}
if (dev->interrupt_out_endpoint == NULL) {
dev_err(idev, "interrupt out endpoint not found\n");
goto error;
}
dev->read_buffer = kmalloc (read_buffer_size, GFP_KERNEL);
if (!dev->read_buffer)
goto error;
dev->interrupt_in_buffer = kmalloc (usb_endpoint_maxp(dev->interrupt_in_endpoint), GFP_KERNEL);
if (!dev->interrupt_in_buffer)
goto error;
dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_in_urb)
goto error;
dev->interrupt_out_buffer = kmalloc (write_buffer_size, GFP_KERNEL);
if (!dev->interrupt_out_buffer)
goto error;
dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_out_urb)
goto error;
dev->interrupt_in_interval = interrupt_in_interval ? interrupt_in_interval : dev->interrupt_in_endpoint->bInterval;
dev->interrupt_out_interval = interrupt_out_interval ? interrupt_out_interval : dev->interrupt_out_endpoint->bInterval;
/* we can register the device now, as it is ready */
usb_set_intfdata (interface, dev);
retval = usb_register_dev (interface, &tower_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(idev, "Not able to get a minor for this device.\n");
usb_set_intfdata (interface, NULL);
goto error;
}
dev->minor = interface->minor;
/* let the user know what node this device is now attached to */
dev_info(&interface->dev, "LEGO USB Tower #%d now attached to major "
"%d minor %d\n", (dev->minor - LEGO_USB_TOWER_MINOR_BASE),
USB_MAJOR, dev->minor);
/* get the firmware version and log it */
result = usb_control_msg (udev,
usb_rcvctrlpipe(udev, 0),
LEGO_USB_TOWER_REQUEST_GET_VERSION,
USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
0,
0,
&get_version_reply,
sizeof(get_version_reply),
1000);
if (result < 0) {
dev_err(idev, "LEGO USB Tower get version control request failed\n");
retval = result;
goto error;
}
dev_info(&interface->dev, "LEGO USB Tower firmware version is %d.%d "
"build %d\n", get_version_reply.major,
get_version_reply.minor,
le16_to_cpu(get_version_reply.build_no));
exit:
return retval;
error:
tower_delete(dev);
return retval;
}
Commit Message: usb: misc: legousbtower: Fix NULL pointer deference
This patch fixes a NULL pointer dereference caused by a race codition in
the probe function of the legousbtower driver. It re-structures the
probe function to only register the interface after successfully reading
the board's firmware ID.
The probe function does not deregister the usb interface after an error
receiving the devices firmware ID. The device file registered
(/dev/usb/legousbtower%d) may be read/written globally before the probe
function returns. When tower_delete is called in the probe function
(after an r/w has been initiated), core dev structures are deleted while
the file operation functions are still running. If the 0 address is
mappable on the machine, this vulnerability can be used to create a
Local Priviege Escalation exploit via a write-what-where condition by
remapping dev->interrupt_out_buffer in tower_write. A forged USB device
and local program execution would be required for LPE. The USB device
would have to delay the control message in tower_probe and accept
the control urb in tower_open whilst guest code initiated a write to the
device file as tower_delete is called from the error in tower_probe.
This bug has existed since 2003. Patch tested by emulated device.
Reported-by: James Patrick-Evans <[email protected]>
Tested-by: James Patrick-Evans <[email protected]>
Signed-off-by: James Patrick-Evans <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-476 | static int tower_probe (struct usb_interface *interface, const struct usb_device_id *id)
{
struct device *idev = &interface->dev;
struct usb_device *udev = interface_to_usbdev(interface);
struct lego_usb_tower *dev = NULL;
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor* endpoint;
struct tower_get_version_reply get_version_reply;
int i;
int retval = -ENOMEM;
int result;
/* allocate memory for our device state and initialize it */
dev = kmalloc (sizeof(struct lego_usb_tower), GFP_KERNEL);
if (!dev)
goto exit;
mutex_init(&dev->lock);
dev->udev = udev;
dev->open_count = 0;
dev->read_buffer = NULL;
dev->read_buffer_length = 0;
dev->read_packet_length = 0;
spin_lock_init (&dev->read_buffer_lock);
dev->packet_timeout_jiffies = msecs_to_jiffies(packet_timeout);
dev->read_last_arrival = jiffies;
init_waitqueue_head (&dev->read_wait);
init_waitqueue_head (&dev->write_wait);
dev->interrupt_in_buffer = NULL;
dev->interrupt_in_endpoint = NULL;
dev->interrupt_in_urb = NULL;
dev->interrupt_in_running = 0;
dev->interrupt_in_done = 0;
dev->interrupt_out_buffer = NULL;
dev->interrupt_out_endpoint = NULL;
dev->interrupt_out_urb = NULL;
dev->interrupt_out_busy = 0;
iface_desc = interface->cur_altsetting;
/* set up the endpoint information */
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (usb_endpoint_xfer_int(endpoint)) {
if (usb_endpoint_dir_in(endpoint))
dev->interrupt_in_endpoint = endpoint;
else
dev->interrupt_out_endpoint = endpoint;
}
}
if(dev->interrupt_in_endpoint == NULL) {
dev_err(idev, "interrupt in endpoint not found\n");
goto error;
}
if (dev->interrupt_out_endpoint == NULL) {
dev_err(idev, "interrupt out endpoint not found\n");
goto error;
}
dev->read_buffer = kmalloc (read_buffer_size, GFP_KERNEL);
if (!dev->read_buffer)
goto error;
dev->interrupt_in_buffer = kmalloc (usb_endpoint_maxp(dev->interrupt_in_endpoint), GFP_KERNEL);
if (!dev->interrupt_in_buffer)
goto error;
dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_in_urb)
goto error;
dev->interrupt_out_buffer = kmalloc (write_buffer_size, GFP_KERNEL);
if (!dev->interrupt_out_buffer)
goto error;
dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
if (!dev->interrupt_out_urb)
goto error;
dev->interrupt_in_interval = interrupt_in_interval ? interrupt_in_interval : dev->interrupt_in_endpoint->bInterval;
dev->interrupt_out_interval = interrupt_out_interval ? interrupt_out_interval : dev->interrupt_out_endpoint->bInterval;
/* get the firmware version and log it */
result = usb_control_msg (udev,
usb_rcvctrlpipe(udev, 0),
LEGO_USB_TOWER_REQUEST_GET_VERSION,
USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
0,
0,
&get_version_reply,
sizeof(get_version_reply),
1000);
if (result < 0) {
dev_err(idev, "LEGO USB Tower get version control request failed\n");
retval = result;
goto error;
}
dev_info(&interface->dev, "LEGO USB Tower firmware version is %d.%d "
"build %d\n", get_version_reply.major,
get_version_reply.minor,
le16_to_cpu(get_version_reply.build_no));
/* we can register the device now, as it is ready */
usb_set_intfdata (interface, dev);
retval = usb_register_dev (interface, &tower_class);
if (retval) {
/* something prevented us from registering this driver */
dev_err(idev, "Not able to get a minor for this device.\n");
usb_set_intfdata (interface, NULL);
goto error;
}
dev->minor = interface->minor;
/* let the user know what node this device is now attached to */
dev_info(&interface->dev, "LEGO USB Tower #%d now attached to major "
"%d minor %d\n", (dev->minor - LEGO_USB_TOWER_MINOR_BASE),
USB_MAJOR, dev->minor);
exit:
return retval;
error:
tower_delete(dev);
return retval;
}
| 167,737 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476 | on_unregister_handler(TCMUService1HandlerManager1 *interface,
GDBusMethodInvocation *invocation,
gchar *subtype,
gpointer user_data)
{
struct tcmur_handler *handler = find_handler_by_subtype(subtype);
struct dbus_info *info = handler ? handler->opaque : NULL;
if (!handler) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"unknown subtype"));
return TRUE;
}
else if (handler->_is_dbus_handler != 1) {
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", FALSE,
"cannot unregister internal handler"));
return TRUE;
}
dbus_unexport_handler(handler);
tcmur_unregister_dbus_handler(handler);
g_bus_unwatch_name(info->watcher_id);
g_free(info);
g_free(handler);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(bs)", TRUE, "succeeded"));
return TRUE;
}
| 167,634 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunRoundTripErrorCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < 64; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
for (int j = 0; j < 64; ++j) {
if (test_temp_block[j] > 0) {
test_temp_block[j] += 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
} else {
test_temp_block[j] -= 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
}
}
REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < 64; ++j) {
const int diff = dst[j] - src[j];
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1, max_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual"
<< " roundtrip error > 1";
EXPECT_GE(count_test_block/5, total_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip "
<< "error > 1/5 per block";
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunRoundTripErrorCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
int max_error = 0;
int total_error = 0;
const int count_test_block = 100000;
DECLARE_ALIGNED(16, int16_t, test_input_block[64]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]);
DECLARE_ALIGNED(16, uint8_t, dst[64]);
DECLARE_ALIGNED(16, uint8_t, src[64]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[64]);
DECLARE_ALIGNED(16, uint16_t, src16[64]);
#endif
for (int i = 0; i < count_test_block; ++i) {
// Initialize a test block with input range [-mask_, mask_].
for (int j = 0; j < 64; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(
RunFwdTxfm(test_input_block, test_temp_block, pitch_));
for (int j = 0; j < 64; ++j) {
if (test_temp_block[j] > 0) {
test_temp_block[j] += 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
} else {
test_temp_block[j] -= 2;
test_temp_block[j] /= 4;
test_temp_block[j] *= 4;
}
}
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(
RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < 64; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const int diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
const int diff = dst[j] - src[j];
#endif
const int error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has an individual"
<< " roundtrip error > 1";
EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error)
<< "Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip "
<< "error > 1/5 per block";
}
| 174,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags)
{
/*
* Protect the call to nfs4_state_set_mode_locked and
* serialise the stateid update
*/
write_seqlock(&state->seqlock);
if (deleg_stateid != NULL) {
memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data));
set_bit(NFS_DELEGATED_STATE, &state->flags);
}
if (open_stateid != NULL)
nfs_set_open_stateid_locked(state, open_stateid, open_flags);
write_sequnlock(&state->seqlock);
spin_lock(&state->owner->so_lock);
update_open_stateflags(state, open_flags);
spin_unlock(&state->owner->so_lock);
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags)
static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode)
{
/*
* Protect the call to nfs4_state_set_mode_locked and
* serialise the stateid update
*/
write_seqlock(&state->seqlock);
if (deleg_stateid != NULL) {
memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data));
set_bit(NFS_DELEGATED_STATE, &state->flags);
}
if (open_stateid != NULL)
nfs_set_open_stateid_locked(state, open_stateid, fmode);
write_sequnlock(&state->seqlock);
spin_lock(&state->owner->so_lock);
update_open_stateflags(state, fmode);
spin_unlock(&state->owner->so_lock);
}
| 165,683 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
if (!pairing_delegate_used_)
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_NONE,
UMA_PAIRING_METHOD_COUNT);
UnregisterAgent();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::OnPair(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Paired";
pairing_context_.reset();
SetTrusted();
ConnectInternal(true, callback, error_callback);
}
| 171,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
while (!pending_queries_.empty()) {
const PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty());
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | error::Error GLES2DecoderPassthroughImpl::ProcessQueries(bool did_finish) {
bool program_completion_query_deferred = false;
while (!pending_queries_.empty()) {
PendingQuery& query = pending_queries_.front();
GLuint result_available = GL_FALSE;
GLuint64 result = 0;
switch (query.target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
DCHECK(query.commands_completed_fence != nullptr);
result_available =
did_finish || query.commands_completed_fence->HasCompleted();
result = result_available;
break;
case GL_COMMANDS_ISSUED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
break;
case GL_LATENCY_QUERY_CHROMIUM:
result_available = GL_TRUE;
result = (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds();
break;
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
result_available = GL_TRUE;
result = GL_TRUE;
for (const PendingReadPixels& pending_read_pixels :
pending_read_pixels_) {
if (pending_read_pixels.waiting_async_pack_queries.count(
query.service_id) > 0) {
DCHECK(!did_finish);
result_available = GL_FALSE;
result = GL_FALSE;
break;
}
}
break;
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
DCHECK(query.buffer_shadow_update_fence);
if (did_finish || query.buffer_shadow_update_fence->HasCompleted()) {
ReadBackBuffersIntoShadowCopies(query.buffer_shadow_updates);
result_available = GL_TRUE;
result = 0;
}
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
result_available = GL_TRUE;
FlushErrors();
result = PopError();
break;
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
GLint status;
if (!api()->glIsProgramFn(query.program_service_id)) {
status = GL_TRUE;
} else {
api()->glGetProgramivFn(query.program_service_id,
GL_COMPLETION_STATUS_KHR, &status);
}
result_available = (status == GL_TRUE);
if (!result_available) {
// Move the query to the end of queue, so that other queries may have
// chance to be processed.
auto temp = std::move(query);
pending_queries_.pop_front();
pending_queries_.emplace_back(std::move(temp));
if (did_finish && !OnlyHasPendingProgramCompletionQueries()) {
continue;
} else {
program_completion_query_deferred = true;
}
}
result = 0;
break;
default:
DCHECK(!IsEmulatedQueryTarget(query.target));
if (did_finish) {
result_available = GL_TRUE;
} else {
api()->glGetQueryObjectuivFn(
query.service_id, GL_QUERY_RESULT_AVAILABLE, &result_available);
}
if (result_available == GL_TRUE) {
if (feature_info_->feature_flags().ext_disjoint_timer_query) {
api()->glGetQueryObjectui64vFn(query.service_id, GL_QUERY_RESULT,
&result);
} else {
GLuint temp_result = 0;
api()->glGetQueryObjectuivFn(query.service_id, GL_QUERY_RESULT,
&temp_result);
result = temp_result;
}
}
break;
}
if (!result_available) {
break;
}
query.sync->result = result;
base::subtle::Release_Store(&query.sync->process_count, query.submit_count);
pending_queries_.pop_front();
}
DCHECK(!did_finish || pending_queries_.empty() ||
program_completion_query_deferred);
return error::kNoError;
}
| 172,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UserActivityDetector::MaybeNotify() {
base::TimeTicks now = base::TimeTicks::Now();
if (last_observer_notification_time_.is_null() ||
(now - last_observer_notification_time_).InSecondsF() >=
kNotifyIntervalSec) {
FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity());
last_observer_notification_time_ = now;
}
}
Commit Message: ash: Make UserActivityDetector ignore synthetic mouse events
This may have been preventing us from suspending (e.g.
mouse event is synthesized in response to lock window being
shown so Chrome tells powerd that the user is active).
BUG=133419
TEST=added
Review URL: https://chromiumcodereview.appspot.com/10574044
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143437 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | void UserActivityDetector::MaybeNotify() {
base::TimeTicks now =
!now_for_test_.is_null() ? now_for_test_ : base::TimeTicks::Now();
if (last_observer_notification_time_.is_null() ||
(now - last_observer_notification_time_).InSecondsF() >=
kNotifyIntervalSec) {
FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity());
last_observer_notification_time_ = now;
}
}
| 170,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: int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
Commit Message: bug #248, fix Out-Of-Bounds Read in read_image_tga
CWE ID: CWE-125 | int read_image_tga( gdIOCtx *ctx, oTga *tga )
{
int pixel_block_size = (tga->bits / 8);
int image_block_size = (tga->width * tga->height) * pixel_block_size;
uint8_t* decompression_buffer = NULL;
unsigned char* conversion_buffer = NULL;
int buffer_caret = 0;
int bitmap_caret = 0;
int i = 0;
int j = 0;
uint8_t encoded_pixels;
if(overflow2(tga->width, tga->height)) {
return -1;
}
if(overflow2(tga->width * tga->height, pixel_block_size)) {
return -1;
}
if(overflow2(image_block_size, sizeof(int))) {
return -1;
}
/*! \todo Add more image type support.
*/
if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE)
return -1;
/*! \brief Allocate memmory for image block
* Allocate a chunk of memory for the image block to be passed into.
*/
tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int));
if (tga->bitmap == NULL)
return -1;
switch (tga->imagetype) {
case TGA_TYPE_RGB:
/*! \brief Read in uncompressed RGB TGA
* Chunk load the pixel data from an uncompressed RGB type TGA.
*/
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gd_error("gd-tga: premature end of image data\n");
gdFree(conversion_buffer);
return -1;
}
while (buffer_caret < image_block_size) {
tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret];
buffer_caret++;
}
gdFree(conversion_buffer);
break;
case TGA_TYPE_RGB_RLE:
/*! \brief Read in RLE compressed RGB TGA
* Chunk load the pixel data from an RLE compressed RGB type TGA.
*/
decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t));
if (decompression_buffer == NULL) {
return -1;
}
conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char));
if (conversion_buffer == NULL) {
gd_error("gd-tga: premature end of image data\n");
gdFree( decompression_buffer );
return -1;
}
if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) {
gdFree(conversion_buffer);
gdFree(decompression_buffer);
return -1;
}
buffer_caret = 0;
while( buffer_caret < image_block_size) {
decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret];
buffer_caret++;
}
buffer_caret = 0;
while( bitmap_caret < image_block_size ) {
if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) {
encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 );
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for (j = 0; j < pixel_block_size; j++, bitmap_caret++) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
}
}
buffer_caret += pixel_block_size;
} else {
encoded_pixels = decompression_buffer[ buffer_caret ] + 1;
buffer_caret++;
if (encoded_pixels != 0) {
if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) {
gdFree( decompression_buffer );
gdFree( conversion_buffer );
return -1;
}
for (i = 0; i < encoded_pixels; i++) {
for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) {
tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ];
}
buffer_caret += pixel_block_size;
}
}
}
}
gdFree( decompression_buffer );
gdFree( conversion_buffer );
break;
}
return 1;
}
| 169,942 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __usb_get_extra_descriptor(char *buffer, unsigned size,
unsigned char type, void **ptr)
{
struct usb_descriptor_header *header;
while (size >= sizeof(struct usb_descriptor_header)) {
header = (struct usb_descriptor_header *)buffer;
if (header->bLength < 2) {
printk(KERN_ERR
"%s: bogus descriptor, type %d length %d\n",
usbcore_name,
header->bDescriptorType,
header->bLength);
return -1;
}
if (header->bDescriptorType == type) {
*ptr = header;
return 0;
}
buffer += header->bLength;
size -= header->bLength;
}
return -1;
}
Commit Message: USB: check usb_get_extra_descriptor for proper size
When reading an extra descriptor, we need to properly check the minimum
and maximum size allowed, to prevent from invalid data being sent by a
device.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Co-developed-by: Linus Torvalds <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Signed-off-by: Mathias Payer <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400 | int __usb_get_extra_descriptor(char *buffer, unsigned size,
unsigned char type, void **ptr, size_t minsize)
{
struct usb_descriptor_header *header;
while (size >= sizeof(struct usb_descriptor_header)) {
header = (struct usb_descriptor_header *)buffer;
if (header->bLength < 2 || header->bLength > size) {
printk(KERN_ERR
"%s: bogus descriptor, type %d length %d\n",
usbcore_name,
header->bDescriptorType,
header->bLength);
return -1;
}
if (header->bDescriptorType == type && header->bLength >= minsize) {
*ptr = header;
return 0;
}
buffer += header->bLength;
size -= header->bLength;
}
return -1;
}
| 168,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
{
char *str;
ASN1_TIME atm;
long offset;
char buff1[24], buff2[24], *p;
int i, j;
p = buff1;
i = ctm->length;
str = (char *)ctm->data;
if (ctm->type == V_ASN1_UTCTIME) {
if ((i < 11) || (i > 17))
return 0;
memcpy(p, str, 10);
p += 10;
str += 10;
} else {
if (i < 13)
return 0;
memcpy(p, str, 12);
p += 12;
str += 12;
}
if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
*(p++) = '0';
*(p++) = '0';
} else {
*(p++) = *(str++);
*(p++) = *(str++);
/* Skip any fractional seconds... */
if (*str == '.') {
str++;
while ((*str >= '0') && (*str <= '9'))
str++;
}
}
*(p++) = 'Z';
*(p++) = '\0';
if (*str == 'Z')
offset = 0;
else {
if ((*str != '+') && (*str != '-'))
return 0;
offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
offset += (str[3] - '0') * 10 + (str[4] - '0');
if (*str == '-')
offset = -offset;
}
atm.type = ctm->type;
atm.flags = 0;
atm.length = sizeof(buff2);
atm.data = (unsigned char *)buff2;
if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
return 0;
if (ctm->type == V_ASN1_UTCTIME) {
i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
if (i < 50)
i += 100; /* cf. RFC 2459 */
j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
if (j < 50)
j += 100;
if (i < j)
return -1;
if (i > j)
return 1;
}
i = strcmp(buff1, buff2);
if (i == 0) /* wait a second then return younger :-) */
return -1;
else
return i;
}
Commit Message: Fix length checks in X509_cmp_time to avoid out-of-bounds reads.
Also tighten X509_cmp_time to reject more than three fractional
seconds in the time; and to reject trailing garbage after the offset.
CVE-2015-1789
Reviewed-by: Viktor Dukhovni <[email protected]>
Reviewed-by: Richard Levitte <[email protected]>
CWE ID: CWE-119 | int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time)
{
char *str;
ASN1_TIME atm;
long offset;
char buff1[24], buff2[24], *p;
int i, j, remaining;
p = buff1;
remaining = ctm->length;
str = (char *)ctm->data;
/*
* Note that the following (historical) code allows much more slack in the
* time format than RFC5280. In RFC5280, the representation is fixed:
* UTCTime: YYMMDDHHMMSSZ
* GeneralizedTime: YYYYMMDDHHMMSSZ
*/
if (ctm->type == V_ASN1_UTCTIME) {
/* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */
int min_length = sizeof("YYMMDDHHMMZ") - 1;
int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1;
if (remaining < min_length || remaining > max_length)
return 0;
memcpy(p, str, 10);
p += 10;
str += 10;
remaining -= 10;
} else {
/* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */
int min_length = sizeof("YYYYMMDDHHMMZ") - 1;
int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1;
if (remaining < min_length || remaining > max_length)
return 0;
memcpy(p, str, 12);
p += 12;
str += 12;
remaining -= 12;
}
if ((*str == 'Z') || (*str == '-') || (*str == '+')) {
*(p++) = '0';
*(p++) = '0';
} else {
/* SS (seconds) */
if (remaining < 2)
return 0;
*(p++) = *(str++);
*(p++) = *(str++);
remaining -= 2;
/*
* Skip any (up to three) fractional seconds...
* TODO(emilia): in RFC5280, fractional seconds are forbidden.
* Can we just kill them altogether?
*/
if (remaining && *str == '.') {
str++;
remaining--;
for (i = 0; i < 3 && remaining; i++, str++, remaining--) {
if (*str < '0' || *str > '9')
break;
}
}
}
*(p++) = 'Z';
*(p++) = '\0';
/* We now need either a terminating 'Z' or an offset. */
if (!remaining)
return 0;
if (*str == 'Z') {
if (remaining != 1)
return 0;
offset = 0;
} else {
/* (+-)HHMM */
if ((*str != '+') && (*str != '-'))
return 0;
/* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */
if (remaining != 5)
return 0;
if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' ||
str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9')
return 0;
offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60;
offset += (str[3] - '0') * 10 + (str[4] - '0');
if (*str == '-')
offset = -offset;
}
atm.type = ctm->type;
atm.flags = 0;
atm.length = sizeof(buff2);
atm.data = (unsigned char *)buff2;
if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL)
return 0;
if (ctm->type == V_ASN1_UTCTIME) {
i = (buff1[0] - '0') * 10 + (buff1[1] - '0');
if (i < 50)
i += 100; /* cf. RFC 2459 */
j = (buff2[0] - '0') * 10 + (buff2[1] - '0');
if (j < 50)
j += 100;
if (i < j)
return -1;
if (i > j)
return 1;
}
i = strcmp(buff1, buff2);
if (i == 0) /* wait a second then return younger :-) */
return -1;
else
return i;
}
| 166,693 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dccp_packet(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, enum ip_conntrack_info ctinfo,
u_int8_t pf, unsigned int hooknum,
unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
struct dccp_hdr _dh, *dh;
u_int8_t type, old_state, new_state;
enum ct_dccp_roles role;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
BUG_ON(dh == NULL);
type = dh->dccph_type;
if (type == DCCP_PKT_RESET &&
!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* Tear down connection immediately if only reply is a RESET */
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
spin_lock_bh(&ct->lock);
role = ct->proto.dccp.role[dir];
old_state = ct->proto.dccp.state;
new_state = dccp_state_table[role][type][old_state];
switch (new_state) {
case CT_DCCP_REQUEST:
if (old_state == CT_DCCP_TIMEWAIT &&
role == CT_DCCP_ROLE_SERVER) {
/* Reincarnation in the reverse direction: reopen and
* reverse client/server roles. */
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER;
}
break;
case CT_DCCP_RESPOND:
if (old_state == CT_DCCP_REQUEST)
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
break;
case CT_DCCP_PARTOPEN:
if (old_state == CT_DCCP_RESPOND &&
type == DCCP_PKT_ACK &&
dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq)
set_bit(IPS_ASSURED_BIT, &ct->status);
break;
case CT_DCCP_IGNORE:
/*
* Connection tracking might be out of sync, so we ignore
* packets that might establish a new connection and resync
* if the server responds with a valid Response.
*/
if (ct->proto.dccp.last_dir == !dir &&
ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST &&
type == DCCP_PKT_RESPONSE) {
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
new_state = CT_DCCP_RESPOND;
break;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid packet ignored ");
return NF_ACCEPT;
case CT_DCCP_INVALID:
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid state transition ");
return -NF_ACCEPT;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
ct->proto.dccp.state = new_state;
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]);
return NF_ACCEPT;
}
Commit Message: netfilter: nf_conntrack_dccp: fix skb_header_pointer API usages
Some occurences in the netfilter tree use skb_header_pointer() in
the following way ...
struct dccp_hdr _dh, *dh;
...
skb_header_pointer(skb, dataoff, sizeof(_dh), &dh);
... where dh itself is a pointer that is being passed as the copy
buffer. Instead, we need to use &_dh as the forth argument so that
we're copying the data into an actual buffer that sits on the stack.
Currently, we probably could overwrite memory on the stack (e.g.
with a possibly mal-formed DCCP packet), but unintentionally, as
we only want the buffer to be placed into _dh variable.
Fixes: 2bc780499aa3 ("[NETFILTER]: nf_conntrack: add DCCP protocol support")
Signed-off-by: Daniel Borkmann <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-20 | static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb,
unsigned int dataoff, enum ip_conntrack_info ctinfo,
u_int8_t pf, unsigned int hooknum,
unsigned int *timeouts)
{
struct net *net = nf_ct_net(ct);
enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo);
struct dccp_hdr _dh, *dh;
u_int8_t type, old_state, new_state;
enum ct_dccp_roles role;
dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh);
BUG_ON(dh == NULL);
type = dh->dccph_type;
if (type == DCCP_PKT_RESET &&
!test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
/* Tear down connection immediately if only reply is a RESET */
nf_ct_kill_acct(ct, ctinfo, skb);
return NF_ACCEPT;
}
spin_lock_bh(&ct->lock);
role = ct->proto.dccp.role[dir];
old_state = ct->proto.dccp.state;
new_state = dccp_state_table[role][type][old_state];
switch (new_state) {
case CT_DCCP_REQUEST:
if (old_state == CT_DCCP_TIMEWAIT &&
role == CT_DCCP_ROLE_SERVER) {
/* Reincarnation in the reverse direction: reopen and
* reverse client/server roles. */
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER;
}
break;
case CT_DCCP_RESPOND:
if (old_state == CT_DCCP_REQUEST)
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
break;
case CT_DCCP_PARTOPEN:
if (old_state == CT_DCCP_RESPOND &&
type == DCCP_PKT_ACK &&
dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq)
set_bit(IPS_ASSURED_BIT, &ct->status);
break;
case CT_DCCP_IGNORE:
/*
* Connection tracking might be out of sync, so we ignore
* packets that might establish a new connection and resync
* if the server responds with a valid Response.
*/
if (ct->proto.dccp.last_dir == !dir &&
ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST &&
type == DCCP_PKT_RESPONSE) {
ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT;
ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER;
ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh);
new_state = CT_DCCP_RESPOND;
break;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid packet ignored ");
return NF_ACCEPT;
case CT_DCCP_INVALID:
spin_unlock_bh(&ct->lock);
if (LOG_INVALID(net, IPPROTO_DCCP))
nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL,
"nf_ct_dccp: invalid state transition ");
return -NF_ACCEPT;
}
ct->proto.dccp.last_dir = dir;
ct->proto.dccp.last_pkt = type;
ct->proto.dccp.state = new_state;
spin_unlock_bh(&ct->lock);
if (new_state != old_state)
nf_conntrack_event_cache(IPCT_PROTOINFO, ct);
nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]);
return NF_ACCEPT;
}
| 166,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: void SetPreviewDataForIndex(int index, const base::RefCountedBytes* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
page_data_map_[index] = const_cast<base::RefCountedBytes*>(data);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void SetPreviewDataForIndex(int index, const base::RefCountedBytes* data) {
if (IsInvalidIndex(index))
return;
page_data_map_[index] = const_cast<base::RefCountedBytes*>(data);
}
| 170,825 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
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 | check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ip6t_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
if (!ip6_checkentry(&e->ipv6))
return -EINVAL;
ret = xt_compat_check_entry_offsets(e, e->elems,
e->target_offset, e->next_offset);
if (ret)
return ret;
off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ipv6, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ip6t_get_target(e);
target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET6, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
| 167,219 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = load_segment_descriptor(ctxt, sel, VCPU_SREG_CS);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->_eip = 0;
memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_jmp_far(struct x86_emulate_ctxt *ctxt)
{
int rc;
unsigned short sel, old_sel;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
u8 cpl = ctxt->ops->cpl(ctxt);
/* Assignment of RIP may only fail in 64-bit mode */
if (ctxt->mode == X86EMUL_MODE_PROT64)
ops->get_segment(ctxt, &old_sel, &old_desc, NULL,
VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return rc;
rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l);
if (rc != X86EMUL_CONTINUE) {
WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64);
/* assigning eip failed; restore the old cs */
ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
return rc;
}
| 166,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SimpleSoftOMXComponent::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (defParams->nPortIndex >= mPorts.size()
|| defParams->nSize
!= sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUndefined;
}
const PortInfo *port =
&mPorts.itemAt(defParams->nPortIndex);
memcpy(defParams, &port->mDef, sizeof(port->mDef));
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SimpleSoftOMXComponent::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamPortDefinition:
{
OMX_PARAM_PORTDEFINITIONTYPE *defParams =
(OMX_PARAM_PORTDEFINITIONTYPE *)params;
if (!isValidOMXParam(defParams)) {
return OMX_ErrorBadParameter;
}
if (defParams->nPortIndex >= mPorts.size()
|| defParams->nSize
!= sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) {
return OMX_ErrorUndefined;
}
const PortInfo *port =
&mPorts.itemAt(defParams->nPortIndex);
memcpy(defParams, &port->mDef, sizeof(port->mDef));
return OMX_ErrorNone;
}
default:
return OMX_ErrorUnsupportedIndex;
}
}
| 174,222 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::CreateInstance(
IMkvReader* pReader,
long long pos,
Segment*& pSegment)
{
assert(pReader);
assert(pos >= 0);
pSegment = NULL;
long long total, available;
const long status = pReader->Length(&total, &available);
if (status < 0) //error
return status;
if (available < 0)
return -1;
if ((total >= 0) && (available > total))
return -1;
for (;;)
{
if ((total >= 0) && (pos >= total))
return E_FILE_FORMAT_INVALID;
long len;
long long result = GetUIntLength(pReader, pos, len);
if (result) //error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return id;
pos += len; //consume ID
result = GetUIntLength(pReader, pos, len);
if (result) //error, or too few available bytes
return result;
if ((total >= 0) && ((pos + len) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return size;
pos += len; //consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (id == 0x08538067) //Segment ID
{
if (size == unknown_size)
size = -1;
else if (total < 0)
size = -1;
else if ((pos + size) > total)
size = -1;
pSegment = new (std::nothrow) Segment(
pReader,
idpos,
pos,
size);
if (pSegment == 0)
return -1; //generic error
return 0; //success
}
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && ((pos + size) > total))
return E_FILE_FORMAT_INVALID;
if ((pos + size) > available)
return pos + size;
pos += size; //consume payload
}
}
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 Segment::CreateInstance(
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id < 0) // error
return id;
if (id == 0x0F43B675) // Cluster ID
break;
pos += len; // consume ID
if ((pos + 1) > available)
return (pos + 1);
// Read Size
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return result;
if (result > 0) // underflow (weird)
return (pos + 1);
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > available)
return pos + len;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return size;
pos += len; // consume length of size of element
const long long element_size = size + pos - element_start;
// Pos now points to start of payload
if ((segment_stop >= 0) && ((pos + size) > segment_stop))
return E_FILE_FORMAT_INVALID;
// We read EBML elements either in total or nothing at all.
if ((pos + size) > available)
return pos + size;
if (id == 0x0549A966) { // Segment Info ID
if (m_pInfo)
return E_FILE_FORMAT_INVALID;
m_pInfo = new (std::nothrow)
SegmentInfo(this, pos, size, element_start, element_size);
if (m_pInfo == NULL)
return -1;
const long status = m_pInfo->Parse();
if (status)
return status;
} else if (id == 0x0654AE6B) { // Tracks ID
if (m_pTracks)
return E_FILE_FORMAT_INVALID;
m_pTracks = new (std::nothrow)
Tracks(this, pos, size, element_start, element_size);
if (m_pTracks == NULL)
return -1;
const long status = m_pTracks->Parse();
| 174,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::DetachInterstitialPage() {
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(static_cast<RenderWidgetHostViewBase*>(
GetRenderManager()->current_frame_host()->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
GetRenderManager()->current_frame_host()->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
bool interstitial_pausing_throbber =
ShowingInterstitialPage() &&
GetRenderManager()->interstitial_page()->pause_throbber();
if (ShowingInterstitialPage())
GetRenderManager()->remove_interstitial_page();
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | void WebContentsImpl::DetachInterstitialPage() {
if (node_.OuterContentsFrameTreeNode()) {
if (GetRenderManager()->GetProxyToOuterDelegate()) {
DCHECK(static_cast<RenderWidgetHostViewBase*>(
GetRenderManager()->current_frame_host()->GetView())
->IsRenderWidgetHostViewChildFrame());
RenderWidgetHostViewChildFrame* view =
static_cast<RenderWidgetHostViewChildFrame*>(
GetRenderManager()->current_frame_host()->GetView());
GetRenderManager()->SetRWHViewForInnerContents(view);
}
}
bool interstitial_pausing_throbber =
ShowingInterstitialPage() && interstitial_page_->pause_throbber();
if (ShowingInterstitialPage())
interstitial_page_ = nullptr;
for (auto& observer : observers_)
observer.DidDetachInterstitialPage();
if (interstitial_pausing_throbber && frame_tree_.IsLoading())
LoadingStateChanged(true, true, nullptr);
}
| 172,325 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
php_stream *file;
size_t memsize;
char *membuf;
off_t pos;
assert(ts != NULL);
if (!ts->innerstream) {
return FAILURE;
}
if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) {
return php_stream_cast(ts->innerstream, castas, ret, 0);
}
/* we are still using a memory based backing. If they are if we can be
* a FILE*, say yes because we can perform the conversion.
* If they actually want to perform the conversion, we need to switch
* the memory stream to a tmpfile stream */
if (ret == NULL && castas == PHP_STREAM_AS_STDIO) {
return SUCCESS;
}
/* say "no" to other stream forms */
if (ret == NULL) {
return FAILURE;
}
/* perform the conversion and then pass the request on to the innerstream */
membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
file = php_stream_fopen_tmpfile();
php_stream_write(file, membuf, memsize);
pos = php_stream_tell(ts->innerstream);
php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE);
ts->innerstream = file;
php_stream_encloses(stream, ts->innerstream);
php_stream_seek(ts->innerstream, pos, SEEK_SET);
return php_stream_cast(ts->innerstream, castas, ret, 1);
}
Commit Message:
CWE ID: CWE-20 | static int php_stream_temp_cast(php_stream *stream, int castas, void **ret TSRMLS_DC)
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
php_stream *file;
size_t memsize;
char *membuf;
off_t pos;
assert(ts != NULL);
if (!ts->innerstream) {
return FAILURE;
}
if (php_stream_is(ts->innerstream, PHP_STREAM_IS_STDIO)) {
return php_stream_cast(ts->innerstream, castas, ret, 0);
}
/* we are still using a memory based backing. If they are if we can be
* a FILE*, say yes because we can perform the conversion.
* If they actually want to perform the conversion, we need to switch
* the memory stream to a tmpfile stream */
if (ret == NULL && castas == PHP_STREAM_AS_STDIO) {
return SUCCESS;
}
/* say "no" to other stream forms */
if (ret == NULL) {
return FAILURE;
}
/* perform the conversion and then pass the request on to the innerstream */
membuf = php_stream_memory_get_buffer(ts->innerstream, &memsize);
file = php_stream_fopen_tmpfile();
php_stream_write(file, membuf, memsize);
pos = php_stream_tell(ts->innerstream);
php_stream_free_enclosed(ts->innerstream, PHP_STREAM_FREE_CLOSE);
ts->innerstream = file;
php_stream_encloses(stream, ts->innerstream);
php_stream_seek(ts->innerstream, pos, SEEK_SET);
return php_stream_cast(ts->innerstream, castas, ret, 1);
}
| 165,478 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
}
Commit Message: Fixed CVE-2018-8784
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119 | static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits)
{
if (!_zgfx)
return FALSE;
while (_zgfx->cBitsCurrent < _nbits)
{
_zgfx->BitsCurrent <<= 8;
if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd)
_zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++;
_zgfx->cBitsCurrent += 8;
}
_zgfx->cBitsRemaining -= _nbits;
_zgfx->cBitsCurrent -= _nbits;
_zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent;
_zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1);
return TRUE;
}
| 169,296 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
Commit Message: Avoid sharing process for blob URLs with null origin.
Previously, when a frame with a unique origin, such as from a data
URL, created a blob URL, the blob URL looked like blob:null/guid and
resulted in a site URL of "blob:" when navigated to. This incorrectly
allowed all such blob URLs to share a process, even if they were
created by different sites.
This CL changes the site URL assigned in such cases to be the full
blob URL, which includes the GUID. This avoids process sharing for
all blob URLs with unique origins.
This fix is conservative in the sense that it would also isolate
different blob URLs created by the same unique origin from each other.
This case isn't expected to be common, so it's unlikely to affect
process count. There's ongoing work to maintain a GUID for unique
origins, so longer-term, we could try using that to track down the
creator and potentially use that GUID in the site URL instead of the
blob URL's GUID, to avoid unnecessary process isolation in scenarios
like this.
Note that as part of this, we discovered a bug where data URLs aren't
able to script blob URLs that they create: https://crbug.com/865254.
This scripting bug should be fixed independently of this CL, and as
far as we can tell, this CL doesn't regress scripting cases like this
further.
Bug: 863623
Change-Id: Ib50407adbba3d5ee0cf6d72d3df7f8d8f24684ee
Reviewed-on: https://chromium-review.googlesource.com/1142389
Commit-Queue: Alex Moshchuk <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#576318}
CWE ID: CWE-285 | GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context,
const GURL& real_url) {
if (real_url.SchemeIs(kGuestScheme))
return real_url;
GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url);
url::Origin origin = url::Origin::Create(url);
auto* policy = ChildProcessSecurityPolicyImpl::GetInstance();
url::Origin isolated_origin;
if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin))
return isolated_origin.GetURL();
if (!origin.host().empty() && origin.scheme() != url::kFileScheme) {
std::string domain = net::registry_controlled_domains::GetDomainAndRegistry(
origin.host(),
net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
std::string site = origin.scheme();
site += url::kStandardSchemeSeparator;
site += domain.empty() ? origin.host() : domain;
return GURL(site);
}
if (!origin.unique()) {
// cover blob:file: and filesystem:file: URIs (see also
// https://crbug.com/697111).
DCHECK(!origin.scheme().empty());
return GURL(origin.scheme() + ":");
} else if (url.has_scheme()) {
// In some cases, it is not safe to use just the scheme as a site URL, as
// that might allow two URLs created by different sites to to share a
// process. See https://crbug.com/863623.
//
// TODO(alexmos,creis): This should eventually be expanded to certain other
// schemes, such as data: and file:.
if (url.SchemeIsBlob()) {
// We get here for blob URLs of form blob:null/guid. Use the full URL
// with the guid in that case, which isolates all blob URLs with unique
// origins from each other. Remove hash from the URL, since
// same-document navigations shouldn't use a different site URL.
if (url.has_ref()) {
GURL::Replacements replacements;
replacements.ClearRef();
url = url.ReplaceComponents(replacements);
}
return url;
}
DCHECK(!url.scheme().empty());
return GURL(url.scheme() + ":");
}
DCHECK(!url.is_valid()) << url;
return GURL();
}
| 173,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) {
struct console_font_op cfo = {
.op = KD_FONT_OP_GET,
.width = UINT_MAX, .height = UINT_MAX,
.charcount = UINT_MAX,
};
struct unimapinit adv = {};
struct unimapdesc unimapd;
_cleanup_free_ struct unipair* unipairs = NULL;
_cleanup_free_ void *fontbuf = NULL;
unsigned i;
int r;
unipairs = new(struct unipair, USHRT_MAX);
if (!unipairs) {
log_oom();
return;
}
/* get metadata of the current font (width, height, count) */
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m");
else {
/* verify parameter sanity first */
if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512)
log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)",
cfo.width, cfo.height, cfo.charcount);
else {
/*
* Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512
* characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always
* requires 32 per glyph, regardless of the actual height - see the comment above #define
* max_font_size 65536 in drivers/tty/vt/vt.c for more details.
*/
fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount);
if (!fontbuf) {
log_oom();
return;
}
/* get fonts from the source console */
cfo.data = fontbuf;
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m");
else {
unimapd.entries = unipairs;
unimapd.entry_ct = USHRT_MAX;
r = ioctl(src_fd, GIO_UNIMAP, &unimapd);
if (r < 0)
log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m");
else
cfo.op = KD_FONT_OP_SET;
}
}
}
if (cfo.op != KD_FONT_OP_SET)
log_warning("Fonts will not be copied to remaining consoles");
for (i = 1; i <= 63; i++) {
char ttyname[sizeof("/dev/tty63")];
_cleanup_close_ int fd_d = -1;
if (i == src_idx || verify_vc_allocation(i) < 0)
continue;
/* try to open terminal */
xsprintf(ttyname, "/dev/tty%u", i);
fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd_d < 0) {
log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i);
continue;
}
if (verify_vc_kbmode(fd_d) < 0)
continue;
toggle_utf8(ttyname, fd_d, utf8);
if (cfo.op != KD_FONT_OP_SET)
continue;
r = ioctl(fd_d, KDFONTOP, &cfo);
if (r < 0) {
int last_errno, mode;
/* The fonts couldn't have been copied. It might be due to the
* terminal being in graphical mode. In this case the kernel
* returns -EINVAL which is too generic for distinguishing this
* specific case. So we need to retrieve the terminal mode and if
* the graphical mode is in used, let's assume that something else
* is using the terminal and the failure was expected as we
* shouldn't have tried to copy the fonts. */
last_errno = errno;
if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT)
log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i);
else
log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i);
continue;
}
/*
* copy unicode translation table unimapd is a ushort count and a pointer
* to an array of struct unipair { ushort, ushort }
*/
r = ioctl(fd_d, PIO_UNIMAPCLR, &adv);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
r = ioctl(fd_d, PIO_UNIMAP, &unimapd);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
log_debug("Font and unimap successfully copied to %s", ttyname);
}
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255 | static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) {
struct console_font_op cfo = {
.op = KD_FONT_OP_GET,
.width = UINT_MAX, .height = UINT_MAX,
.charcount = UINT_MAX,
};
struct unimapinit adv = {};
struct unimapdesc unimapd;
_cleanup_free_ struct unipair* unipairs = NULL;
_cleanup_free_ void *fontbuf = NULL;
unsigned i;
int r;
unipairs = new(struct unipair, USHRT_MAX);
if (!unipairs) {
log_oom();
return;
}
/* get metadata of the current font (width, height, count) */
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m");
else {
/* verify parameter sanity first */
if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512)
log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)",
cfo.width, cfo.height, cfo.charcount);
else {
/*
* Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512
* characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always
* requires 32 per glyph, regardless of the actual height - see the comment above #define
* max_font_size 65536 in drivers/tty/vt/vt.c for more details.
*/
fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount);
if (!fontbuf) {
log_oom();
return;
}
/* get fonts from the source console */
cfo.data = fontbuf;
r = ioctl(src_fd, KDFONTOP, &cfo);
if (r < 0)
log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m");
else {
unimapd.entries = unipairs;
unimapd.entry_ct = USHRT_MAX;
r = ioctl(src_fd, GIO_UNIMAP, &unimapd);
if (r < 0)
log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m");
else
cfo.op = KD_FONT_OP_SET;
}
}
}
if (cfo.op != KD_FONT_OP_SET)
log_warning("Fonts will not be copied to remaining consoles");
for (i = 1; i <= 63; i++) {
char ttyname[sizeof("/dev/tty63")];
_cleanup_close_ int fd_d = -1;
if (i == src_idx || verify_vc_allocation(i) < 0)
continue;
/* try to open terminal */
xsprintf(ttyname, "/dev/tty%u", i);
fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY);
if (fd_d < 0) {
log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i);
continue;
}
if (vt_verify_kbmode(fd_d) < 0)
continue;
toggle_utf8(ttyname, fd_d, utf8);
if (cfo.op != KD_FONT_OP_SET)
continue;
r = ioctl(fd_d, KDFONTOP, &cfo);
if (r < 0) {
int last_errno, mode;
/* The fonts couldn't have been copied. It might be due to the
* terminal being in graphical mode. In this case the kernel
* returns -EINVAL which is too generic for distinguishing this
* specific case. So we need to retrieve the terminal mode and if
* the graphical mode is in used, let's assume that something else
* is using the terminal and the failure was expected as we
* shouldn't have tried to copy the fonts. */
last_errno = errno;
if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT)
log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i);
else
log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i);
continue;
}
/*
* copy unicode translation table unimapd is a ushort count and a pointer
* to an array of struct unipair { ushort, ushort }
*/
r = ioctl(fd_d, PIO_UNIMAPCLR, &adv);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
r = ioctl(fd_d, PIO_UNIMAP, &unimapd);
if (r < 0) {
log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i);
continue;
}
log_debug("Font and unimap successfully copied to %s", ttyname);
}
}
| 169,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_malloc((sizeof *p->vec) *
(max_frags + NET_TX_PKT_PL_START_FRAG));
p->raw = g_malloc((sizeof *p->raw) * max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
}
Commit Message:
CWE ID: CWE-190 | void net_tx_pkt_init(struct NetTxPkt **pkt, PCIDevice *pci_dev,
uint32_t max_frags, bool has_virt_hdr)
{
struct NetTxPkt *p = g_malloc0(sizeof *p);
p->pci_dev = pci_dev;
p->vec = g_new(struct iovec, max_frags + NET_TX_PKT_PL_START_FRAG);
p->raw = g_new(struct iovec, max_frags);
p->max_payload_frags = max_frags;
p->max_raw_frags = max_frags;
p->max_raw_frags = max_frags;
p->has_virt_hdr = has_virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_base = &p->virt_hdr;
p->vec[NET_TX_PKT_VHDR_FRAG].iov_len =
p->has_virt_hdr ? sizeof p->virt_hdr : 0;
p->vec[NET_TX_PKT_L2HDR_FRAG].iov_base = &p->l2_hdr;
p->vec[NET_TX_PKT_L3HDR_FRAG].iov_base = &p->l3_hdr;
*pkt = p;
}
| 164,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __mkroute_input(struct sk_buff *skb,
const struct fib_result *res,
struct in_device *in_dev,
__be32 daddr, __be32 saddr, u32 tos)
{
struct fib_nh_exception *fnhe;
struct rtable *rth;
int err;
struct in_device *out_dev;
unsigned int flags = 0;
bool do_cache;
u32 itag = 0;
/* get a working reference to the output device */
out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res));
if (out_dev == NULL) {
net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n");
return -EINVAL;
}
err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res),
in_dev->dev, in_dev, &itag);
if (err < 0) {
ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr,
saddr);
goto cleanup;
}
do_cache = res->fi && !itag;
if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) &&
(IN_DEV_SHARED_MEDIA(out_dev) ||
inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) {
flags |= RTCF_DOREDIRECT;
do_cache = false;
}
if (skb->protocol != htons(ETH_P_IP)) {
/* Not IP (i.e. ARP). Do not create route, if it is
* invalid for proxy arp. DNAT routes are always valid.
*
* Proxy arp feature have been extended to allow, ARP
* replies back to the same interface, to support
* Private VLAN switch technologies. See arp.c.
*/
if (out_dev == in_dev &&
IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) {
err = -EINVAL;
goto cleanup;
}
}
fnhe = find_exception(&FIB_RES_NH(*res), daddr);
if (do_cache) {
if (fnhe != NULL)
rth = rcu_dereference(fnhe->fnhe_rth_input);
else
rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input);
if (rt_cache_valid(rth)) {
skb_dst_set_noref(skb, &rth->dst);
goto out;
}
}
rth = rt_dst_alloc(out_dev->dev,
IN_DEV_CONF_GET(in_dev, NOPOLICY),
IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache);
if (!rth) {
err = -ENOBUFS;
goto cleanup;
}
rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev));
rth->rt_flags = flags;
rth->rt_type = res->type;
rth->rt_is_input = 1;
rth->rt_iif = 0;
rth->rt_pmtu = 0;
rth->rt_gateway = 0;
rth->rt_uses_gateway = 0;
INIT_LIST_HEAD(&rth->rt_uncached);
RT_CACHE_STAT_INC(in_slow_tot);
rth->dst.input = ip_forward;
rth->dst.output = ip_output;
rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag);
skb_dst_set(skb, &rth->dst);
out:
err = 0;
cleanup:
return err;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <[email protected]>
Signed-off-by: Marcelo Leitner <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17 | static int __mkroute_input(struct sk_buff *skb,
const struct fib_result *res,
struct in_device *in_dev,
__be32 daddr, __be32 saddr, u32 tos)
{
struct fib_nh_exception *fnhe;
struct rtable *rth;
int err;
struct in_device *out_dev;
unsigned int flags = 0;
bool do_cache;
u32 itag = 0;
/* get a working reference to the output device */
out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res));
if (out_dev == NULL) {
net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n");
return -EINVAL;
}
err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res),
in_dev->dev, in_dev, &itag);
if (err < 0) {
ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr,
saddr);
goto cleanup;
}
do_cache = res->fi && !itag;
if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) &&
skb->protocol == htons(ETH_P_IP) &&
(IN_DEV_SHARED_MEDIA(out_dev) ||
inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res))))
IPCB(skb)->flags |= IPSKB_DOREDIRECT;
if (skb->protocol != htons(ETH_P_IP)) {
/* Not IP (i.e. ARP). Do not create route, if it is
* invalid for proxy arp. DNAT routes are always valid.
*
* Proxy arp feature have been extended to allow, ARP
* replies back to the same interface, to support
* Private VLAN switch technologies. See arp.c.
*/
if (out_dev == in_dev &&
IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) {
err = -EINVAL;
goto cleanup;
}
}
fnhe = find_exception(&FIB_RES_NH(*res), daddr);
if (do_cache) {
if (fnhe != NULL)
rth = rcu_dereference(fnhe->fnhe_rth_input);
else
rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input);
if (rt_cache_valid(rth)) {
skb_dst_set_noref(skb, &rth->dst);
goto out;
}
}
rth = rt_dst_alloc(out_dev->dev,
IN_DEV_CONF_GET(in_dev, NOPOLICY),
IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache);
if (!rth) {
err = -ENOBUFS;
goto cleanup;
}
rth->rt_genid = rt_genid_ipv4(dev_net(rth->dst.dev));
rth->rt_flags = flags;
rth->rt_type = res->type;
rth->rt_is_input = 1;
rth->rt_iif = 0;
rth->rt_pmtu = 0;
rth->rt_gateway = 0;
rth->rt_uses_gateway = 0;
INIT_LIST_HEAD(&rth->rt_uncached);
RT_CACHE_STAT_INC(in_slow_tot);
rth->dst.input = ip_forward;
rth->dst.output = ip_output;
rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag);
skb_dst_set(skb, &rth->dst);
out:
err = 0;
cleanup:
return err;
}
| 166,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: ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_reader);
#endif
}
Commit Message:
CWE ID: | ZEND_API void zend_ts_hash_graceful_destroy(TsHashTable *ht)
{
begin_write(ht);
zend_hash_graceful_destroy(TS_HASH(ht));
end_write(ht);
#ifdef ZTS
tsrm_mutex_free(ht->mx_reader);
tsrm_mutex_free(ht->mx_writer);
#endif
}
| 164,883 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: stf_status ikev2parent_inI2outR2(struct msg_digest *md)
{
struct state *st = md->st;
/* struct connection *c = st->st_connection; */
/*
* the initiator sent us an encrypted payload. We need to calculate
* our g^xy, and skeyseed values, and then decrypt the payload.
*/
DBG(DBG_CONTROLMORE,
DBG_log(
"ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2"));
/* verify that there is in fact an encrypted payload */
if (!md->chain[ISAKMP_NEXT_v2E]) {
libreswan_log("R2 state should receive an encrypted payload");
reset_globals();
return STF_FATAL;
}
/* now. we need to go calculate the g^xy */
{
struct dh_continuation *dh = alloc_thing(
struct dh_continuation,
"ikev2_inI2outR2 KE");
stf_status e;
dh->md = md;
set_suspended(st, dh->md);
pcrc_init(&dh->dh_pcrc);
dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue;
e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER,
st->st_oakley.groupnum);
if (e != STF_SUSPEND && e != STF_INLINE) {
loglog(RC_CRYPTOFAILED, "system too busy");
delete_state(st);
}
reset_globals();
return e;
}
}
Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload
CWE ID: CWE-20 | stf_status ikev2parent_inI2outR2(struct msg_digest *md)
{
struct state *st = md->st;
/* struct connection *c = st->st_connection; */
/*
* the initiator sent us an encrypted payload. We need to calculate
* our g^xy, and skeyseed values, and then decrypt the payload.
*/
DBG(DBG_CONTROLMORE,
DBG_log(
"ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2"));
/* verify that there is in fact an encrypted payload */
if (!md->chain[ISAKMP_NEXT_v2E]) {
libreswan_log("R2 state should receive an encrypted payload");
reset_globals(); /* XXX suspicious - why was this deemed neccessary? */
return STF_FATAL;
}
/* now. we need to go calculate the g^xy */
{
struct dh_continuation *dh = alloc_thing(
struct dh_continuation,
"ikev2_inI2outR2 KE");
stf_status e;
dh->md = md;
set_suspended(st, dh->md);
pcrc_init(&dh->dh_pcrc);
dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue;
e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER,
st->st_oakley.groupnum);
if (e != STF_SUSPEND && e != STF_INLINE) {
loglog(RC_CRYPTOFAILED, "system too busy");
delete_state(st);
}
reset_globals();
return e;
}
}
| 166,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 IDNToUnicodeWithAdjustments(
base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
converted_idn =
IDNToUnicodeOneComponent(input16.data() + component_start,
component_length, &out16);
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
return out16;
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20 | base::string16 IDNToUnicodeWithAdjustments(
base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
bool is_tld_ascii = true;
size_t last_dot = host.rfind('.');
if (last_dot != base::StringPiece::npos &&
host.substr(last_dot).starts_with(".xn--")) {
is_tld_ascii = false;
}
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
converted_idn =
IDNToUnicodeOneComponent(input16.data() + component_start,
component_length, is_tld_ascii, &out16);
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
return out16;
}
| 172,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c);
switch (type) {
case EVP_CTRL_INIT:
cctx->key_set = 0;
cctx->iv_set = 0;
cctx->L = 8;
cctx->M = 12;
cctx->tag_set = 0;
cctx->len_set = 0;
cctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
cctx->tls_aad_len = arg;
{
uint16_t len =
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
| EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
/* Correct length for explicit IV */
len -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!EVP_CIPHER_CTX_encrypting(c))
len -= cctx->M;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return cctx->M;
case EVP_CTRL_CCM_SET_IV_FIXED:
/* Sanity check length */
if (arg != EVP_CCM_TLS_FIXED_IV_LEN)
return 0;
/* Just copy to first part of IV */
memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg);
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
arg = 15 - arg;
case EVP_CTRL_CCM_SET_L:
if (arg < 2 || arg > 8)
return 0;
cctx->L = arg;
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if ((arg & 1) || arg < 4 || arg > 16)
return 0;
if (EVP_CIPHER_CTX_encrypting(c) && ptr)
return 0;
if (ptr) {
cctx->tag_set = 1;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
}
cctx->M = arg;
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set)
return 0;
if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
return 0;
cctx->tag_set = 0;
cctx->iv_set = 0;
cctx->len_set = 0;
return 1;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out);
if (cctx->ccm.key) {
if (cctx->ccm.key != &cctx->ks)
return 0;
cctx_out->ccm.key = &cctx_out->ks;
}
return 1;
}
default:
return -1;
}
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125 | static int aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c);
switch (type) {
case EVP_CTRL_INIT:
cctx->key_set = 0;
cctx->iv_set = 0;
cctx->L = 8;
cctx->M = 12;
cctx->tag_set = 0;
cctx->len_set = 0;
cctx->tls_aad_len = -1;
return 1;
case EVP_CTRL_AEAD_TLS1_AAD:
/* Save the AAD for later use */
if (arg != EVP_AEAD_TLS1_AAD_LEN)
return 0;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
cctx->tls_aad_len = arg;
{
uint16_t len =
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8
| EVP_CIPHER_CTX_buf_noconst(c)[arg - 1];
/* Correct length for explicit IV */
if (len < EVP_CCM_TLS_EXPLICIT_IV_LEN)
return 0;
len -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
/* If decrypting correct for tag too */
if (!EVP_CIPHER_CTX_encrypting(c)) {
if (len < cctx->M)
return 0;
len -= cctx->M;
}
EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8;
EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff;
}
/* Extra padding: tag appended to record */
return cctx->M;
case EVP_CTRL_CCM_SET_IV_FIXED:
/* Sanity check length */
if (arg != EVP_CCM_TLS_FIXED_IV_LEN)
return 0;
/* Just copy to first part of IV */
memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg);
return 1;
case EVP_CTRL_AEAD_SET_IVLEN:
arg = 15 - arg;
case EVP_CTRL_CCM_SET_L:
if (arg < 2 || arg > 8)
return 0;
cctx->L = arg;
return 1;
case EVP_CTRL_AEAD_SET_TAG:
if ((arg & 1) || arg < 4 || arg > 16)
return 0;
if (EVP_CIPHER_CTX_encrypting(c) && ptr)
return 0;
if (ptr) {
cctx->tag_set = 1;
memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg);
}
cctx->M = arg;
return 1;
case EVP_CTRL_AEAD_GET_TAG:
if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set)
return 0;
if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg))
return 0;
cctx->tag_set = 0;
cctx->iv_set = 0;
cctx->len_set = 0;
return 1;
case EVP_CTRL_COPY:
{
EVP_CIPHER_CTX *out = ptr;
EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out);
if (cctx->ccm.key) {
if (cctx->ccm.key != &cctx->ks)
return 0;
cctx_out->ccm.key = &cctx_out->ks;
}
return 1;
}
default:
return -1;
}
}
| 168,430 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 perf_event_read_group(struct perf_event *event,
u64 read_format, char __user *buf)
{
struct perf_event *leader = event->group_leader, *sub;
int n = 0, size = 0, ret = -EFAULT;
struct perf_event_context *ctx = leader->ctx;
u64 values[5];
u64 count, enabled, running;
mutex_lock(&ctx->mutex);
count = perf_event_read_value(leader, &enabled, &running);
values[n++] = 1 + leader->nr_siblings;
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
values[n++] = enabled;
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
values[n++] = running;
values[n++] = count;
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(leader);
size = n * sizeof(u64);
if (copy_to_user(buf, values, size))
goto unlock;
ret = size;
list_for_each_entry(sub, &leader->sibling_list, group_entry) {
n = 0;
values[n++] = perf_event_read_value(sub, &enabled, &running);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(sub);
size = n * sizeof(u64);
if (copy_to_user(buf + ret, values, size)) {
ret = -EFAULT;
goto unlock;
}
ret += size;
}
unlock:
mutex_unlock(&ctx->mutex);
return ret;
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | static int perf_event_read_group(struct perf_event *event,
u64 read_format, char __user *buf)
{
struct perf_event *leader = event->group_leader, *sub;
struct perf_event_context *ctx = leader->ctx;
int n = 0, size = 0, ret;
u64 count, enabled, running;
u64 values[5];
lockdep_assert_held(&ctx->mutex);
count = perf_event_read_value(leader, &enabled, &running);
values[n++] = 1 + leader->nr_siblings;
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
values[n++] = enabled;
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
values[n++] = running;
values[n++] = count;
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(leader);
size = n * sizeof(u64);
if (copy_to_user(buf, values, size))
return -EFAULT;
ret = size;
list_for_each_entry(sub, &leader->sibling_list, group_entry) {
n = 0;
values[n++] = perf_event_read_value(sub, &enabled, &running);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(sub);
size = n * sizeof(u64);
if (copy_to_user(buf + ret, values, size)) {
return -EFAULT;
}
ret += size;
}
return ret;
}
| 166,986 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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.
*/
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;
}
}
}
Commit Message: adb: use asocket's close function when closing.
close_all_sockets was assuming that all registered local sockets used
local_socket_close as their close function. However, this is not true
for JDWP sockets.
Bug: http://b/28347842
Change-Id: I40a1174845cd33f15f30ce70828a7081cd5a087e
(cherry picked from commit 53eb31d87cb84a4212f4850bf745646e1fb12814)
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)) {
s->close(s);
goto restart;
}
}
}
| 173,405 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NormalPage::objectPayloadSizeForTesting() {
size_t objectPayloadSize = 0;
Address headerAddress = payload();
markAsSwept();
ASSERT(headerAddress != payloadEnd());
do {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(headerAddress);
if (!header->isFree()) {
ASSERT(header->checkHeader());
objectPayloadSize += header->payloadSize();
}
ASSERT(header->size() < blinkPagePayloadSize());
headerAddress += header->size();
ASSERT(headerAddress <= payloadEnd());
} while (headerAddress < payloadEnd());
return objectPayloadSize;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | size_t NormalPage::objectPayloadSizeForTesting() {
size_t objectPayloadSize = 0;
Address headerAddress = payload();
markAsSwept();
ASSERT(headerAddress != payloadEnd());
do {
HeapObjectHeader* header =
reinterpret_cast<HeapObjectHeader*>(headerAddress);
if (!header->isFree()) {
header->checkHeader();
objectPayloadSize += header->payloadSize();
}
ASSERT(header->size() < blinkPagePayloadSize());
headerAddress += header->size();
ASSERT(headerAddress <= payloadEnd());
} while (headerAddress < payloadEnd());
return objectPayloadSize;
}
| 172,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: transform_disable(PNG_CONST char *name)
{
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 0;
return;
}
list = list->list;
}
fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
name);
exit(99);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_disable(PNG_CONST char *name)
transform_disable(const char *name)
{
image_transform *list = image_transform_first;
while (list != &image_transform_end)
{
if (strcmp(list->name, name) == 0)
{
list->enable = 0;
return;
}
list = list->list;
}
fprintf(stderr, "pngvalid: --transform-disable=%s: unknown transform\n",
name);
exit(99);
}
| 173,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSelection::FocusedOrActiveStateChanged() {
bool active_and_focused = FrameIsFocusedAndActive();
if (Element* element = GetDocument().FocusedElement())
element->FocusStateChanged();
GetDocument().UpdateStyleAndLayoutTree();
auto* view = GetDocument().GetLayoutView();
if (view)
layout_selection_->InvalidatePaintForSelection();
if (active_and_focused)
SetSelectionFromNone();
frame_caret_->SetCaretVisibility(active_and_focused
? CaretVisibility::kVisible
: CaretVisibility::kHidden);
frame_->GetEventHandler().CapsLockStateMayHaveChanged();
if (use_secure_keyboard_entry_when_active_)
SetUseSecureKeyboardEntry(active_and_focused);
}
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 FrameSelection::FocusedOrActiveStateChanged() {
bool active_and_focused = FrameIsFocusedAndActive();
if (Element* element = GetDocument().FocusedElement())
element->FocusStateChanged();
GetDocument().UpdateStyleAndLayoutTree();
auto* view = GetDocument().GetLayoutView();
if (view)
layout_selection_->InvalidatePaintForSelection();
if (active_and_focused)
SetSelectionFromNone();
frame_caret_->SetCaretVisibility(active_and_focused
? CaretVisibility::kVisible
: CaretVisibility::kHidden);
frame_->GetEventHandler().CapsLockStateMayHaveChanged();
}
| 171,854 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
std::string* error) {
int error_code = 0;
Value* params =
base::JSONReader::ReadAndReturnError(json, true, &error_code, error);
if (error_code != 0) {
VLOG(1) << "Could not parse JSON object, " << *error;
if (params)
delete params;
return false;
}
if (!params || params->GetType() != Value::TYPE_DICTIONARY) {
*error = "Data passed in URL must be of type dictionary.";
VLOG(1) << "Invalid type to parse";
if (params)
delete params;
return false;
}
*dict = static_cast<DictionaryValue*>(params);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ParseJSONDictionary(const std::string& json, DictionaryValue** dict,
| 170,466 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int can_open_cached(struct nfs4_state *state, int mode)
{
int ret = 0;
switch (mode & (FMODE_READ|FMODE_WRITE|O_EXCL)) {
case FMODE_READ:
ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0;
break;
case FMODE_WRITE:
ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0;
break;
case FMODE_READ|FMODE_WRITE:
ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0;
}
return ret;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static int can_open_cached(struct nfs4_state *state, int mode)
static int can_open_cached(struct nfs4_state *state, fmode_t mode, int open_mode)
{
int ret = 0;
if (open_mode & O_EXCL)
goto out;
switch (mode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
ret |= test_bit(NFS_O_RDONLY_STATE, &state->flags) != 0;
break;
case FMODE_WRITE:
ret |= test_bit(NFS_O_WRONLY_STATE, &state->flags) != 0;
break;
case FMODE_READ|FMODE_WRITE:
ret |= test_bit(NFS_O_RDWR_STATE, &state->flags) != 0;
}
out:
return ret;
}
| 165,686 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ip_forward(struct sk_buff *skb)
{
u32 mtu;
struct iphdr *iph; /* Our header */
struct rtable *rt; /* Route we use */
struct ip_options *opt = &(IPCB(skb)->opt);
/* that should never happen */
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))
goto drop;
if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))
return NET_RX_SUCCESS;
skb_forward_csum(skb);
/*
* According to the RFC, we must first decrease the TTL field. If
* that reaches zero, we must reply an ICMP control message telling
* that the packet's lifetime expired.
*/
if (ip_hdr(skb)->ttl <= 1)
goto too_many_hops;
if (!xfrm4_route_forward(skb))
goto drop;
rt = skb_rtable(skb);
if (opt->is_strictroute && rt->rt_uses_gateway)
goto sr_failed;
IPCB(skb)->flags |= IPSKB_FORWARDED;
mtu = ip_dst_mtu_maybe_forward(&rt->dst, true);
if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {
IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
goto drop;
}
/* We are about to mangle packet. Copy it! */
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))
goto drop;
iph = ip_hdr(skb);
/* Decrease ttl after skb cow done */
ip_decrease_ttl(iph);
/*
* We now generate an ICMP HOST REDIRECT giving the route
* we calculated.
*/
if (rt->rt_flags&RTCF_DOREDIRECT && !opt->srr && !skb_sec_path(skb))
ip_rt_send_redirect(skb);
skb->priority = rt_tos2priority(iph->tos);
return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,
rt->dst.dev, ip_forward_finish);
sr_failed:
/*
* Strict routing permits no gatewaying
*/
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);
goto drop;
too_many_hops:
/* Tell the sender its packet died... */
IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);
icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <[email protected]>
Signed-off-by: Marcelo Leitner <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17 | int ip_forward(struct sk_buff *skb)
{
u32 mtu;
struct iphdr *iph; /* Our header */
struct rtable *rt; /* Route we use */
struct ip_options *opt = &(IPCB(skb)->opt);
/* that should never happen */
if (skb->pkt_type != PACKET_HOST)
goto drop;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm4_policy_check(NULL, XFRM_POLICY_FWD, skb))
goto drop;
if (IPCB(skb)->opt.router_alert && ip_call_ra_chain(skb))
return NET_RX_SUCCESS;
skb_forward_csum(skb);
/*
* According to the RFC, we must first decrease the TTL field. If
* that reaches zero, we must reply an ICMP control message telling
* that the packet's lifetime expired.
*/
if (ip_hdr(skb)->ttl <= 1)
goto too_many_hops;
if (!xfrm4_route_forward(skb))
goto drop;
rt = skb_rtable(skb);
if (opt->is_strictroute && rt->rt_uses_gateway)
goto sr_failed;
IPCB(skb)->flags |= IPSKB_FORWARDED;
mtu = ip_dst_mtu_maybe_forward(&rt->dst, true);
if (!ip_may_fragment(skb) && ip_exceeds_mtu(skb, mtu)) {
IP_INC_STATS(dev_net(rt->dst.dev), IPSTATS_MIB_FRAGFAILS);
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED,
htonl(mtu));
goto drop;
}
/* We are about to mangle packet. Copy it! */
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+rt->dst.header_len))
goto drop;
iph = ip_hdr(skb);
/* Decrease ttl after skb cow done */
ip_decrease_ttl(iph);
/*
* We now generate an ICMP HOST REDIRECT giving the route
* we calculated.
*/
if (IPCB(skb)->flags & IPSKB_DOREDIRECT && !opt->srr &&
!skb_sec_path(skb))
ip_rt_send_redirect(skb);
skb->priority = rt_tos2priority(iph->tos);
return NF_HOOK(NFPROTO_IPV4, NF_INET_FORWARD, skb, skb->dev,
rt->dst.dev, ip_forward_finish);
sr_failed:
/*
* Strict routing permits no gatewaying
*/
icmp_send(skb, ICMP_DEST_UNREACH, ICMP_SR_FAILED, 0);
goto drop;
too_many_hops:
/* Tell the sender its packet died... */
IP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), IPSTATS_MIB_INHDRERRORS);
icmp_send(skb, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL, 0);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
| 166,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoundPool::doLoad(sp<Sample>& sample)
{
ALOGV("doLoad: loading sample sampleID=%d", sample->sampleID());
sample->startLoad();
mDecodeThread->loadSample(sample->sampleID());
}
Commit Message: DO NOT MERGE SoundPool: add lock for findSample access from SoundPoolThread
Sample decoding still occurs in SoundPoolThread
without holding the SoundPool lock.
Bug: 25781119
Change-Id: I11fde005aa9cf5438e0390a0d2dfe0ec1dd282e8
CWE ID: CWE-264 | void SoundPool::doLoad(sp<Sample>& sample)
int sampleID;
{
Mutex::Autolock lock(&mLock);
sampleID = ++mNextSampleID;
sp<Sample> sample = new Sample(sampleID, fd, offset, length);
mSamples.add(sampleID, sample);
sample->startLoad();
}
// mDecodeThread->loadSample() must be called outside of mLock.
// mDecodeThread->loadSample() may block on mDecodeThread message queue space;
// the message queue emptying may block on SoundPool::findSample().
//
// It theoretically possible that sample loads might decode out-of-order.
mDecodeThread->loadSample(sampleID);
return sampleID;
}
| 173,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks)
{
if (!m_provider) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state."));
return;
}
RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin();
String errorMessage;
if (!executionContext->isSecureContext(errorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage));
return;
}
KURL pageURL = KURL(KURL(), documentOrigin->toString());
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported.")));
return;
}
KURL scriptURL = rawScriptURL;
scriptURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(scriptURL)) {
RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported.")));
return;
}
KURL patternURL = scope;
patternURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(patternURL)) {
RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported.")));
return;
}
WebString webErrorMessage;
if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8())));
return;
}
m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr());
}
Commit Message: Check CSP before registering ServiceWorkers
Service Worker registrations should be subject to the same CSP checks as
other workers. The spec doesn't say this explicitly
(https://www.w3.org/TR/CSP2/#directive-child-src-workers says "Worker or
SharedWorker constructors"), but it seems to be in the spirit of things,
and it matches Firefox's behavior.
BUG=579801
Review URL: https://codereview.chromium.org/1861253004
Cr-Commit-Position: refs/heads/master@{#385775}
CWE ID: CWE-284 | void ServiceWorkerContainer::registerServiceWorkerImpl(ExecutionContext* executionContext, const KURL& rawScriptURL, const KURL& scope, PassOwnPtr<RegistrationCallbacks> callbacks)
{
if (!m_provider) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeState, "Failed to register a ServiceWorker: The document is in an invalid state."));
return;
}
RefPtr<SecurityOrigin> documentOrigin = executionContext->getSecurityOrigin();
String errorMessage;
if (!executionContext->isSecureContext(errorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, errorMessage));
return;
}
KURL pageURL = KURL(KURL(), documentOrigin->toString());
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(pageURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the current origin ('" + documentOrigin->toString() + "') is not supported.")));
return;
}
KURL scriptURL = rawScriptURL;
scriptURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(scriptURL)) {
RefPtr<SecurityOrigin> scriptOrigin = SecurityOrigin::create(scriptURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scriptURL ('" + scriptOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(scriptURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the script ('" + scriptURL.getString() + "') is not supported.")));
return;
}
KURL patternURL = scope;
patternURL.removeFragmentIdentifier();
if (!documentOrigin->canRequest(patternURL)) {
RefPtr<SecurityOrigin> patternOrigin = SecurityOrigin::create(patternURL);
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The origin of the provided scope ('" + patternOrigin->toString() + "') does not match the current origin ('" + documentOrigin->toString() + "').")));
return;
}
if (!SchemeRegistry::shouldTreatURLSchemeAsAllowingServiceWorkers(patternURL.protocol())) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The URL protocol of the scope ('" + patternURL.getString() + "') is not supported.")));
return;
}
WebString webErrorMessage;
if (!m_provider->validateScopeAndScriptURL(patternURL, scriptURL, &webErrorMessage)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeType, WebString::fromUTF8("Failed to register a ServiceWorker: " + webErrorMessage.utf8())));
return;
}
ContentSecurityPolicy* csp = executionContext->contentSecurityPolicy();
if (csp) {
if (!csp->allowWorkerContextFromSource(scriptURL, ContentSecurityPolicy::DidNotRedirect, ContentSecurityPolicy::SendReport)) {
callbacks->onError(WebServiceWorkerError(WebServiceWorkerError::ErrorTypeSecurity, String("Failed to register a ServiceWorker: The provided scriptURL ('" + scriptURL.getString() + "') violates the Content Security Policy.")));
return;
}
}
m_provider->registerServiceWorker(patternURL, scriptURL, callbacks.leakPtr());
}
| 173,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
Commit Message: Check partword is in range for # of partitions
and reformat tabs->spaces for readability.
Bug: 28556125
Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c
CWE ID: CWE-20 | int res_unpack(vorbis_info_residue *info,
vorbis_info *vi,oggpack_buffer *opb){
int j,k;
codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
memset(info,0,sizeof(*info));
info->type=oggpack_read(opb,16);
if(info->type>2 || info->type<0)goto errout;
info->begin=oggpack_read(opb,24);
info->end=oggpack_read(opb,24);
info->grouping=oggpack_read(opb,24)+1;
info->partitions=(char)(oggpack_read(opb,6)+1);
info->groupbook=(unsigned char)oggpack_read(opb,8);
if(info->groupbook>=ci->books)goto errout;
info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks));
info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks));
for(j=0;j<info->partitions;j++){
int cascade=oggpack_read(opb,3);
if(oggpack_read(opb,1))
cascade|=(oggpack_read(opb,5)<<3);
info->stagemasks[j]=cascade;
}
for(j=0;j<info->partitions;j++){
for(k=0;k<8;k++){
if((info->stagemasks[j]>>k)&1){
unsigned char book=(unsigned char)oggpack_read(opb,8);
if(book>=ci->books)goto errout;
info->stagebooks[j*8+k]=book;
if(k+1>info->stages)info->stages=k+1;
}else
info->stagebooks[j*8+k]=0xff;
}
}
if(oggpack_eop(opb))goto errout;
return 0;
errout:
res_clear_info(info);
return 1;
}
| 173,562 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build)
{
struct f2fs_nm_info *nm_i = NM_I(sbi);
struct free_nid *i;
struct nat_entry *ne;
int err;
/* 0 nid should not be used */
if (unlikely(nid == 0))
return false;
if (build) {
/* do not add allocated nids */
ne = __lookup_nat_cache(nm_i, nid);
if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
nat_get_blkaddr(ne) != NULL_ADDR))
return false;
}
i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
i->nid = nid;
i->state = NID_NEW;
if (radix_tree_preload(GFP_NOFS)) {
kmem_cache_free(free_nid_slab, i);
return true;
}
spin_lock(&nm_i->nid_list_lock);
err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true);
spin_unlock(&nm_i->nid_list_lock);
radix_tree_preload_end();
if (err) {
kmem_cache_free(free_nid_slab, i);
return true;
}
return true;
}
Commit Message: f2fs: fix race condition in between free nid allocator/initializer
In below concurrent case, allocated nid can be loaded into free nid cache
and be allocated again.
Thread A Thread B
- f2fs_create
- f2fs_new_inode
- alloc_nid
- __insert_nid_to_list(ALLOC_NID_LIST)
- f2fs_balance_fs_bg
- build_free_nids
- __build_free_nids
- scan_nat_page
- add_free_nid
- __lookup_nat_cache
- f2fs_add_link
- init_inode_metadata
- new_inode_page
- new_node_page
- set_node_addr
- alloc_nid_done
- __remove_nid_from_list(ALLOC_NID_LIST)
- __insert_nid_to_list(FREE_NID_LIST)
This patch makes nat cache lookup and free nid list operation being atomical
to avoid this race condition.
Signed-off-by: Jaegeuk Kim <[email protected]>
Signed-off-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-362 | static bool add_free_nid(struct f2fs_sb_info *sbi, nid_t nid, bool build)
{
struct f2fs_nm_info *nm_i = NM_I(sbi);
struct free_nid *i, *e;
struct nat_entry *ne;
int err = -EINVAL;
bool ret = false;
/* 0 nid should not be used */
if (unlikely(nid == 0))
return false;
i = f2fs_kmem_cache_alloc(free_nid_slab, GFP_NOFS);
i->nid = nid;
i->state = NID_NEW;
if (radix_tree_preload(GFP_NOFS))
goto err;
spin_lock(&nm_i->nid_list_lock);
if (build) {
/*
* Thread A Thread B
* - f2fs_create
* - f2fs_new_inode
* - alloc_nid
* - __insert_nid_to_list(ALLOC_NID_LIST)
* - f2fs_balance_fs_bg
* - build_free_nids
* - __build_free_nids
* - scan_nat_page
* - add_free_nid
* - __lookup_nat_cache
* - f2fs_add_link
* - init_inode_metadata
* - new_inode_page
* - new_node_page
* - set_node_addr
* - alloc_nid_done
* - __remove_nid_from_list(ALLOC_NID_LIST)
* - __insert_nid_to_list(FREE_NID_LIST)
*/
ne = __lookup_nat_cache(nm_i, nid);
if (ne && (!get_nat_flag(ne, IS_CHECKPOINTED) ||
nat_get_blkaddr(ne) != NULL_ADDR))
goto err_out;
e = __lookup_free_nid_list(nm_i, nid);
if (e) {
if (e->state == NID_NEW)
ret = true;
goto err_out;
}
}
ret = true;
err = __insert_nid_to_list(sbi, i, FREE_NID_LIST, true);
err_out:
spin_unlock(&nm_i->nid_list_lock);
radix_tree_preload_end();
err:
if (err)
kmem_cache_free(free_nid_slab, i);
return ret;
}
| 169,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: xfs_attr_rmtval_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen = args->valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
Commit Message: xfs: remote attribute overwrite causes transaction overrun
Commit e461fcb ("xfs: remote attribute lookups require the value
length") passes the remote attribute length in the xfs_da_args
structure on lookup so that CRC calculations and validity checking
can be performed correctly by related code. This, unfortunately has
the side effect of changing the args->valuelen parameter in cases
where it shouldn't.
That is, when we replace a remote attribute, the incoming
replacement stores the value and length in args->value and
args->valuelen, but then the lookup which finds the existing remote
attribute overwrites args->valuelen with the length of the remote
attribute being replaced. Hence when we go to create the new
attribute, we create it of the size of the existing remote
attribute, not the size it is supposed to be. When the new attribute
is much smaller than the old attribute, this results in a
transaction overrun and an ASSERT() failure on a debug kernel:
XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331
Fix this by keeping the remote attribute value length separate to
the attribute value length in the xfs_da_args structure. The enables
us to pass the length of the remote attribute to be removed without
overwriting the new attribute's length.
Also, ensure that when we save remote block contexts for a later
rename we zero the original state variables so that we don't confuse
the state of the attribute to be removes with the state of the new
attribute that we just added. [Spotted by Brain Foster.]
Signed-off-by: Dave Chinner <[email protected]>
Reviewed-by: Brian Foster <[email protected]>
Signed-off-by: Dave Chinner <[email protected]>
CWE ID: CWE-19 | xfs_attr_rmtval_get(
struct xfs_da_args *args)
{
struct xfs_bmbt_irec map[ATTR_RMTVALUE_MAPSIZE];
struct xfs_mount *mp = args->dp->i_mount;
struct xfs_buf *bp;
xfs_dablk_t lblkno = args->rmtblkno;
__uint8_t *dst = args->value;
int valuelen;
int nmap;
int error;
int blkcnt = args->rmtblkcnt;
int i;
int offset = 0;
trace_xfs_attr_rmtval_get(args);
ASSERT(!(args->flags & ATTR_KERNOVAL));
ASSERT(args->rmtvaluelen == args->valuelen);
valuelen = args->rmtvaluelen;
while (valuelen > 0) {
nmap = ATTR_RMTVALUE_MAPSIZE;
error = xfs_bmapi_read(args->dp, (xfs_fileoff_t)lblkno,
blkcnt, map, &nmap,
XFS_BMAPI_ATTRFORK);
if (error)
return error;
ASSERT(nmap >= 1);
for (i = 0; (i < nmap) && (valuelen > 0); i++) {
xfs_daddr_t dblkno;
int dblkcnt;
ASSERT((map[i].br_startblock != DELAYSTARTBLOCK) &&
(map[i].br_startblock != HOLESTARTBLOCK));
dblkno = XFS_FSB_TO_DADDR(mp, map[i].br_startblock);
dblkcnt = XFS_FSB_TO_BB(mp, map[i].br_blockcount);
error = xfs_trans_read_buf(mp, NULL, mp->m_ddev_targp,
dblkno, dblkcnt, 0, &bp,
&xfs_attr3_rmt_buf_ops);
if (error)
return error;
error = xfs_attr_rmtval_copyout(mp, bp, args->dp->i_ino,
&offset, &valuelen,
&dst);
xfs_buf_relse(bp);
if (error)
return error;
/* roll attribute extent map forwards */
lblkno += map[i].br_blockcount;
blkcnt -= map[i].br_blockcount;
}
}
ASSERT(valuelen == 0);
return 0;
}
| 166,739 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromotingInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
CHECK(!initialized_);
initialized_ = true;
VLOG(1) << "Started ChromotingInstance::Init";
if (!media::IsMediaLibraryInitialized()) {
LOG(ERROR) << "Media library not initialized.";
return false;
}
net::EnableSSLServerSockets();
context_.Start();
scoped_refptr<FrameConsumerProxy> consumer_proxy =
new FrameConsumerProxy(plugin_task_runner_);
rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(),
context_.decode_task_runner(),
consumer_proxy);
view_.reset(new PepperView(this, &context_, rectangle_decoder_.get()));
consumer_proxy->Attach(view_->AsWeakPtr());
return true;
}
Commit Message: Restrict the Chromoting client plugin to use by extensions & apps.
BUG=160456
Review URL: https://chromiumcodereview.appspot.com/11365276
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168289 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool ChromotingInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
CHECK(!initialized_);
initialized_ = true;
VLOG(1) << "Started ChromotingInstance::Init";
if (!media::IsMediaLibraryInitialized()) {
LOG(ERROR) << "Media library not initialized.";
return false;
}
// Check that the calling content is part of an app or extension.
if (!IsCallerAppOrExtension()) {
LOG(ERROR) << "Not an app or extension";
return false;
}
net::EnableSSLServerSockets();
context_.Start();
scoped_refptr<FrameConsumerProxy> consumer_proxy =
new FrameConsumerProxy(plugin_task_runner_);
rectangle_decoder_ = new RectangleUpdateDecoder(context_.main_task_runner(),
context_.decode_task_runner(),
consumer_proxy);
view_.reset(new PepperView(this, &context_, rectangle_decoder_.get()));
consumer_proxy->Attach(view_->AsWeakPtr());
return true;
}
| 170,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.