project
stringclasses 765
values | commit_id
stringlengths 6
81
| func
stringlengths 19
482k
| vul
int64 0
1
| CVE ID
stringlengths 13
16
| CWE ID
stringclasses 13
values | CWE Name
stringclasses 13
values | CWE Description
stringclasses 13
values | Potential Mitigation
stringclasses 11
values | __index_level_0__
int64 0
23.9k
|
---|---|---|---|---|---|---|---|---|---|
qemu | b16c129daf0fed91febbb88de23dae8271c8898a | static int ehci_init_transfer(EHCIPacket *p)
{
uint32_t cpage, offset, bytes, plen;
dma_addr_t page;
cpage = get_field(p->qtd.token, QTD_TOKEN_CPAGE);
bytes = get_field(p->qtd.token, QTD_TOKEN_TBYTES);
offset = p->qtd.bufptr[0] & ~QTD_BUFPTR_MASK;
qemu_sglist_init(&p->sgl, p->queue->ehci->device, 5, p->queue->ehci->as);
while (bytes > 0) {
if (cpage > 4) {
fprintf(stderr, "cpage out of range (%d)\n", cpage);
return -1;
}
page = p->qtd.bufptr[cpage] & QTD_BUFPTR_MASK;
page += offset;
plen = bytes;
if (plen > 4096 - offset) {
plen = 4096 - offset;
offset = 0;
cpage++;
}
qemu_sglist_add(&p->sgl, page, plen);
bytes -= plen;
}
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,523 |
Android | e629194c62a9a129ce378e08cb1059a8a53f1795 | WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice,
UWORD8 u1_nal_ref_idc,
dec_struct_t *ps_dec /* Decoder parameters */
)
{
dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm;
dec_pic_params_t *ps_pps;
dec_seq_params_t *ps_seq;
dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice;
pocstruct_t s_tmp_poc;
WORD32 i_delta_poc[2];
WORD32 i4_poc = 0;
UWORD16 u2_first_mb_in_slice, u2_frame_num;
UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type;
UWORD32 u4_idr_pic_id = 0;
UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type;
UWORD8 u1_nal_unit_type;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst;
WORD8 i1_is_end_of_poc;
WORD32 ret, end_of_frame;
WORD32 prev_slice_err, num_mb_skipped;
UWORD8 u1_mbaff;
pocstruct_t *ps_cur_poc;
UWORD32 u4_temp;
WORD32 i_temp;
UWORD32 u4_call_end_of_pic = 0;
/* read FirstMbInSlice and slice type*/
ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0;
u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u2_first_mb_in_slice
> (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs))
{
return ERROR_CORRUPTED_SLICE;
}
/*we currently don not support ASO*/
if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag)
<= ps_dec->u2_cur_mb_addr) && (ps_dec->u2_cur_mb_addr != 0)
&& (ps_dec->u4_first_slice_in_pic != 0))
{
return ERROR_CORRUPTED_SLICE;
}
COPYTHECONTEXT("SH: first_mb_in_slice",u2_first_mb_in_slice);
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > 9)
return ERROR_INV_SLC_TYPE_T;
u1_slice_type = u4_temp;
COPYTHECONTEXT("SH: slice_type",(u1_slice_type));
ps_dec->u1_sl_typ_5_9 = 0;
/* Find Out the Slice Type is 5 to 9 or not then Set the Flag */
/* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/
/* will be of same type of current */
if(u1_slice_type > 4)
{
u1_slice_type -= 5;
ps_dec->u1_sl_typ_5_9 = 1;
}
{
UWORD32 skip;
if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB)
|| (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB))
{
UWORD32 u4_bit_stream_offset = 0;
if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL)
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else if((I_SLICE == u1_slice_type)
&& (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames))
{
skip = 0;
ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE;
}
else
{
skip = 1;
}
/* If one frame worth of data is already skipped, do not skip the next one */
if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped))
{
skip = 0;
}
if(skip)
{
ps_dec->u4_prev_nal_skipped = 1;
ps_dec->i4_dec_skip_mode = IVD_SKIP_PB;
return 0;
}
else
{
/* If the previous NAL was skipped, then
do not process that buffer in this call.
Return to app and process it in the next call.
This is necessary to handle cases where I/IDR is not complete in
the current buffer and application intends to fill the remaining part of the bitstream
later. This ensures we process only frame worth of data in every call */
if(1 == ps_dec->u4_prev_nal_skipped)
{
ps_dec->u4_return_to_app = 1;
return 0;
}
}
}
}
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp & MASK_ERR_PIC_SET_ID)
return ERROR_INV_SPS_PPS_T;
/* discard slice if pic param is invalid */
COPYTHECONTEXT("SH: pic_parameter_set_id", u4_temp);
ps_pps = &ps_dec->ps_pps[u4_temp];
if(FALSE == ps_pps->u1_is_valid)
{
return ERROR_INV_SPS_PPS_T;
}
ps_seq = ps_pps->ps_sps;
if(!ps_seq)
return ERROR_INV_SPS_PPS_T;
if(FALSE == ps_seq->u1_is_valid)
return ERROR_INV_SPS_PPS_T;
/* Get the frame num */
u2_frame_num = ih264d_get_bits_h264(ps_bitstrm,
ps_seq->u1_bits_in_frm_num);
COPYTHECONTEXT("SH: frame_num", u2_frame_num);
/* Get the field related flags */
if(!ps_seq->u1_frame_mbs_only_flag)
{
u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: field_pic_flag", u1_field_pic_flag);
u1_bottom_field_flag = 0;
if(u1_field_pic_flag)
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld;
u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm);
COPYTHECONTEXT("SH: bottom_field_flag", u1_bottom_field_flag);
}
else
{
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
}
else
{
u1_field_pic_flag = 0;
u1_bottom_field_flag = 0;
ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan;
}
u1_nal_unit_type = SLICE_NAL;
if(u1_is_idr_slice)
{
if(0 == u1_field_pic_flag)
{
ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY;
}
u1_nal_unit_type = IDR_SLICE_NAL;
u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
if(u4_idr_pic_id > 65535)
return ERROR_INV_SPS_PPS_T;
COPYTHECONTEXT("SH: ", u4_idr_pic_id);
}
/* read delta pic order count information*/
i_delta_poc[0] = i_delta_poc[1] = 0;
s_tmp_poc.i4_pic_order_cnt_lsb = 0;
s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0;
u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type;
if(u1_pic_order_cnt_type == 0)
{
i_temp = ih264d_get_bits_h264(
ps_bitstrm,
ps_seq->u1_log2_max_pic_order_cnt_lsb_minus);
if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb)
return ERROR_INV_SPS_PPS_T;
s_tmp_poc.i4_pic_order_cnt_lsb = i_temp;
COPYTHECONTEXT("SH: pic_order_cnt_lsb", s_tmp_poc.i4_pic_order_cnt_lsb);
if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt_bottom",
s_tmp_poc.i4_delta_pic_order_cnt_bottom);
}
}
s_tmp_poc.i4_delta_pic_order_cnt[0] = 0;
s_tmp_poc.i4_delta_pic_order_cnt[1] = 0;
if(u1_pic_order_cnt_type == 1
&& (!ps_seq->u1_delta_pic_order_always_zero_flag))
{
s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst,
pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[0]",
s_tmp_poc.i4_delta_pic_order_cnt[0]);
if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag)
{
s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev(
pu4_bitstrm_ofst, pu4_bitstrm_buf);
COPYTHECONTEXT("SH: delta_pic_order_cnt[1]",
s_tmp_poc.i4_delta_pic_order_cnt[1]);
}
}
if(ps_pps->u1_redundant_pic_cnt_present_flag)
{
u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf);
if(u4_temp > MAX_REDUNDANT_PIC_CNT)
return ERROR_INV_SPS_PPS_T;
u1_redundant_pic_cnt = u4_temp;
COPYTHECONTEXT("SH: redundant_pic_cnt", u1_redundant_pic_cnt);
}
/*--------------------------------------------------------------------*/
/* Check if the slice is part of new picture */
/*--------------------------------------------------------------------*/
i1_is_end_of_poc = 0;
if(!ps_dec->u1_first_slice_in_stream)
{
i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc,
&s_tmp_poc, &ps_dec->s_cur_pic_poc,
ps_cur_slice, u1_pic_order_cnt_type,
u1_nal_unit_type, u4_idr_pic_id,
u1_field_pic_flag,
u1_bottom_field_flag);
/* since we support only Full frame decode, every new process should
* process a new pic
*/
if((ps_dec->u4_first_slice_in_pic == 2) && (i1_is_end_of_poc == 0))
{
/* if it is the first slice is process call ,it should be a new frame. If it is not
* reject current pic and dont add it to dpb
*/
ps_dec->ps_dec_err_status->u1_err_flag |= REJECT_CUR_PIC;
i1_is_end_of_poc = 1;
}
else
{
/* reset REJECT_CUR_PIC */
ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC;
}
}
/*--------------------------------------------------------------------*/
/* Check for error in slice and parse the missing/corrupted MB's */
/* as skip-MB's in an inserted P-slice */
/*--------------------------------------------------------------------*/
u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag);
prev_slice_err = 0;
if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream)
{
if(u2_frame_num != ps_dec->u2_prv_frame_num
&& ps_dec->u1_top_bottom_decoded != 0
&& ps_dec->u1_top_bottom_decoded
!= (TOP_FIELD_ONLY | BOT_FIELD_ONLY))
{
ps_dec->u1_dangling_field = 1;
if(ps_dec->u4_first_slice_in_pic)
{
prev_slice_err = 1;
}
else
{
prev_slice_err = 2;
}
if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY)
ps_cur_slice->u1_bottom_field_flag = 1;
else
ps_cur_slice->u1_bottom_field_flag = 0;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &ps_dec->s_cur_pic_poc;
u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL;
}
else if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice > 0)
{
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
ps_cur_poc = &s_tmp_poc;
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->i4_pic_order_cnt_lsb =
s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
}
}
else
{
if(ps_dec->u4_first_slice_in_pic)
{
/* if valid slice header is not decoded do start of pic processing
* since in the current process call, frame num is not updated in the slice structure yet
* ih264d_is_end_of_pic is checked with valid frame num of previous process call,
* although i1_is_end_of_poc is set there could be more slices in the frame,
* so conceal only till cur slice */
prev_slice_err = 1;
num_mb_skipped = u2_first_mb_in_slice << u1_mbaff;
}
else
{
/* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame
* completely */
prev_slice_err = 2;
num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
- ps_dec->u2_total_mbs_coded;
}
ps_cur_poc = &s_tmp_poc;
}
}
else
{
if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded)
{
prev_slice_err = 2;
num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff)
- ps_dec->u2_total_mbs_coded;
ps_cur_poc = &s_tmp_poc;
}
else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded)
{
return ERROR_CORRUPTED_SLICE;
}
}
if(prev_slice_err)
{
ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err);
if(ps_dec->u1_dangling_field == 1)
{
ps_dec->u1_second_field = 1 - ps_dec->u1_second_field;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_dec->u2_prv_frame_num = u2_frame_num;
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_DANGLING_FIELD_IN_PIC;
}
if(prev_slice_err == 2)
{
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_INCOMPLETE_FRAME;
}
if(ps_dec->u2_total_mbs_coded
>= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)
{
/* return if all MBs in frame are parsed*/
ps_dec->u1_first_slice_in_stream = 0;
return ERROR_IN_LAST_SLICE_OF_PIC;
}
if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC)
{
ih264d_err_pic_dispbuf_mgr(ps_dec);
return ERROR_NEW_FRAME_EXPECTED;
}
if(ret != OK)
return ret;
i1_is_end_of_poc = 0;
}
if (ps_dec->u4_first_slice_in_pic == 0)
ps_dec->ps_parse_cur_slice++;
ps_dec->u1_slice_header_done = 0;
/*--------------------------------------------------------------------*/
/* If the slice is part of new picture, do End of Pic processing. */
/*--------------------------------------------------------------------*/
if(!ps_dec->u1_first_slice_in_stream)
{
UWORD8 uc_mbs_exceed = 0;
if(ps_dec->u2_total_mbs_coded
== (ps_dec->ps_cur_sps->u2_max_mb_addr + 1))
{
/*u2_total_mbs_coded is forced to u2_max_mb_addr+ 1 at the end of decode ,so
,if it is first slice in pic dont consider u2_total_mbs_coded to detect new picture */
if(ps_dec->u4_first_slice_in_pic == 0)
uc_mbs_exceed = 1;
}
if(i1_is_end_of_poc || uc_mbs_exceed)
{
if(1 == ps_dec->u1_last_pic_not_decoded)
{
ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec);
if(ret != OK)
return ret;
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
#if WIN32
H264_DEC_DEBUG_PRINT(" ------ PIC SKIPPED ------\n");
#endif
return RET_LAST_SKIP;
}
else
{
ret = ih264d_end_of_pic(ps_dec, u1_is_idr_slice, u2_frame_num);
if(ret != OK)
return ret;
}
}
}
if(u1_field_pic_flag)
{
ps_dec->u2_prv_frame_num = u2_frame_num;
}
if(ps_cur_slice->u1_mmco_equalto5)
{
WORD32 i4_temp_poc;
WORD32 i4_top_field_order_poc, i4_bot_field_order_poc;
if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair
{
i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
i4_bot_field_order_poc =
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
i4_temp_poc = MIN(i4_top_field_order_poc,
i4_bot_field_order_poc);
}
else if(!ps_cur_slice->u1_bottom_field_flag)
i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt;
else
i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_top_field_order_cnt;
ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc
- ps_dec->ps_cur_pic->i4_bottom_field_order_cnt;
ps_dec->ps_cur_pic->i4_poc = i4_temp_poc;
ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num,
&ps_dec->s_prev_pic_poc,
&s_tmp_poc, ps_cur_slice, ps_pps,
u1_nal_ref_idc,
u1_bottom_field_flag,
u1_field_pic_flag, &i4_poc);
if(ret != OK)
return ret;
/* Display seq no calculations */
if(i4_poc >= ps_dec->i4_max_poc)
ps_dec->i4_max_poc = i4_poc;
/* IDR Picture or POC wrap around */
if(i4_poc == 0)
{
ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq
+ ps_dec->i4_max_poc
+ ps_dec->u1_max_dec_frame_buffering + 1;
ps_dec->i4_max_poc = 0;
}
}
/*--------------------------------------------------------------------*/
/* Copy the values read from the bitstream to the slice header and then*/
/* If the slice is first slice in picture, then do Start of Picture */
/* processing. */
/*--------------------------------------------------------------------*/
ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0];
ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1];
ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id;
ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice;
ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag;
ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag;
ps_cur_slice->u1_slice_type = u1_slice_type;
ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb;
ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type;
ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt;
ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc;
ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type;
if(ps_seq->u1_frame_mbs_only_flag)
ps_cur_slice->u1_direct_8x8_inference_flag =
ps_seq->u1_direct_8x8_inference_flag;
else
ps_cur_slice->u1_direct_8x8_inference_flag = 1;
if(u1_slice_type == B_SLICE)
{
ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264(
ps_bitstrm);
COPYTHECONTEXT("SH: direct_spatial_mv_pred_flag",
ps_cur_slice->u1_direct_spatial_mv_pred_flag);
if(ps_cur_slice->u1_direct_spatial_mv_pred_flag)
ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct;
else
ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct;
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB;
}
else
{
if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag)))
ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff;
}
if(ps_dec->u4_first_slice_in_pic == 2)
{
if(u2_first_mb_in_slice == 0)
{
ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps);
if(ret != OK)
return ret;
}
ps_dec->u4_output_present = 0;
{
ih264d_get_next_display_field(ps_dec,
ps_dec->ps_out_buffer,
&(ps_dec->s_disp_op));
/* If error code is non-zero then there is no buffer available for display,
hence avoid format conversion */
if(0 != ps_dec->s_disp_op.u4_error_code)
{
ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht;
}
else
ps_dec->u4_output_present = 1;
}
if(ps_dec->u1_separate_parse == 1)
{
if(ps_dec->u4_dec_thread_created == 0)
{
ithread_create(ps_dec->pv_dec_thread_handle, NULL,
(void *)ih264d_decode_picture_thread,
(void *)ps_dec);
ps_dec->u4_dec_thread_created = 1;
}
if((ps_dec->u4_num_cores == 3) &&
((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag)
&& (ps_dec->u4_bs_deblk_thread_created == 0))
{
ps_dec->u4_start_recon_deblk = 0;
ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL,
(void *)ih264d_recon_deblk_thread,
(void *)ps_dec);
ps_dec->u4_bs_deblk_thread_created = 1;
}
}
}
/* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */
{
UWORD8 uc_nofield_nombaff;
uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0)
&& (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0)
&& (u1_slice_type != B_SLICE)
&& (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0));
/* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */
if(uc_nofield_nombaff)
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_bp;
}
else
{
ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp;
ps_dec->p_motion_compensate = ih264d_motion_compensate_mp;
}
}
/*
* Decide whether to decode the current picture or not
*/
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if(ps_err->u4_frm_sei_sync == u2_frame_num)
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT;
}
ps_err->u4_cur_frm = u2_frame_num;
}
/* Decision for decoding if the picture is to be skipped */
{
WORD32 i4_skip_b_pic, i4_skip_p_pic;
i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT)
&& (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT)
&& (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc);
/**************************************************************/
/* Skip the B picture if skip mask is set for B picture and */
/* Current B picture is a non reference B picture or there is */
/* no user for reference B picture */
/**************************************************************/
if(i4_skip_b_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
/* Don't decode the picture in SKIP-B mode if that picture is B */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
/**************************************************************/
/* Skip the P picture if skip mask is set for P picture and */
/* Current P picture is a non reference P picture or there is */
/* no user for reference P picture */
/**************************************************************/
if(i4_skip_p_pic)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
/* Don't decode the picture in SKIP-P mode if that picture is P */
/* and also it is not to be used as a reference picture */
ps_dec->u1_last_pic_not_decoded = 1;
return OK;
}
}
{
UWORD16 u2_mb_x, u2_mb_y;
ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice
<< ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE)
- SUB_BLK_SIZE;
if(u2_first_mb_in_slice)
{
UWORD8 u1_mb_aff;
UWORD8 u1_field_pic;
UWORD16 u2_frm_wd_in_mbs;
u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs;
u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag;
u1_field_pic = ps_cur_slice->u1_field_pic_flag;
{
UWORD32 x_offset;
UWORD32 y_offset;
UWORD32 u4_frame_stride;
tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs);
u2_mb_y <<= u1_mb_aff;
if((u2_mb_x > u2_frm_wd_in_mbs - 1)
|| (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1))
{
return ERROR_CORRUPTED_SLICE;
}
u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic;
x_offset = u2_mb_x << 4;
y_offset = (u2_mb_y * u4_frame_stride) << 4;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset
+ y_offset;
u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic;
x_offset >>= 1;
y_offset = (u2_mb_y * u4_frame_stride) << 3;
x_offset *= YUV420SP_FACTOR;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset
+ y_offset;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset
+ y_offset;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
if(ps_dec->u1_separate_parse == 1)
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
else
{
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic
+ (u2_first_mb_in_slice << u1_mb_aff);
}
ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff);
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv
+ ((u2_first_mb_in_slice << u1_mb_aff) << 4);
}
}
else
{
tfr_ctxt_t *ps_trns_addr;
if(ps_dec->u1_separate_parse)
{
ps_trns_addr = &ps_dec->s_tran_addrecon_parse;
}
else
{
ps_trns_addr = &ps_dec->s_tran_addrecon;
}
u2_mb_x = 0xffff;
u2_mb_y = 0;
ps_dec->u2_cur_mb_addr = 0;
ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic;
ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv;
ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1;
ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2;
ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3;
ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y;
ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u;
ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v;
}
ps_dec->ps_part = ps_dec->ps_parse_part_params;
ps_dec->u2_mbx =
(MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby =
(DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs));
ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag;
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
}
/* RBSP stop bit is used for CABAC decoding*/
ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode;
ps_dec->u1_B = (u1_slice_type == B_SLICE);
ps_dec->u4_next_mb_skip = 0;
ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice =
ps_dec->ps_cur_slice->u2_first_mb_in_slice;
ps_dec->ps_parse_cur_slice->slice_type =
ps_dec->ps_cur_slice->u1_slice_type;
ps_dec->u4_start_recon_deblk = 1;
{
WORD32 num_entries;
WORD32 size;
UWORD8 *pu1_buf;
num_entries = MAX_FRAMES;
if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) &&
(0 == ps_dec->i4_display_delay))
{
num_entries = 1;
}
num_entries = ((2 * num_entries) + 1);
if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc)
{
num_entries *= 2;
}
size = num_entries * sizeof(void *);
size += PAD_MAP_IDX_POC * sizeof(void *);
pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf;
pu1_buf += size * ps_dec->u2_cur_slice_num;
ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf;
}
if(ps_dec->u1_separate_parse)
{
ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data;
}
else
{
ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
}
ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat;
if(u1_slice_type == I_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT;
ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice);
if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE)
ps_dec->i4_pic_type = I_SLICE;
}
else if(u1_slice_type == P_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT;
ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
if(ps_dec->i4_pic_type != B_SLICE)
ps_dec->i4_pic_type = P_SLICE;
}
else if(u1_slice_type == B_SLICE)
{
ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT;
ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice);
ps_dec->u1_pr_sl_type = u1_slice_type;
ps_dec->i4_pic_type = B_SLICE;
}
else
return ERROR_INV_SLC_TYPE_T;
if(ps_dec->u1_slice_header_done)
{
/* set to zero to indicate a valid slice has been decoded */
/* first slice header successfully decoded */
ps_dec->u4_first_slice_in_pic = 0;
ps_dec->u1_first_slice_in_stream = 0;
}
if(ret != OK)
return ret;
ps_dec->u2_cur_slice_num++;
/* storing last Mb X and MbY of the slice */
ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx;
ps_dec->i2_prev_slice_mby = ps_dec->u2_mby;
/* End of Picture detection */
if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1))
{
ps_dec->u1_pic_decode_done = 1;
}
{
dec_err_status_t * ps_err = ps_dec->ps_dec_err_status;
if((ps_err->u1_err_flag & REJECT_PB_PICS)
&& (ps_err->u1_cur_pic_type == PIC_TYPE_I))
{
ps_err->u1_err_flag = ACCEPT_ALL_PICS;
}
}
PRINT_BIN_BIT_RATIO(ps_dec)
return ret;
}
| 1 | CVE-2016-3741 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 220 |
linux | 5d6751eaff672ea77642e74e92e6c0ac7f9709ab | static int ath6kl_wmi_pstream_timeout_event_rx(struct wmi *wmi, u8 *datap,
int len)
{
struct wmi_pstream_timeout_event *ev;
if (len < sizeof(struct wmi_pstream_timeout_event))
return -EINVAL;
ev = (struct wmi_pstream_timeout_event *) datap;
/*
* When the pstream (fat pipe == AC) timesout, it means there were
* no thinStreams within this pstream & it got implicitly created
* due to data flow on this AC. We start the inactivity timer only
* for implicitly created pstream. Just reset the host state.
*/
spin_lock_bh(&wmi->lock);
wmi->stream_exist_for_ac[ev->traffic_class] = 0;
wmi->fat_pipe_exist &= ~(1 << ev->traffic_class);
spin_unlock_bh(&wmi->lock);
/* Indicate inactivity to driver layer for this fatpipe (pstream) */
ath6kl_indicate_tx_activity(wmi->parent_dev, ev->traffic_class, false);
return 0;
} | 1 | CVE-2019-15926 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 8,352 |
tcpdump | 13ab8d18617d616c7d343530f8a842e7143fb5cc | atmarp_addr_print(netdissect_options *ndo,
const u_char *ha, u_int ha_len, const u_char *srca,
u_int srca_len)
{
if (ha_len == 0)
ND_PRINT((ndo, "<No address>"));
else {
ND_PRINT((ndo, "%s", linkaddr_string(ndo, ha, LINKADDR_ATM, ha_len)));
if (srca_len != 0)
ND_PRINT((ndo, ",%s",
linkaddr_string(ndo, srca, LINKADDR_ATM, srca_len)));
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,957 |
FFmpeg | 9807d3976be0e92e4ece3b4b1701be894cd7c2e1 | static int pva_probe(AVProbeData * pd) {
const unsigned char *buf = pd->buf;
int len = pva_check(buf);
if (len < 0)
return 0;
if (pd->buf_size >= len + 8 &&
pva_check(buf + len) >= 0)
return AVPROBE_SCORE_EXTENSION;
return AVPROBE_SCORE_MAX / 4;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,770 |
ekiga | 02654fc949722a78d41fcffac8687d73d8574647 | plugin_parse_directory (Ekiga::KickStart& kickstart,
const gchar* path)
{
g_return_if_fail (path != NULL);
GError* error = NULL;
GDir* directory = g_dir_open (path, 0, &error);
#if DEBUG
std::cout << "Trying to load plugins in " << path << "... ";
#endif
if (directory != NULL) {
#if DEBUG
std::cout << "open succeeded" << std::endl;
#endif
const gchar* name = g_dir_read_name (directory);
while (name) {
gchar* filename = g_build_filename (path, name, NULL);
/* There is something to say here : it is unsafe to test then decide
* what to do, because things could have changed between the time we
* test and the time we act. But I think it's good enough for the
* purpose of this code. If I'm wrong, report as a bug.
* (Snark, 20090618)
*/
if (g_str_has_suffix (filename, G_MODULE_SUFFIX))
plugin_parse_file (kickstart, filename);
else
plugin_parse_directory (kickstart, filename);
g_free (filename);
name = g_dir_read_name (directory);
}
g_dir_close (directory);
} else {
#if DEBUG
std::cout << "failure: " << error->message << std::endl;
#endif
g_error_free (error);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,407 |
linux | 44afb3a04391a74309d16180d1e4f8386fdfa745 | i915_gem_execbuffer_reserve(struct intel_ring_buffer *ring,
struct drm_file *file,
struct list_head *objects)
{
drm_i915_private_t *dev_priv = ring->dev->dev_private;
struct drm_i915_gem_object *obj;
int ret, retry;
bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
struct list_head ordered_objects;
INIT_LIST_HEAD(&ordered_objects);
while (!list_empty(objects)) {
struct drm_i915_gem_exec_object2 *entry;
bool need_fence, need_mappable;
obj = list_first_entry(objects,
struct drm_i915_gem_object,
exec_list);
entry = obj->exec_entry;
need_fence =
has_fenced_gpu_access &&
entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode != I915_TILING_NONE;
need_mappable =
entry->relocation_count ? true : need_fence;
if (need_mappable)
list_move(&obj->exec_list, &ordered_objects);
else
list_move_tail(&obj->exec_list, &ordered_objects);
obj->base.pending_read_domains = 0;
obj->base.pending_write_domain = 0;
}
list_splice(&ordered_objects, objects);
/* Attempt to pin all of the buffers into the GTT.
* This is done in 3 phases:
*
* 1a. Unbind all objects that do not match the GTT constraints for
* the execbuffer (fenceable, mappable, alignment etc).
* 1b. Increment pin count for already bound objects.
* 2. Bind new objects.
* 3. Decrement pin count.
*
* This avoid unnecessary unbinding of later objects in order to makr
* room for the earlier objects *unless* we need to defragment.
*/
retry = 0;
do {
ret = 0;
/* Unbind any ill-fitting objects or pin. */
list_for_each_entry(obj, objects, exec_list) {
struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
bool need_fence, need_mappable;
if (!obj->gtt_space)
continue;
need_fence =
has_fenced_gpu_access &&
entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode != I915_TILING_NONE;
need_mappable =
entry->relocation_count ? true : need_fence;
if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
(need_mappable && !obj->map_and_fenceable))
ret = i915_gem_object_unbind(obj);
else
ret = pin_and_fence_object(obj, ring);
if (ret)
goto err;
}
/* Bind fresh objects */
list_for_each_entry(obj, objects, exec_list) {
if (obj->gtt_space)
continue;
ret = pin_and_fence_object(obj, ring);
if (ret) {
int ret_ignore;
/* This can potentially raise a harmless
* -EINVAL if we failed to bind in the above
* call. It cannot raise -EINTR since we know
* that the bo is freshly bound and so will
* not need to be flushed or waited upon.
*/
ret_ignore = i915_gem_object_unbind(obj);
(void)ret_ignore;
WARN_ON(obj->gtt_space);
break;
}
}
/* Decrement pin count for bound objects */
list_for_each_entry(obj, objects, exec_list) {
struct drm_i915_gem_exec_object2 *entry;
if (!obj->gtt_space)
continue;
entry = obj->exec_entry;
if (entry->flags & __EXEC_OBJECT_HAS_FENCE) {
i915_gem_object_unpin_fence(obj);
entry->flags &= ~__EXEC_OBJECT_HAS_FENCE;
}
i915_gem_object_unpin(obj);
/* ... and ensure ppgtt mapping exist if needed. */
if (dev_priv->mm.aliasing_ppgtt && !obj->has_aliasing_ppgtt_mapping) {
i915_ppgtt_bind_object(dev_priv->mm.aliasing_ppgtt,
obj, obj->cache_level);
obj->has_aliasing_ppgtt_mapping = 1;
}
}
if (ret != -ENOSPC || retry > 1)
return ret;
/* First attempt, just clear anything that is purgeable.
* Second attempt, clear the entire GTT.
*/
ret = i915_gem_evict_everything(ring->dev, retry == 0);
if (ret)
return ret;
retry++;
} while (1);
err:
list_for_each_entry_continue_reverse(obj, objects, exec_list) {
struct drm_i915_gem_exec_object2 *entry;
if (!obj->gtt_space)
continue;
entry = obj->exec_entry;
if (entry->flags & __EXEC_OBJECT_HAS_FENCE) {
i915_gem_object_unpin_fence(obj);
entry->flags &= ~__EXEC_OBJECT_HAS_FENCE;
}
i915_gem_object_unpin(obj);
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,791 |
linux | 75b0cea7bf307f362057cc778efe89af4c615354 | static ssize_t acpi_table_oem_revision_show(struct config_item *cfg, char *str)
{
struct acpi_table_header *h = get_header(cfg);
if (!h)
return -EINVAL;
return sprintf(str, "%d\n", h->oem_revision);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,186 |
ImageMagick | 50f54462076648ac2e36c3f58f4dadd4babbf1c9 | static Image *ReadTXTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
colorspace[MagickPathExtent],
text[MagickPathExtent];
Image
*image;
long
x_offset,
y_offset;
PixelInfo
pixel;
MagickBooleanType
status;
QuantumAny
range;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
count,
type,
y;
unsigned long
depth,
height,
max_value,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) ResetMagickMemory(text,0,sizeof(text));
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
width=0;
height=0;
max_value=0;
*colorspace='\0';
count=(ssize_t) sscanf(text+32,"%lu,%lu,%lu,%s",&width,&height,&max_value,
colorspace);
if ((count != 4) || (width == 0) || (height == 0) || (max_value == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=width;
image->rows=height;
for (depth=1; (GetQuantumRange(depth)+1) < max_value; depth++)
if (depth >= 64)
break;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
LocaleLower(colorspace);
i=(ssize_t) strlen(colorspace)-1;
image->alpha_trait=UndefinedPixelTrait;
if ((i > 0) && (colorspace[i] == 'a'))
{
colorspace[i]='\0';
image->alpha_trait=BlendPixelTrait;
}
type=ParseCommandOption(MagickColorspaceOptions,MagickFalse,colorspace);
if (type < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,(ColorspaceType) type,exception);
GetPixelInfo(image,&pixel);
range=GetQuantumRange(image->depth);
for (y=0; y < (ssize_t) image->rows; y++)
{
double
alpha,
black,
blue,
green,
red;
red=0.0;
green=0.0;
blue=0.0;
black=0.0;
alpha=0.0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ReadBlobString(image,text) == (char *) NULL)
break;
switch (image->colorspace)
{
case GRAYColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&alpha);
green=red;
blue=red;
break;
}
count=(ssize_t) sscanf(text,"%ld,%ld: (%lf%*[%,]",&x_offset,
&y_offset,&red);
green=red;
blue=red;
break;
}
case CMYKColorspace:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&black,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue,&black);
break;
}
default:
{
if (image->alpha_trait != UndefinedPixelTrait)
{
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]%lf%*[%,]",
&x_offset,&y_offset,&red,&green,&blue,&alpha);
break;
}
count=(ssize_t) sscanf(text,
"%ld,%ld: (%lf%*[%,]%lf%*[%,]%lf%*[%,]",&x_offset,
&y_offset,&red,&green,&blue);
break;
}
}
if (strchr(text,'%') != (char *) NULL)
{
red*=0.01*range;
green*=0.01*range;
blue*=0.01*range;
black*=0.01*range;
alpha*=0.01*range;
}
if (image->colorspace == LabColorspace)
{
green+=(range+1)/2.0;
blue+=(range+1)/2.0;
}
pixel.red=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (red+0.5),
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (green+0.5),
range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (blue+0.5),
range);
pixel.black=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (black+0.5),
range);
pixel.alpha=(MagickRealType) ScaleAnyToQuantum((QuantumAny) (alpha+0.5),
range);
q=GetAuthenticPixels(image,(ssize_t) x_offset,(ssize_t) y_offset,1,1,
exception);
if (q == (Quantum *) NULL)
continue;
SetPixelViaPixelInfo(image,&pixel,q);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
(void) ReadBlobString(image,text);
if (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (LocaleNCompare((char *) text,MagickID,strlen(MagickID)) == 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,105 |
linux-2.6 | 7b82dc0e64e93f430182f36b46b79fcee87d3532 | struct file *lookup_instantiate_filp(struct nameidata *nd, struct dentry *dentry,
int (*open)(struct inode *, struct file *))
{
if (IS_ERR(nd->intent.open.file))
goto out;
if (IS_ERR(dentry))
goto out_err;
nd->intent.open.file = __dentry_open(dget(dentry), mntget(nd->mnt),
nd->intent.open.flags - 1,
nd->intent.open.file,
open);
out:
return nd->intent.open.file;
out_err:
release_open_intent(nd);
nd->intent.open.file = (struct file *)dentry;
goto out;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,818 |
Android | 552a3b5df2a6876d10da20f72e4cc0d44ac2c790 | void encodeBase64(
const void *_data, size_t size, AString *out) {
out->clear();
const uint8_t *data = (const uint8_t *)_data;
size_t i;
for (i = 0; i < (size / 3) * 3; i += 3) {
uint8_t x1 = data[i];
uint8_t x2 = data[i + 1];
uint8_t x3 = data[i + 2];
out->append(encode6Bit(x1 >> 2));
out->append(encode6Bit((x1 << 4 | x2 >> 4) & 0x3f));
out->append(encode6Bit((x2 << 2 | x3 >> 6) & 0x3f));
out->append(encode6Bit(x3 & 0x3f));
}
switch (size % 3) {
case 0:
break;
case 2:
{
uint8_t x1 = data[i];
uint8_t x2 = data[i + 1];
out->append(encode6Bit(x1 >> 2));
out->append(encode6Bit((x1 << 4 | x2 >> 4) & 0x3f));
out->append(encode6Bit((x2 << 2) & 0x3f));
out->append('=');
break;
}
default:
{
uint8_t x1 = data[i];
out->append(encode6Bit(x1 >> 2));
out->append(encode6Bit((x1 << 4) & 0x3f));
out->append("==");
break;
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,677 |
poppler | 58e04a08afee39370283c494ee2e4e392fd3b684 | void JBIG2Stream::readSegments() {
Guint segNum, segFlags, segType, page, segLength;
Guint refFlags, nRefSegs;
Guint *refSegs;
Goffset segDataPos;
int c1, c2, c3;
Guint i;
while (readULong(&segNum)) {
if (!readUByte(&segFlags)) {
goto eofError1;
}
segType = segFlags & 0x3f;
if (!readUByte(&refFlags)) {
goto eofError1;
}
nRefSegs = refFlags >> 5;
if (nRefSegs == 7) {
if ((c1 = curStr->getChar()) == EOF ||
(c2 = curStr->getChar()) == EOF ||
(c3 = curStr->getChar()) == EOF) {
goto eofError1;
}
refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3;
nRefSegs = refFlags & 0x1fffffff;
for (i = 0; i < (nRefSegs + 9) >> 3; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError1;
}
}
}
refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint));
if (segNum <= 256) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUByte(&refSegs[i])) {
goto eofError2;
}
}
} else if (segNum <= 65536) {
for (i = 0; i < nRefSegs; ++i) {
if (!readUWord(&refSegs[i])) {
goto eofError2;
}
}
} else {
for (i = 0; i < nRefSegs; ++i) {
if (!readULong(&refSegs[i])) {
goto eofError2;
}
}
}
if (segFlags & 0x40) {
if (!readULong(&page)) {
goto eofError2;
}
} else {
if (!readUByte(&page)) {
goto eofError2;
}
}
if (!readULong(&segLength)) {
goto eofError2;
}
segDataPos = curStr->getPos();
if (!pageBitmap && ((segType >= 4 && segType <= 7) ||
(segType >= 20 && segType <= 43))) {
error(errSyntaxError, curStr->getPos(), "First JBIG2 segment associated with a page must be a page information segment");
goto syntaxError;
}
switch (segType) {
case 0:
if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) {
goto syntaxError;
}
break;
case 4:
readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs);
break;
case 6:
readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs);
break;
case 7:
readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs);
break;
case 16:
readPatternDictSeg(segNum, segLength);
break;
case 20:
readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 22:
readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 23:
readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 36:
readGenericRegionSeg(segNum, gFalse, gFalse, segLength);
break;
case 38:
readGenericRegionSeg(segNum, gTrue, gFalse, segLength);
break;
case 39:
readGenericRegionSeg(segNum, gTrue, gTrue, segLength);
break;
case 40:
readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength,
refSegs, nRefSegs);
break;
case 42:
readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength,
refSegs, nRefSegs);
break;
case 43:
readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength,
refSegs, nRefSegs);
break;
case 48:
readPageInfoSeg(segLength);
break;
case 50:
readEndOfStripeSeg(segLength);
break;
case 52:
readProfilesSeg(segLength);
break;
case 53:
readCodeTableSeg(segNum, segLength);
break;
case 62:
readExtensionSeg(segLength);
break;
default:
error(errSyntaxError, curStr->getPos(), "Unknown segment type in JBIG2 stream");
for (i = 0; i < segLength; ++i) {
if ((c1 = curStr->getChar()) == EOF) {
goto eofError2;
}
}
break;
}
if (segLength != 0xffffffff) {
Goffset segExtraBytes = segDataPos + segLength - curStr->getPos();
if (segExtraBytes > 0) {
error(errSyntaxError, curStr->getPos(), "{0:d} extraneous byte{1:s} after segment",
segExtraBytes, (segExtraBytes > 1) ? "s" : "");
int trash;
for (Goffset i = segExtraBytes; i > 0; i--) {
readByte(&trash);
}
} else if (segExtraBytes < 0) {
error(errSyntaxError, curStr->getPos(), "Previous segment handler read too many bytes");
}
}
gfree(refSegs);
}
return;
syntaxError:
gfree(refSegs);
return;
eofError2:
gfree(refSegs);
eofError1:
error(errSyntaxError, curStr->getPos(), "Unexpected EOF in JBIG2 stream");
}
| 1 | CVE-2013-7296 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,579 |
imageworsener | a4f247707f08e322f0b41e82c3e06e224240a654 | static unsigned int iw_scale_to_int(double s, unsigned int maxcolor)
{
if(s<=0.0) return 0;
if(s>=1.0) return maxcolor;
return (unsigned int)(0.5+s*maxcolor);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,154 |
ImageMagick | 560e6e512961008938aa1d1b9aab06347b1c8f9b | ModuleExport size_t RegisterPCXImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("DCX");
entry->decoder=(DecodeImageHandler *) ReadPCXImage;
entry->encoder=(EncodeImageHandler *) WritePCXImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsDCX;
entry->description=ConstantString("ZSoft IBM PC multi-page Paintbrush");
entry->module=ConstantString("PCX");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PCX");
entry->decoder=(DecodeImageHandler *) ReadPCXImage;
entry->encoder=(EncodeImageHandler *) WritePCXImage;
entry->magick=(IsImageFormatHandler *) IsPCX;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("ZSoft IBM PC Paintbrush");
entry->module=ConstantString("PCX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,947 |
php-src | f3feddb5b45b5abd93abb1a95044b7e099d51c84 | PHP_BZ2_API php_stream *_php_stream_bz2open(php_stream_wrapper *wrapper,
char *path,
char *mode,
int options,
char **opened_path,
php_stream_context *context STREAMS_DC TSRMLS_DC)
{
php_stream *retstream = NULL, *stream = NULL;
char *path_copy = NULL;
BZFILE *bz_file = NULL;
if (strncasecmp("compress.bzip2://", path, 17) == 0) {
path += 17;
}
if (mode[0] == '\0' || (mode[0] != 'w' && mode[0] != 'r' && mode[1] != '\0')) {
return NULL;
}
#ifdef VIRTUAL_DIR
virtual_filepath_ex(path, &path_copy, NULL TSRMLS_CC);
#else
path_copy = path;
#endif
if (php_check_open_basedir(path_copy TSRMLS_CC)) {
#ifdef VIRTUAL_DIR
free(path_copy);
#endif
return NULL;
}
/* try and open it directly first */
bz_file = BZ2_bzopen(path_copy, mode);
if (opened_path && bz_file) {
*opened_path = estrdup(path_copy);
}
#ifdef VIRTUAL_DIR
free(path_copy);
#endif
path_copy = NULL;
if (bz_file == NULL) {
/* that didn't work, so try and get something from the network/wrapper */
stream = php_stream_open_wrapper(path, mode, options | STREAM_WILL_CAST, opened_path);
if (stream) {
int fd;
if (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **) &fd, REPORT_ERRORS)) {
bz_file = BZ2_bzdopen(fd, mode);
}
}
/* remove the file created by php_stream_open_wrapper(), it is not needed since BZ2 functions
* failed.
*/
if (opened_path && !bz_file && mode[0] == 'w') {
VCWD_UNLINK(*opened_path);
}
}
if (bz_file) {
retstream = _php_stream_bz2open_from_BZFILE(bz_file, mode, stream STREAMS_REL_CC TSRMLS_CC);
if (retstream) {
return retstream;
}
BZ2_bzclose(bz_file);
}
if (stream) {
php_stream_close(stream);
}
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,924 |
Chrome | baef1ffd73db183ca50c854e1779ed7f6e5100a8 | void SetUpCacheWithVariousFiles() {
CreateFile(persistent_directory_.AppendASCII("id_foo.md5foo"));
CreateFile(persistent_directory_.AppendASCII("id_bar.local"));
CreateFile(persistent_directory_.AppendASCII("id_baz.local"));
CreateFile(persistent_directory_.AppendASCII("id_bad.md5bad"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
persistent_directory_.AppendASCII("id_symlink"));
CreateFile(tmp_directory_.AppendASCII("id_qux.md5qux"));
CreateFile(tmp_directory_.AppendASCII("id_quux.local"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
tmp_directory_.AppendASCII("id_symlink_tmp"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
pinned_directory_.AppendASCII("id_foo"));
CreateSymbolicLink(FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull),
pinned_directory_.AppendASCII("id_corge"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_dangling.md5foo"),
pinned_directory_.AppendASCII("id_dangling"));
CreateSymbolicLink(tmp_directory_.AppendASCII("id_qux.md5qux"),
pinned_directory_.AppendASCII("id_outside"));
CreateFile(pinned_directory_.AppendASCII("id_not_symlink"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_bar.local"),
outgoing_directory_.AppendASCII("id_bar"));
CreateSymbolicLink(persistent_directory_.AppendASCII("id_foo.md5foo"),
outgoing_directory_.AppendASCII("id_foo"));
}
| 1 | CVE-2012-2895 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,217 |
linux | 594cc251fdd0d231d342d88b2fdff4bc42fb0690 | i915_gem_execbuffer2_ioctl(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_gem_execbuffer2 *args = data;
struct drm_i915_gem_exec_object2 *exec2_list;
struct drm_syncobj **fences = NULL;
const size_t count = args->buffer_count;
int err;
if (!check_buffer_count(count)) {
DRM_DEBUG("execbuf2 with %zd buffers\n", count);
return -EINVAL;
}
if (!i915_gem_check_execbuffer(args))
return -EINVAL;
/* Allocate an extra slot for use by the command parser */
exec2_list = kvmalloc_array(count + 1, eb_element_size(),
__GFP_NOWARN | GFP_KERNEL);
if (exec2_list == NULL) {
DRM_DEBUG("Failed to allocate exec list for %zd buffers\n",
count);
return -ENOMEM;
}
if (copy_from_user(exec2_list,
u64_to_user_ptr(args->buffers_ptr),
sizeof(*exec2_list) * count)) {
DRM_DEBUG("copy %zd exec entries failed\n", count);
kvfree(exec2_list);
return -EFAULT;
}
if (args->flags & I915_EXEC_FENCE_ARRAY) {
fences = get_fence_array(args, file);
if (IS_ERR(fences)) {
kvfree(exec2_list);
return PTR_ERR(fences);
}
}
err = i915_gem_do_execbuffer(dev, file, args, exec2_list, fences);
/*
* Now that we have begun execution of the batchbuffer, we ignore
* any new error after this point. Also given that we have already
* updated the associated relocations, we try to write out the current
* object locations irrespective of any error.
*/
if (args->flags & __EXEC_HAS_RELOC) {
struct drm_i915_gem_exec_object2 __user *user_exec_list =
u64_to_user_ptr(args->buffers_ptr);
unsigned int i;
/* Copy the new buffer offsets back to the user's exec list. */
user_access_begin();
for (i = 0; i < args->buffer_count; i++) {
if (!(exec2_list[i].offset & UPDATE))
continue;
exec2_list[i].offset =
gen8_canonical_addr(exec2_list[i].offset & PIN_OFFSET_MASK);
unsafe_put_user(exec2_list[i].offset,
&user_exec_list[i].offset,
end_user);
}
end_user:
user_access_end();
}
args->flags &= ~__I915_EXEC_UNKNOWN_FLAGS;
put_fence_array(args, fences);
kvfree(exec2_list);
return err;
} | 1 | CVE-2018-20669 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 9,053 |
Chrome | bc1f34b9be509f1404f0bb1ba1947614d5f0bcd1 | void UtilityServiceFactory::RegisterServices(ServiceMap* services) {
GetContentClient()->utility()->RegisterServices(services);
service_manager::EmbeddedServiceInfo video_capture_info;
video_capture_info.factory = base::Bind(&CreateVideoCaptureService);
services->insert(
std::make_pair(video_capture::mojom::kServiceName, video_capture_info));
#if BUILDFLAG(ENABLE_PEPPER_CDMS)
service_manager::EmbeddedServiceInfo info;
info.factory = base::Bind(&CreateMediaService);
services->insert(std::make_pair(media::mojom::kMediaServiceName, info));
#endif
service_manager::EmbeddedServiceInfo shape_detection_info;
shape_detection_info.factory =
base::Bind(&shape_detection::ShapeDetectionService::Create);
services->insert(std::make_pair(shape_detection::mojom::kServiceName,
shape_detection_info));
service_manager::EmbeddedServiceInfo data_decoder_info;
data_decoder_info.factory = base::Bind(&CreateDataDecoderService);
services->insert(
std::make_pair(data_decoder::mojom::kServiceName, data_decoder_info));
if (base::FeatureList::IsEnabled(features::kNetworkService)) {
GetContentClient()->utility()->RegisterNetworkBinders(
network_registry_.get());
service_manager::EmbeddedServiceInfo network_info;
network_info.factory = base::Bind(
&UtilityServiceFactory::CreateNetworkService, base::Unretained(this));
network_info.task_runner = ChildProcess::current()->io_task_runner();
services->insert(
std::make_pair(content::mojom::kNetworkServiceName, network_info));
}
}
| 1 | CVE-2015-1280 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 77 |
tcpdump | 3b36ec4e713dea9266db11975066c425aa669b6c | vqp_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
const struct vqp_common_header_t *vqp_common_header;
const struct vqp_obj_tlv_t *vqp_obj_tlv;
const u_char *tptr;
uint16_t vqp_obj_len;
uint32_t vqp_obj_type;
int tlen;
uint8_t nitems;
tptr=pptr;
tlen = len;
vqp_common_header = (const struct vqp_common_header_t *)pptr;
ND_TCHECK(*vqp_common_header);
/*
* Sanity checking of the header.
*/
if (VQP_EXTRACT_VERSION(vqp_common_header->version) != VQP_VERSION) {
ND_PRINT((ndo, "VQP version %u packet not supported",
VQP_EXTRACT_VERSION(vqp_common_header->version)));
return;
}
/* in non-verbose mode just lets print the basic Message Type */
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "VQPv%u %s Message, error-code %s (%u), length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
nitems = vqp_common_header->nitems;
ND_PRINT((ndo, "\n\tVQPv%u, %s Message, error-code %s (%u), seq 0x%08x, items %u, length %u",
VQP_EXTRACT_VERSION(vqp_common_header->version),
tok2str(vqp_msg_type_values, "unknown (%u)",vqp_common_header->msg_type),
tok2str(vqp_error_code_values, "unknown (%u)",vqp_common_header->error_code),
vqp_common_header->error_code,
EXTRACT_32BITS(&vqp_common_header->sequence),
nitems,
len));
/* skip VQP Common header */
tptr+=sizeof(const struct vqp_common_header_t);
tlen-=sizeof(const struct vqp_common_header_t);
while (nitems > 0 && tlen > 0) {
vqp_obj_tlv = (const struct vqp_obj_tlv_t *)tptr;
vqp_obj_type = EXTRACT_32BITS(vqp_obj_tlv->obj_type);
vqp_obj_len = EXTRACT_16BITS(vqp_obj_tlv->obj_length);
tptr+=sizeof(struct vqp_obj_tlv_t);
tlen-=sizeof(struct vqp_obj_tlv_t);
ND_PRINT((ndo, "\n\t %s Object (0x%08x), length %u, value: ",
tok2str(vqp_obj_values, "Unknown", vqp_obj_type),
vqp_obj_type, vqp_obj_len));
/* basic sanity check */
if (vqp_obj_type == 0 || vqp_obj_len ==0) {
return;
}
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, vqp_obj_len);
switch(vqp_obj_type) {
case VQP_OBJ_IP_ADDRESS:
ND_PRINT((ndo, "%s (0x%08x)", ipaddr_string(ndo, tptr), EXTRACT_32BITS(tptr)));
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_PORT_NAME:
case VQP_OBJ_VLAN_NAME:
case VQP_OBJ_VTP_DOMAIN:
case VQP_OBJ_ETHERNET_PKT:
safeputs(ndo, tptr, vqp_obj_len);
break;
/* those objects have similar semantics - fall through */
case VQP_OBJ_MAC_ADDRESS:
case VQP_OBJ_MAC_NULL:
ND_PRINT((ndo, "%s", etheraddr_string(ndo, tptr)));
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,tptr, "\n\t ", vqp_obj_len);
break;
}
tptr += vqp_obj_len;
tlen -= vqp_obj_len;
nitems--;
}
return;
trunc:
ND_PRINT((ndo, "\n\t[|VQP]"));
}
| 1 | CVE-2017-13045 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 3,036 |
net | 36d5fe6a000790f56039afe26834265db0a3ad4c | static size_t ovs_flow_cmd_msg_size(const struct sw_flow_actions *acts)
{
return NLMSG_ALIGN(sizeof(struct ovs_header))
+ nla_total_size(key_attr_size()) /* OVS_FLOW_ATTR_KEY */
+ nla_total_size(key_attr_size()) /* OVS_FLOW_ATTR_MASK */
+ nla_total_size(sizeof(struct ovs_flow_stats)) /* OVS_FLOW_ATTR_STATS */
+ nla_total_size(1) /* OVS_FLOW_ATTR_TCP_FLAGS */
+ nla_total_size(8) /* OVS_FLOW_ATTR_USED */
+ nla_total_size(acts->actions_len); /* OVS_FLOW_ATTR_ACTIONS */
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,101 |
php-src | 97eff7eb57fc2320c267a949cffd622c38712484?w=1 | PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 1 | CVE-2016-5093 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 6,739 |
linux | b69040d8e39f20d5215a03502a8e8b4c6ab78395 | void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.auth_capable = new->peer.auth_capable;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,534 |
dbus | 9a6bce9b615abca6068348c1606ba8eaf13d9ae0 | my_object_many_args (MyObject *obj, guint32 x, const char *str, double trouble, double *d_ret, char **str_ret, GError **error)
{
*d_ret = trouble + (x * 2);
*str_ret = g_ascii_strup (str, -1);
return TRUE;
}
| 1 | CVE-2010-1172 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 9,981 |
enlightment | 37a96801663b7b4cd3fbe56cc0eb8b6a17e766a8 | load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
break;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = calloc(w, sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
if (!rows)
{
goto quit2;
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
DATA32 colormap[256];
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
memset (colormap, 0, sizeof(colormap));
if (cmap != NULL)
{
for (i = cmap->ColorCount > 256 ? 256 : cmap->ColorCount; i-- > 0;)
{
r = cmap->Colors[i].Red;
g = cmap->Colors[i].Green;
b = cmap->Colors[i].Blue;
colormap[i] = (0xff << 24) | (r << 16) | (g << 8) | b;
}
/* if bg > cmap->ColorCount, it is transparent black already */
if (transp >= 0 && transp < 256)
colormap[transp] = bg >= 0 && bg < 256 ? colormap[bg] & 0x00ffffff : 0x00000000;
}
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
{
r = cmap->Colors[bg].Red;
g = cmap->Colors[bg].Green;
b = cmap->Colors[bg].Blue;
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
{
for (j = 0; j < w; j++)
{
*ptr++ = colormap[rows[i][j]];
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
}
finish:
if (progress)
progress(im, 100, 0, last_y, w, h);
}
rc = 1; /* Success */
quit:
for (i = 0; i < h; i++)
free(rows[i]);
free(rows);
quit2:
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
DGifCloseFile(gif, NULL);
#else
DGifCloseFile(gif);
#endif
return rc;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,736 |
ovs | 0befd1f3745055c32940f5faf9559be6a14395e6 | oftable_set_name(struct oftable *table, const char *name)
{
if (name && name[0]) {
int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
if (!table->name || strncmp(name, table->name, len)) {
free(table->name);
table->name = xmemdup0(name, len);
}
} else {
free(table->name);
table->name = NULL;
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,526 |
libebml | 24e5cd7c666b1ddd85619d60486db0a5481c1b90 | EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel,
uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel)
{
int PossibleID_Length = 0;
binary PossibleIdNSize[16];
int PossibleSizeLength;
uint64 SizeUnknown;
int ReadIndex = 0; // trick for the algo, start index at 0
uint32 ReadSize = 0;
uint64 SizeFound;
int SizeIdx;
bool bFound;
int UpperLevel_original = UpperLevel;
do {
// read a potential ID
do {
assert(ReadIndex < 16);
// build the ID with the current Read Buffer
bFound = false;
binary IdBitMask = 1 << 7;
for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) {
if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) {
// ID found
PossibleID_Length = SizeIdx + 1;
IdBitMask >>= SizeIdx;
bFound = true;
break;
}
}
if (bFound) {
break;
}
if (ReadIndex >= 4) {
// ID not found
// shift left the read octets
memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex);
}
if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) {
return NULL; // no more data ?
}
ReadSize++;
} while (!bFound && MaxDataSize > ReadSize);
SizeIdx = ReadIndex;
ReadIndex -= PossibleID_Length;
// read the data size
uint32 _SizeLength;
PossibleSizeLength = ReadIndex;
while (1) {
_SizeLength = PossibleSizeLength;
SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown);
if (_SizeLength != 0) {
bFound = true;
break;
}
if (PossibleSizeLength >= 8) {
bFound = false;
break;
}
if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) {
return NULL; // no more data ?
}
ReadSize++;
PossibleSizeLength++;
}
if (bFound) {
// find the element in the context and use the correct creator
EbmlId PossibleID(PossibleIdNSize, PossibleID_Length);
EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel);
///< \todo continue is misplaced
if (Result != NULL) {
if (AllowDummyElt || !Result->IsDummy()) {
Result->SetSizeLength(_SizeLength);
Result->Size = SizeFound;
// UpperLevel values
// -1 : global element
// 0 : child
// 1 : same level
// + : further parent
if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) {
if (SizeFound == SizeUnknown) {
Result->SetSizeInfinite();
}
Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID);
Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID);
// place the file at the beggining of the data
DataStream.setFilePointer(Result->SizePosition + _SizeLength);
return Result;
}
}
delete Result;
}
}
// recover all the data in the buffer minus one byte
ReadIndex = SizeIdx - 1;
memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex);
UpperLevel = UpperLevel_original;
} while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length );
return NULL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,403 |
openjpeg | ef01f18dfc6780b776d0674ed3e7415c6ef54d24 | 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((size_t)(l_tcp->numlayers + 1U) * 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;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,492 |
linux | b4cbb197c7e7a68dbad0d491242e3ca67420c13e | int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
unsigned long pfn, unsigned long size, pgprot_t prot)
{
pgd_t *pgd;
unsigned long next;
unsigned long end = addr + PAGE_ALIGN(size);
struct mm_struct *mm = vma->vm_mm;
int err;
/*
* Physically remapped pages are special. Tell the
* rest of the world about it:
* VM_IO tells people not to look at these pages
* (accesses can have side effects).
* VM_PFNMAP tells the core MM that the base pages are just
* raw PFN mappings, and do not have a "struct page" associated
* with them.
* VM_DONTEXPAND
* Disable vma merging and expanding with mremap().
* VM_DONTDUMP
* Omit vma from core dump, even when VM_IO turned off.
*
* There's a horrible special case to handle copy-on-write
* behaviour that some programs depend on. We mark the "original"
* un-COW'ed pages by matching them up with "vma->vm_pgoff".
* See vm_normal_page() for details.
*/
if (is_cow_mapping(vma->vm_flags)) {
if (addr != vma->vm_start || end != vma->vm_end)
return -EINVAL;
vma->vm_pgoff = pfn;
}
err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
if (err)
return -EINVAL;
vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
BUG_ON(addr >= end);
pfn -= addr >> PAGE_SHIFT;
pgd = pgd_offset(mm, addr);
flush_cache_range(vma, addr, end);
do {
next = pgd_addr_end(addr, end);
err = remap_pud_range(mm, pgd, addr, next,
pfn + (addr >> PAGE_SHIFT), prot);
if (err)
break;
} while (pgd++, addr = next, addr != end);
if (err)
untrack_pfn(vma, pfn, PAGE_ALIGN(size));
return err;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,598 |
libxkbcommon | 4e2ee9c3f6050d773f8bbe05bc0edb17f1ff8371 | ExprResolveLevel(struct xkb_context *ctx, const ExprDef *expr,
xkb_level_index_t *level_rtrn)
{
bool ok;
int result;
ok = ExprResolveIntegerLookup(ctx, expr, &result, SimpleLookup,
levelNames);
if (!ok)
return false;
if (result < 1) {
log_err(ctx, "Shift level %d is out of range\n", result);
return false;
}
/* Level is zero-indexed from now on. */
*level_rtrn = (unsigned int) (result - 1);
return true;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,897 |
nettle | c71d2c9d20eeebb985e3872e4550137209e3ce4d | ecc_256_modq (const struct ecc_modulo *q, mp_limb_t *rp)
{
mp_limb_t u2, u1, u0;
mp_size_t n;
n = 2*q->size;
u2 = rp[--n];
u1 = rp[n-1];
/* This is not particularly fast, but should work well with assembly implementation. */
for (; n >= q->size; n--)
{
mp_limb_t q2, q1, q0, t, c1, c0;
u0 = rp[n-2];
/* <q2, q1, q0> = v * u2 + <u2,u1>, same method as above.
+---+---+
| u2| u1|
+---+---+
|-u2|
+-+-+-+
| u2|
+---+-+-+-+-+
| q2| q1| q0|
+---+---+---+
*/
q1 = u2 - (u2 > u1);
q0 = u1 - u2;
t = u2 << 32;
q0 += t;
t = (u2 >> 32) + (q0 < t) + 1;
q1 += t;
q2 = q1 < t;
/* Compute candidate remainder, <u1, u0> - <q2, q1> * (2^128 - 2^96 + 2^64 - 1)
<u1, u0> + 2^64 q2 + (2^96 - 2^64 + 1) q1 (mod 2^128)
+---+---+
| u1| u0|
+---+---+
| q2| q1|
+---+---+
|-q1|
+-+-+-+
| q1|
--+-+-+-+---+
| u2| u1|
+---+---+
*/
u2 = u1 + q2 - q1;
u1 = u0 + q1;
u2 += (u1 < q1);
u2 += (q1 << 32);
t = -(mp_limb_t) (u2 >= q0);
q1 += t;
q2 += t + (q1 < t);
u1 += t;
u2 += (t << 32) + (u1 < t);
assert (q2 < 2);
c0 = cnd_sub_n (q2, rp + n - 3, q->m, 1);
c0 += (-q2) & q->m[1];
t = mpn_submul_1 (rp + n - 4, q->m, 2, q1);
c0 += t;
c1 = c0 < t;
/* Construct underflow condition. */
c1 += (u1 < c0);
t = - (mp_limb_t) (u2 < c1);
u1 -= c0;
u2 -= c1;
/* Conditional add of p */
u1 += t;
u2 += (t<<32) + (u1 < t);
t = cnd_add_n (t, rp + n - 4, q->m, 2);
u1 += t;
u2 += (u1 < t);
}
rp[2] = u1;
rp[3] = u2;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,741 |
linux | 0b79459b482e85cb7426aa7da683a9f2c97aeae1 | static int kvm_guest_time_update(struct kvm_vcpu *v)
{
unsigned long flags, this_tsc_khz;
struct kvm_vcpu_arch *vcpu = &v->arch;
struct kvm_arch *ka = &v->kvm->arch;
void *shared_kaddr;
s64 kernel_ns, max_kernel_ns;
u64 tsc_timestamp, host_tsc;
struct pvclock_vcpu_time_info *guest_hv_clock;
u8 pvclock_flags;
bool use_master_clock;
kernel_ns = 0;
host_tsc = 0;
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
spin_lock(&ka->pvclock_gtod_sync_lock);
use_master_clock = ka->use_master_clock;
if (use_master_clock) {
host_tsc = ka->master_cycle_now;
kernel_ns = ka->master_kernel_ns;
}
spin_unlock(&ka->pvclock_gtod_sync_lock);
/* Keep irq disabled to prevent changes to the clock */
local_irq_save(flags);
this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
if (unlikely(this_tsc_khz == 0)) {
local_irq_restore(flags);
kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
return 1;
}
if (!use_master_clock) {
host_tsc = native_read_tsc();
kernel_ns = get_kernel_ns();
}
tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
/*
* We may have to catch up the TSC to match elapsed wall clock
* time for two reasons, even if kvmclock is used.
* 1) CPU could have been running below the maximum TSC rate
* 2) Broken TSC compensation resets the base at each VCPU
* entry to avoid unknown leaps of TSC even when running
* again on the same CPU. This may cause apparent elapsed
* time to disappear, and the guest to stand still or run
* very slowly.
*/
if (vcpu->tsc_catchup) {
u64 tsc = compute_guest_tsc(v, kernel_ns);
if (tsc > tsc_timestamp) {
adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
tsc_timestamp = tsc;
}
}
local_irq_restore(flags);
if (!vcpu->time_page)
return 0;
/*
* Time as measured by the TSC may go backwards when resetting the base
* tsc_timestamp. The reason for this is that the TSC resolution is
* higher than the resolution of the other clock scales. Thus, many
* possible measurments of the TSC correspond to one measurement of any
* other clock, and so a spread of values is possible. This is not a
* problem for the computation of the nanosecond clock; with TSC rates
* around 1GHZ, there can only be a few cycles which correspond to one
* nanosecond value, and any path through this code will inevitably
* take longer than that. However, with the kernel_ns value itself,
* the precision may be much lower, down to HZ granularity. If the
* first sampling of TSC against kernel_ns ends in the low part of the
* range, and the second in the high end of the range, we can get:
*
* (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
*
* As the sampling errors potentially range in the thousands of cycles,
* it is possible such a time value has already been observed by the
* guest. To protect against this, we must compute the system time as
* observed by the guest and ensure the new system time is greater.
*/
max_kernel_ns = 0;
if (vcpu->hv_clock.tsc_timestamp) {
max_kernel_ns = vcpu->last_guest_tsc -
vcpu->hv_clock.tsc_timestamp;
max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
vcpu->hv_clock.tsc_to_system_mul,
vcpu->hv_clock.tsc_shift);
max_kernel_ns += vcpu->last_kernel_ns;
}
if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
&vcpu->hv_clock.tsc_shift,
&vcpu->hv_clock.tsc_to_system_mul);
vcpu->hw_tsc_khz = this_tsc_khz;
}
/* with a master <monotonic time, tsc value> tuple,
* pvclock clock reads always increase at the (scaled) rate
* of guest TSC - no need to deal with sampling errors.
*/
if (!use_master_clock) {
if (max_kernel_ns > kernel_ns)
kernel_ns = max_kernel_ns;
}
/* With all the info we got, fill in the values */
vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
vcpu->last_kernel_ns = kernel_ns;
vcpu->last_guest_tsc = tsc_timestamp;
/*
* The interface expects us to write an even number signaling that the
* update is finished. Since the guest won't see the intermediate
* state, we just increase by 2 at the end.
*/
vcpu->hv_clock.version += 2;
shared_kaddr = kmap_atomic(vcpu->time_page);
guest_hv_clock = shared_kaddr + vcpu->time_offset;
/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
pvclock_flags = (guest_hv_clock->flags & PVCLOCK_GUEST_STOPPED);
if (vcpu->pvclock_set_guest_stopped_request) {
pvclock_flags |= PVCLOCK_GUEST_STOPPED;
vcpu->pvclock_set_guest_stopped_request = false;
}
/* If the host uses TSC clocksource, then it is stable */
if (use_master_clock)
pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
vcpu->hv_clock.flags = pvclock_flags;
memcpy(shared_kaddr + vcpu->time_offset, &vcpu->hv_clock,
sizeof(vcpu->hv_clock));
kunmap_atomic(shared_kaddr);
mark_page_dirty(v->kvm, vcpu->time >> PAGE_SHIFT);
return 0;
}
| 1 | CVE-2013-1797 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 8,489 |
Android | 295c883fe3105b19bcd0f9e07d54c6b589fc5bff | void SoftVideoDecoderOMXComponent::onPortEnableCompleted(OMX_U32 portIndex, bool enabled) {
if (portIndex != kOutputPortIndex) {
return;
}
switch (mOutputPortSettingsChange) {
case NONE:
break;
case AWAITING_DISABLED:
{
CHECK(!enabled);
mOutputPortSettingsChange = AWAITING_ENABLED;
break;
}
default:
{
CHECK_EQ((int)mOutputPortSettingsChange, (int)AWAITING_ENABLED);
CHECK(enabled);
mOutputPortSettingsChange = NONE;
break;
}
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,283 |
gegl | 4757cdf73d3675478d645a3ec8250ba02168a230 | ppm_load_read_header(FILE *fp,
pnm_struct *img)
{
/* PPM Headers Variable Declaration */
gchar *ptr;
//gchar *retval;
gchar header[MAX_CHARS_IN_ROW];
gint maxval;
/* Check the PPM file Type P2 or P5 */
fgets (header,MAX_CHARS_IN_ROW,fp);
if (header[0] != ASCII_P ||
(header[1] != PIXMAP_ASCII &&
header[1] != PIXMAP_RAW))
{
g_warning ("Image is not a portable pixmap");
return FALSE;
}
img->type = header[1];
/* Check the Comments */
fgets (header,MAX_CHARS_IN_ROW,fp);
while(header[0] == '#')
{
fgets (header,MAX_CHARS_IN_ROW,fp);
}
/* Get Width and Height */
img->width = strtol (header,&ptr,0);
img->height = atoi (ptr);
fgets (header,MAX_CHARS_IN_ROW,fp);
maxval = strtol (header,&ptr,0);
if ((maxval != 255) && (maxval != 65535))
{
g_warning ("Image is not an 8-bit or 16-bit portable pixmap");
return FALSE;
}
switch (maxval)
{
case 255:
img->bpc = sizeof (guchar);
break;
case 65535:
img->bpc = sizeof (gushort);
break;
default:
g_warning ("%s: Programmer stupidity error", G_STRLOC);
}
/* Later on, img->numsamples is multiplied with img->bpc to allocate
* memory. Ensure it doesn't overflow. */
if (!img->width || !img->height ||
G_MAXSIZE / img->width / img->height / CHANNEL_COUNT < img->bpc)
{
g_warning ("Illegal width/height: %ld/%ld", img->width, img->height);
return FALSE;
}
img->numsamples = img->width * img->height * CHANNEL_COUNT;
return TRUE;
} | 1 | CVE-2012-4433 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 5,993 |
linux | 6377f787aeb945cae7abbb6474798de129e1f3ac | static void *atalk_seq_route_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct atalk_route *r;
++*pos;
if (v == SEQ_START_TOKEN) {
r = NULL;
if (atalk_routes)
r = atalk_routes;
goto out;
}
r = v;
r = r->next;
out:
return r;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,919 |
tcpdump | 0f95d441e4b5d7512cc5c326c8668a120e048eda | ppp_print(netdissect_options *ndo,
register const u_char *p, u_int length)
{
u_int proto,ppp_header;
u_int olen = length; /* _o_riginal length */
u_int hdr_len = 0;
/*
* Here, we assume that p points to the Address and Control
* field (if they present).
*/
if (length < 2)
goto trunc;
ND_TCHECK2(*p, 2);
ppp_header = EXTRACT_16BITS(p);
switch(ppp_header) {
case (PPP_WITHDIRECTION_IN << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "In "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_WITHDIRECTION_OUT << 8 | PPP_CONTROL):
if (ndo->ndo_eflag) ND_PRINT((ndo, "Out "));
p += 2;
length -= 2;
hdr_len += 2;
break;
case (PPP_ADDRESS << 8 | PPP_CONTROL):
p += 2; /* ACFC not used */
length -= 2;
hdr_len += 2;
break;
default:
break;
}
if (length < 2)
goto trunc;
ND_TCHECK(*p);
if (*p % 2) {
proto = *p; /* PFC is used */
p++;
length--;
hdr_len++;
} else {
ND_TCHECK2(*p, 2);
proto = EXTRACT_16BITS(p);
p += 2;
length -= 2;
hdr_len += 2;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s (0x%04x), length %u: ",
tok2str(ppptype2str, "unknown", proto),
proto,
olen));
handle_ppp(ndo, proto, p, length);
return (hdr_len);
trunc:
ND_PRINT((ndo, "[|ppp]"));
return (0);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,522 |
php-src | 3462efa386f26d343062094514af604c29e3edce | static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement TSRMLS_DC)
{
int de, i=0, section_index = SECTION_MAKERNOTE;
int NumDirEntries, old_motorola_intel, offset_diff;
const maker_note_type *maker_note;
char *dir_start;
int data_len;
for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) {
if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) {
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make));
#endif
/* unknown manufacturer, not an error, use it as a string */
return TRUE;
}
maker_note = maker_note_array+i;
/*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/
if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make)))
continue;
if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model)))
continue;
if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len))
continue;
break;
}
if (maker_note->offset >= value_len) {
/* Do not go past the value end */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset);
return FALSE;
}
dir_start = value_ptr + maker_note->offset;
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement));
#endif
ImageInfo->sections_found |= FOUND_MAKERNOTE;
old_motorola_intel = ImageInfo->motorola_intel;
switch (maker_note->byte_order) {
case MN_ORDER_INTEL:
ImageInfo->motorola_intel = 0;
break;
case MN_ORDER_MOTOROLA:
ImageInfo->motorola_intel = 1;
break;
default:
case MN_ORDER_NORMAL:
break;
}
NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel);
switch (maker_note->offset_mode) {
case MN_OFFSET_MAKER:
offset_base = value_ptr;
data_len = value_len;
break;
case MN_OFFSET_GUESS:
if (maker_note->offset + 10 + 4 >= value_len) {
/* Can not read dir_start+10 since it's beyond value end */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len);
return FALSE;
}
offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel);
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff);
#endif
if (offset_diff < 0 || offset_diff >= value_len ) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len);
return FALSE;
}
offset_base = value_ptr + offset_diff;
data_len = value_len - offset_diff;
break;
default:
case MN_OFFSET_NORMAL:
break;
}
if ((2+NumDirEntries*12) > value_len) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len);
return FALSE;
}
for (de=0;de<NumDirEntries;de++) {
if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de,
offset_base, data_len, displacement, section_index, 0, maker_note->tag_table TSRMLS_CC)) {
return FALSE;
}
}
ImageInfo->motorola_intel = old_motorola_intel;
/* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE));
#endif
return TRUE;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,673 |
ghostscript | 97096297d409ec6f206298444ba00719607e8ba8 | gstate_to_update(fz_context *ctx, pdf_filter_processor *p)
{
filter_gstate *gstate = p->gstate;
/* If we're not the top, that's fine */
if (gstate->next != NULL)
return gstate;
/* We are the top. Push a group, so we're not */
filter_push(ctx, p);
gstate = p->gstate;
gstate->pushed = 1;
if (p->chain->op_q)
p->chain->op_q(ctx, p->chain);
return p->gstate;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,103 |
Chrome | 116d0963cadfbf55ef2ec3d13781987c4d80517a | void GetPreviewDataForIndex(int index,
scoped_refptr<base::RefCountedBytes>* data) {
if (index != printing::COMPLETE_PREVIEW_DOCUMENT_INDEX &&
index < printing::FIRST_PAGE_INDEX) {
return;
}
PreviewPageDataMap::iterator it = page_data_map_.find(index);
if (it != page_data_map_.end())
*data = it->second.get();
}
| 1 | CVE-2012-2891 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 1,026 |
linux | 8e3fbf870481eb53b2d3a322d1fc395ad8b367ed | static netdev_tx_t yam_send_packet(struct sk_buff *skb,
struct net_device *dev)
{
struct yam_port *yp = netdev_priv(dev);
skb_queue_tail(&yp->send_queue, skb);
dev->trans_start = jiffies;
return NETDEV_TX_OK;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,349 |
tensorflow | 2d88f470dea2671b430884260f3626b1fe99830a | inline bool ResolveAxis(const int num_dims, const int* axis,
const int64_t num_axis, int* out_axis,
int* out_num_axis) {
*out_num_axis = 0; // Just in case.
// Short-circuit axis resolution for scalars; the axis will go unused.
if (num_dims == 0) {
return true;
}
// o(n^2) is fine since out_num_axis should be really small, mostly <= 4
for (int64_t idx = 0; idx < num_axis; ++idx) {
// Handle negative index. A positive index 'p_idx' can be represented as a
// negative index 'n_idx' as: n_idx = p_idx-num_dims
// eg: For num_dims=3, [0, 1, 2] is the same as [-3, -2, -1] */
int current = axis[idx] < 0 ? (axis[idx] + num_dims) : axis[idx];
TFLITE_DCHECK(current >= 0 && current < num_dims);
bool is_dup = false;
for (int j = 0; j < *out_num_axis; ++j) {
if (out_axis[j] == current) {
is_dup = true;
break;
}
}
if (!is_dup) {
out_axis[*out_num_axis] = current;
*out_num_axis += 1;
}
}
return true;
} | 1 | CVE-2020-15207 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,364 |
Chrome | fd2335678e96c34d14f4b20f0d9613dfbd1ccdb4 | bool ShouldQuicHeadersIncludeH2StreamDependencies(
const VariationParameters& quic_trial_params) {
return base::LowerCaseEqualsASCII(
GetVariationParam(quic_trial_params,
"headers_include_h2_stream_dependency"),
"true");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,534 |
Chrome | 0d7717faeaef5b72434632c95c78bee4883e2573 | void PopulateForm(const std::string& field_id) {
std::string js("document.getElementById('" + field_id + "').focus();");
ASSERT_TRUE(content::ExecuteScript(render_view_host(), js));
SendKeyToPageAndWait(ui::VKEY_DOWN);
SendKeyToPopupAndWait(ui::VKEY_DOWN);
SendKeyToPopupAndWait(ui::VKEY_RETURN);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,741 |
open5gs | c0f695525088486c509f37a02ff1fda211b141bb | void ogs_nas_5gs_imsi_to_bcd(
ogs_nas_5gs_mobile_identity_t *mobile_identity, char *imsi_bcd)
{
ogs_nas_5gs_mobile_identity_suci_t *mobile_identity_suci = NULL;
ogs_plmn_id_t plmn_id;
char tmp[OGS_MAX_IMSI_BCD_LEN+1];
char *p, *last;
ogs_assert(mobile_identity);
ogs_assert(imsi_bcd);
p = imsi_bcd;
last = imsi_bcd + OGS_MAX_IMSI_BCD_LEN + 1;
mobile_identity_suci =
(ogs_nas_5gs_mobile_identity_suci_t *)mobile_identity->buffer;
ogs_assert(mobile_identity_suci);
ogs_nas_to_plmn_id(&plmn_id, &mobile_identity_suci->nas_plmn_id);
if (ogs_plmn_id_mnc_len(&plmn_id) == 2)
p = ogs_slprintf(p, last, "%03d%02d",
ogs_plmn_id_mcc(&plmn_id), ogs_plmn_id_mnc(&plmn_id));
else
p = ogs_slprintf(p, last, "%03d%03d",
ogs_plmn_id_mcc(&plmn_id), ogs_plmn_id_mnc(&plmn_id));
ogs_assert(mobile_identity->length > 8);
ogs_buffer_to_bcd(mobile_identity_suci->scheme_output,
mobile_identity->length - 8, tmp);
p = ogs_slprintf(p, last, "%s", tmp);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,228 |
ImageMagick | 9cf2f738f714eba6d47be1127ed255acd2b51750 | static size_t EncodeImage(Image *image,const size_t bytes_per_line,
const unsigned char *pixels,unsigned char *compressed_pixels)
{
ssize_t
y;
register const unsigned char
*p;
register ssize_t
i,
x;
register unsigned char
*q;
/*
Runlength encode pixels.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(pixels != (const unsigned char *) NULL);
assert(compressed_pixels != (unsigned char *) NULL);
p=pixels;
q=compressed_pixels;
i=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
for (x=0; x < (ssize_t) bytes_per_line; x+=i)
{
/*
Determine runlength.
*/
for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++)
if ((*(p+i) != *p) || (i == 255))
break;
*q++=(unsigned char) i;
*q++=(*p);
p+=i;
}
/*
End of line.
*/
*q++=0x00;
*q++=0x00;
if (SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows) == MagickFalse)
break;
}
/*
End of bitmap.
*/
*q++=0;
*q++=0x01;
return((size_t) (q-compressed_pixels));
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,923 |
oniguruma | d3e402928b6eb3327f8f7d59a9edfa622fec557b | onig_get_capture_range_in_callout(OnigCalloutArgs* a, int mem_num, int* begin, int* end)
{
OnigRegex reg;
const UChar* str;
StackType* stk_base;
int i;
i = mem_num;
reg = a->regex;
str = a->string;
stk_base = a->stk_base;
if (i > 0) {
if (a->mem_end_stk[i] != INVALID_STACK_INDEX) {
if (MEM_STATUS_AT(reg->bt_mem_start, i))
*begin = (int )(STACK_AT(a->mem_start_stk[i])->u.mem.pstr - str);
else
*begin = (int )((UChar* )((void* )a->mem_start_stk[i]) - str);
*end = (int )((MEM_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(a->mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )a->mem_end_stk[i])) - str);
}
else {
*begin = *end = ONIG_REGION_NOTPOS;
}
}
else
return ONIGERR_INVALID_ARGUMENT;
return ONIG_NORMAL;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,460 |
linux | 1e38da300e1e395a15048b0af1e5305bd91402f6 | SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)
{
int ufd;
struct timerfd_ctx *ctx;
/* Check the TFD_* constants for consistency. */
BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK);
if ((flags & ~TFD_CREATE_FLAGS) ||
(clockid != CLOCK_MONOTONIC &&
clockid != CLOCK_REALTIME &&
clockid != CLOCK_REALTIME_ALARM &&
clockid != CLOCK_BOOTTIME &&
clockid != CLOCK_BOOTTIME_ALARM))
return -EINVAL;
if (!capable(CAP_WAKE_ALARM) &&
(clockid == CLOCK_REALTIME_ALARM ||
clockid == CLOCK_BOOTTIME_ALARM))
return -EPERM;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
init_waitqueue_head(&ctx->wqh);
ctx->clockid = clockid;
if (isalarm(ctx))
alarm_init(&ctx->t.alarm,
ctx->clockid == CLOCK_REALTIME_ALARM ?
ALARM_REALTIME : ALARM_BOOTTIME,
timerfd_alarmproc);
else
hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS);
ctx->moffs = ktime_mono_to_real(0);
ufd = anon_inode_getfd("[timerfd]", &timerfd_fops, ctx,
O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS));
if (ufd < 0)
kfree(ctx);
return ufd;
}
| 1 | CVE-2017-10661 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 8,321 |
Chrome | 4d17163f4b66be517dc49019a029e5ddbd45078c | void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
{
if (!defaultStyle) {
if (!root || elementCanUseSimpleDefaultStyle(root))
loadSimpleDefaultStyle();
else
loadFullDefaultStyle();
}
}
| 1 | CVE-2013-0828 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 1,401 |
linux | a2f18db0c68fec96631c10cad9384c196e9008ac | static void nf_tables_abort_release(struct nft_trans *trans)
{
switch (trans->msg_type) {
case NFT_MSG_NEWTABLE:
nf_tables_table_destroy(&trans->ctx);
break;
case NFT_MSG_NEWCHAIN:
nf_tables_chain_destroy(trans->ctx.chain);
break;
case NFT_MSG_NEWRULE:
nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
break;
case NFT_MSG_NEWSET:
nft_set_destroy(nft_trans_set(trans));
break;
}
kfree(trans);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,330 |
linux | 6f442be2fb22be02cafa606f1769fa1e6f894441 | void __init trap_init(void)
{
int i;
#ifdef CONFIG_EISA
void __iomem *p = early_ioremap(0x0FFFD9, 4);
if (readl(p) == 'E' + ('I'<<8) + ('S'<<16) + ('A'<<24))
EISA_bus = 1;
early_iounmap(p, 4);
#endif
set_intr_gate(X86_TRAP_DE, divide_error);
set_intr_gate_ist(X86_TRAP_NMI, &nmi, NMI_STACK);
/* int4 can be called from all */
set_system_intr_gate(X86_TRAP_OF, &overflow);
set_intr_gate(X86_TRAP_BR, bounds);
set_intr_gate(X86_TRAP_UD, invalid_op);
set_intr_gate(X86_TRAP_NM, device_not_available);
#ifdef CONFIG_X86_32
set_task_gate(X86_TRAP_DF, GDT_ENTRY_DOUBLEFAULT_TSS);
#else
set_intr_gate_ist(X86_TRAP_DF, &double_fault, DOUBLEFAULT_STACK);
#endif
set_intr_gate(X86_TRAP_OLD_MF, coprocessor_segment_overrun);
set_intr_gate(X86_TRAP_TS, invalid_TSS);
set_intr_gate(X86_TRAP_NP, segment_not_present);
set_intr_gate_ist(X86_TRAP_SS, &stack_segment, STACKFAULT_STACK);
set_intr_gate(X86_TRAP_GP, general_protection);
set_intr_gate(X86_TRAP_SPURIOUS, spurious_interrupt_bug);
set_intr_gate(X86_TRAP_MF, coprocessor_error);
set_intr_gate(X86_TRAP_AC, alignment_check);
#ifdef CONFIG_X86_MCE
set_intr_gate_ist(X86_TRAP_MC, &machine_check, MCE_STACK);
#endif
set_intr_gate(X86_TRAP_XF, simd_coprocessor_error);
/* Reserve all the builtin and the syscall vector: */
for (i = 0; i < FIRST_EXTERNAL_VECTOR; i++)
set_bit(i, used_vectors);
#ifdef CONFIG_IA32_EMULATION
set_system_intr_gate(IA32_SYSCALL_VECTOR, ia32_syscall);
set_bit(IA32_SYSCALL_VECTOR, used_vectors);
#endif
#ifdef CONFIG_X86_32
set_system_trap_gate(SYSCALL_VECTOR, &system_call);
set_bit(SYSCALL_VECTOR, used_vectors);
#endif
/*
* Set the IDT descriptor to a fixed read-only location, so that the
* "sidt" instruction will not leak the location of the kernel, and
* to defend the IDT against arbitrary memory write vulnerabilities.
* It will be reloaded in cpu_init() */
__set_fixmap(FIX_RO_IDT, __pa_symbol(idt_table), PAGE_KERNEL_RO);
idt_descr.address = fix_to_virt(FIX_RO_IDT);
/*
* Should be a barrier for any external CPU state:
*/
cpu_init();
x86_init.irqs.trap_init();
#ifdef CONFIG_X86_64
memcpy(&debug_idt_table, &idt_table, IDT_ENTRIES * 16);
set_nmi_gate(X86_TRAP_DB, &debug);
set_nmi_gate(X86_TRAP_BP, &int3);
#endif
}
| 1 | CVE-2014-9322 | CWE-264 | Permissions, Privileges, and Access Controls | Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control. | Not Found in CWE Page | 180 |
linux | 350b8bdd689cd2ab2c67c8a86a0be86cfa0751a7 | int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot)
{
gfn_t gfn, end_gfn;
pfn_t pfn;
int r = 0;
struct iommu_domain *domain = kvm->arch.iommu_domain;
int flags;
/* check if iommu exists and in use */
if (!domain)
return 0;
gfn = slot->base_gfn;
end_gfn = gfn + slot->npages;
flags = IOMMU_READ;
if (!(slot->flags & KVM_MEM_READONLY))
flags |= IOMMU_WRITE;
if (!kvm->arch.iommu_noncoherent)
flags |= IOMMU_CACHE;
while (gfn < end_gfn) {
unsigned long page_size;
/* Check if already mapped */
if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) {
gfn += 1;
continue;
}
/* Get the page size we could use to map */
page_size = kvm_host_page_size(kvm, gfn);
/* Make sure the page_size does not exceed the memslot */
while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn)
page_size >>= 1;
/* Make sure gfn is aligned to the page size we want to map */
while ((gfn << PAGE_SHIFT) & (page_size - 1))
page_size >>= 1;
/* Make sure hva is aligned to the page size we want to map */
while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1))
page_size >>= 1;
/*
* Pin all pages we are about to map in memory. This is
* important because we unmap and unpin in 4kb steps later.
*/
pfn = kvm_pin_pages(slot, gfn, page_size);
if (is_error_noslot_pfn(pfn)) {
gfn += 1;
continue;
}
/* Map into IO address space */
r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn),
page_size, flags);
if (r) {
printk(KERN_ERR "kvm_iommu_map_address:"
"iommu failed to map pfn=%llx\n", pfn);
goto unmap_pages;
}
gfn += page_size >> PAGE_SHIFT;
}
return 0;
unmap_pages:
kvm_iommu_put_pages(kvm, slot->base_gfn, gfn);
return r;
}
| 1 | CVE-2014-3601 | CWE-189 | Numeric Errors | Weaknesses in this category are related to improper calculation or conversion of numbers. | Not Found in CWE Page | 9,701 |
cairo | 03a820b173ed1fdef6ff14b4468f5dbc02ff59be | _cairo_image_compositor_reset_static_data (void)
{
CAIRO_MUTEX_LOCK (_cairo_glyph_cache_mutex);
if (global_glyph_cache)
pixman_glyph_cache_destroy (global_glyph_cache);
global_glyph_cache = NULL;
CAIRO_MUTEX_UNLOCK (_cairo_glyph_cache_mutex);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 12,490 |
linux | f961e3f2acae94b727380c0b74e2d3954d0edf79 | nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp,
struct svc_export *exp,
struct dentry *dentry, u32 *bmval,
struct svc_rqst *rqstp, int ignore_crossmnt)
{
u32 bmval0 = bmval[0];
u32 bmval1 = bmval[1];
u32 bmval2 = bmval[2];
struct kstat stat;
struct svc_fh *tempfh = NULL;
struct kstatfs statfs;
__be32 *p;
int starting_len = xdr->buf->len;
int attrlen_offset;
__be32 attrlen;
u32 dummy;
u64 dummy64;
u32 rdattr_err = 0;
__be32 status;
int err;
struct nfs4_acl *acl = NULL;
void *context = NULL;
int contextlen;
bool contextsupport = false;
struct nfsd4_compoundres *resp = rqstp->rq_resp;
u32 minorversion = resp->cstate.minorversion;
struct path path = {
.mnt = exp->ex_path.mnt,
.dentry = dentry,
};
struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1);
BUG_ON(!nfsd_attrs_supported(minorversion, bmval));
if (exp->ex_fslocs.migrated) {
status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err);
if (status)
goto out;
}
err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT);
if (err)
goto out_nfserr;
if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE |
FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) ||
(bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE |
FATTR4_WORD1_SPACE_TOTAL))) {
err = vfs_statfs(&path, &statfs);
if (err)
goto out_nfserr;
}
if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) {
tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL);
status = nfserr_jukebox;
if (!tempfh)
goto out;
fh_init(tempfh, NFS4_FHSIZE);
status = fh_compose(tempfh, exp, dentry, NULL);
if (status)
goto out;
fhp = tempfh;
}
if (bmval0 & FATTR4_WORD0_ACL) {
err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl);
if (err == -EOPNOTSUPP)
bmval0 &= ~FATTR4_WORD0_ACL;
else if (err == -EINVAL) {
status = nfserr_attrnotsupp;
goto out;
} else if (err != 0)
goto out_nfserr;
}
#ifdef CONFIG_NFSD_V4_SECURITY_LABEL
if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) ||
bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) {
if (exp->ex_flags & NFSEXP_SECURITY_LABEL)
err = security_inode_getsecctx(d_inode(dentry),
&context, &contextlen);
else
err = -EOPNOTSUPP;
contextsupport = (err == 0);
if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) {
if (err == -EOPNOTSUPP)
bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL;
else if (err)
goto out_nfserr;
}
}
#endif /* CONFIG_NFSD_V4_SECURITY_LABEL */
status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2);
if (status)
goto out;
attrlen_offset = xdr->buf->len;
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
p++; /* to be backfilled later */
if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) {
u32 supp[3];
memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp));
if (!IS_POSIXACL(dentry->d_inode))
supp[0] &= ~FATTR4_WORD0_ACL;
if (!contextsupport)
supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL;
if (!supp[2]) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(2);
*p++ = cpu_to_be32(supp[0]);
*p++ = cpu_to_be32(supp[1]);
} else {
p = xdr_reserve_space(xdr, 16);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(3);
*p++ = cpu_to_be32(supp[0]);
*p++ = cpu_to_be32(supp[1]);
*p++ = cpu_to_be32(supp[2]);
}
}
if (bmval0 & FATTR4_WORD0_TYPE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
dummy = nfs4_file_type(stat.mode);
if (dummy == NF4BAD) {
status = nfserr_serverfault;
goto out;
}
*p++ = cpu_to_be32(dummy);
}
if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
if (exp->ex_flags & NFSEXP_NOSUBTREECHECK)
*p++ = cpu_to_be32(NFS4_FH_PERSISTENT);
else
*p++ = cpu_to_be32(NFS4_FH_PERSISTENT|
NFS4_FH_VOL_RENAME);
}
if (bmval0 & FATTR4_WORD0_CHANGE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = encode_change(p, &stat, d_inode(dentry), exp);
}
if (bmval0 & FATTR4_WORD0_SIZE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, stat.size);
}
if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_NAMED_ATTR) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_FSID) {
p = xdr_reserve_space(xdr, 16);
if (!p)
goto out_resource;
if (exp->ex_fslocs.migrated) {
p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR);
p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR);
} else switch(fsid_source(fhp)) {
case FSIDSOURCE_FSID:
p = xdr_encode_hyper(p, (u64)exp->ex_fsid);
p = xdr_encode_hyper(p, (u64)0);
break;
case FSIDSOURCE_DEV:
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(MAJOR(stat.dev));
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(MINOR(stat.dev));
break;
case FSIDSOURCE_UUID:
p = xdr_encode_opaque_fixed(p, exp->ex_uuid,
EX_UUID_LEN);
break;
}
}
if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_LEASE_TIME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(nn->nfsd4_lease);
}
if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(rdattr_err);
}
if (bmval0 & FATTR4_WORD0_ACL) {
struct nfs4_ace *ace;
if (acl == NULL) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
goto out_acl;
}
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(acl->naces);
for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) {
p = xdr_reserve_space(xdr, 4*3);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(ace->type);
*p++ = cpu_to_be32(ace->flag);
*p++ = cpu_to_be32(ace->access_mask &
NFS4_ACE_MASK_ALL);
status = nfsd4_encode_aclname(xdr, rqstp, ace);
if (status)
goto out;
}
}
out_acl:
if (bmval0 & FATTR4_WORD0_ACLSUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ?
ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0);
}
if (bmval0 & FATTR4_WORD0_CANSETTIME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_FILEHANDLE) {
p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4);
if (!p)
goto out_resource;
p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base,
fhp->fh_handle.fh_size);
}
if (bmval0 & FATTR4_WORD0_FILEID) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, stat.ino);
}
if (bmval0 & FATTR4_WORD0_FILES_AVAIL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_ffree);
}
if (bmval0 & FATTR4_WORD0_FILES_FREE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_ffree);
}
if (bmval0 & FATTR4_WORD0_FILES_TOTAL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_files);
}
if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) {
status = nfsd4_encode_fs_locations(xdr, rqstp, exp);
if (status)
goto out;
}
if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_MAXFILESIZE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes);
}
if (bmval0 & FATTR4_WORD0_MAXLINK) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(255);
}
if (bmval0 & FATTR4_WORD0_MAXNAME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(statfs.f_namelen);
}
if (bmval0 & FATTR4_WORD0_MAXREAD) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp));
}
if (bmval0 & FATTR4_WORD0_MAXWRITE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp));
}
if (bmval1 & FATTR4_WORD1_MODE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.mode & S_IALLUGO);
}
if (bmval1 & FATTR4_WORD1_NO_TRUNC) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval1 & FATTR4_WORD1_NUMLINKS) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.nlink);
}
if (bmval1 & FATTR4_WORD1_OWNER) {
status = nfsd4_encode_user(xdr, rqstp, stat.uid);
if (status)
goto out;
}
if (bmval1 & FATTR4_WORD1_OWNER_GROUP) {
status = nfsd4_encode_group(xdr, rqstp, stat.gid);
if (status)
goto out;
}
if (bmval1 & FATTR4_WORD1_RAWDEV) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
*p++ = cpu_to_be32((u32) MAJOR(stat.rdev));
*p++ = cpu_to_be32((u32) MINOR(stat.rdev));
}
if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_FREE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_USED) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)stat.blocks << 9;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_TIME_ACCESS) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec);
*p++ = cpu_to_be32(stat.atime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_TIME_DELTA) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(1);
*p++ = cpu_to_be32(0);
}
if (bmval1 & FATTR4_WORD1_TIME_METADATA) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec);
*p++ = cpu_to_be32(stat.ctime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_TIME_MODIFY) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec);
*p++ = cpu_to_be32(stat.mtime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) {
struct kstat parent_stat;
u64 ino = stat.ino;
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
/*
* Get parent's attributes if not ignoring crossmount
* and this is the root of a cross-mounted filesystem.
*/
if (ignore_crossmnt == 0 &&
dentry == exp->ex_path.mnt->mnt_root) {
err = get_parent_attributes(exp, &parent_stat);
if (err)
goto out_nfserr;
ino = parent_stat.ino;
}
p = xdr_encode_hyper(p, ino);
}
#ifdef CONFIG_NFSD_PNFS
if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) {
status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) {
status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.blksize);
}
#endif /* CONFIG_NFSD_PNFS */
if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) {
status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0,
NFSD_SUPPATTR_EXCLCREAT_WORD1,
NFSD_SUPPATTR_EXCLCREAT_WORD2);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) {
status = nfsd4_encode_security_label(xdr, rqstp, context,
contextlen);
if (status)
goto out;
}
attrlen = htonl(xdr->buf->len - attrlen_offset - 4);
write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4);
status = nfs_ok;
out:
#ifdef CONFIG_NFSD_V4_SECURITY_LABEL
if (context)
security_release_secctx(context, contextlen);
#endif /* CONFIG_NFSD_V4_SECURITY_LABEL */
kfree(acl);
if (tempfh) {
fh_put(tempfh);
kfree(tempfh);
}
if (status)
xdr_truncate_encode(xdr, starting_len);
return status;
out_nfserr:
status = nfserrno(err);
goto out;
out_resource:
status = nfserr_resource;
goto out;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,203 |
net | c88507fbad8055297c1d1e21e599f46960cbee39 | int ip6_route_add(struct fib6_config *cfg)
{
int err;
struct net *net = cfg->fc_nlinfo.nl_net;
struct rt6_info *rt = NULL;
struct net_device *dev = NULL;
struct inet6_dev *idev = NULL;
struct fib6_table *table;
int addr_type;
if (cfg->fc_dst_len > 128 || cfg->fc_src_len > 128)
return -EINVAL;
#ifndef CONFIG_IPV6_SUBTREES
if (cfg->fc_src_len)
return -EINVAL;
#endif
if (cfg->fc_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(net, cfg->fc_ifindex);
if (!dev)
goto out;
idev = in6_dev_get(dev);
if (!idev)
goto out;
}
if (cfg->fc_metric == 0)
cfg->fc_metric = IP6_RT_PRIO_USER;
err = -ENOBUFS;
if (cfg->fc_nlinfo.nlh &&
!(cfg->fc_nlinfo.nlh->nlmsg_flags & NLM_F_CREATE)) {
table = fib6_get_table(net, cfg->fc_table);
if (!table) {
pr_warn("NLM_F_CREATE should be specified when creating new route\n");
table = fib6_new_table(net, cfg->fc_table);
}
} else {
table = fib6_new_table(net, cfg->fc_table);
}
if (!table)
goto out;
rt = ip6_dst_alloc(net, NULL, DST_NOCOUNT, table);
if (!rt) {
err = -ENOMEM;
goto out;
}
if (cfg->fc_flags & RTF_EXPIRES)
rt6_set_expires(rt, jiffies +
clock_t_to_jiffies(cfg->fc_expires));
else
rt6_clean_expires(rt);
if (cfg->fc_protocol == RTPROT_UNSPEC)
cfg->fc_protocol = RTPROT_BOOT;
rt->rt6i_protocol = cfg->fc_protocol;
addr_type = ipv6_addr_type(&cfg->fc_dst);
if (addr_type & IPV6_ADDR_MULTICAST)
rt->dst.input = ip6_mc_input;
else if (cfg->fc_flags & RTF_LOCAL)
rt->dst.input = ip6_input;
else
rt->dst.input = ip6_forward;
rt->dst.output = ip6_output;
ipv6_addr_prefix(&rt->rt6i_dst.addr, &cfg->fc_dst, cfg->fc_dst_len);
rt->rt6i_dst.plen = cfg->fc_dst_len;
if (rt->rt6i_dst.plen == 128)
rt->dst.flags |= DST_HOST;
if (!(rt->dst.flags & DST_HOST) && cfg->fc_mx) {
u32 *metrics = kzalloc(sizeof(u32) * RTAX_MAX, GFP_KERNEL);
if (!metrics) {
err = -ENOMEM;
goto out;
}
dst_init_metrics(&rt->dst, metrics, 0);
}
#ifdef CONFIG_IPV6_SUBTREES
ipv6_addr_prefix(&rt->rt6i_src.addr, &cfg->fc_src, cfg->fc_src_len);
rt->rt6i_src.plen = cfg->fc_src_len;
#endif
rt->rt6i_metric = cfg->fc_metric;
/* We cannot add true routes via loopback here,
they would result in kernel looping; promote them to reject routes
*/
if ((cfg->fc_flags & RTF_REJECT) ||
(dev && (dev->flags & IFF_LOOPBACK) &&
!(addr_type & IPV6_ADDR_LOOPBACK) &&
!(cfg->fc_flags & RTF_LOCAL))) {
/* hold loopback dev/idev if we haven't done so. */
if (dev != net->loopback_dev) {
if (dev) {
dev_put(dev);
in6_dev_put(idev);
}
dev = net->loopback_dev;
dev_hold(dev);
idev = in6_dev_get(dev);
if (!idev) {
err = -ENODEV;
goto out;
}
}
rt->rt6i_flags = RTF_REJECT|RTF_NONEXTHOP;
switch (cfg->fc_type) {
case RTN_BLACKHOLE:
rt->dst.error = -EINVAL;
rt->dst.output = dst_discard;
rt->dst.input = dst_discard;
break;
case RTN_PROHIBIT:
rt->dst.error = -EACCES;
rt->dst.output = ip6_pkt_prohibit_out;
rt->dst.input = ip6_pkt_prohibit;
break;
case RTN_THROW:
default:
rt->dst.error = (cfg->fc_type == RTN_THROW) ? -EAGAIN
: -ENETUNREACH;
rt->dst.output = ip6_pkt_discard_out;
rt->dst.input = ip6_pkt_discard;
break;
}
goto install_route;
}
if (cfg->fc_flags & RTF_GATEWAY) {
const struct in6_addr *gw_addr;
int gwa_type;
gw_addr = &cfg->fc_gateway;
rt->rt6i_gateway = *gw_addr;
gwa_type = ipv6_addr_type(gw_addr);
if (gwa_type != (IPV6_ADDR_LINKLOCAL|IPV6_ADDR_UNICAST)) {
struct rt6_info *grt;
/* IPv6 strictly inhibits using not link-local
addresses as nexthop address.
Otherwise, router will not able to send redirects.
It is very good, but in some (rare!) circumstances
(SIT, PtP, NBMA NOARP links) it is handy to allow
some exceptions. --ANK
*/
err = -EINVAL;
if (!(gwa_type & IPV6_ADDR_UNICAST))
goto out;
grt = rt6_lookup(net, gw_addr, NULL, cfg->fc_ifindex, 1);
err = -EHOSTUNREACH;
if (!grt)
goto out;
if (dev) {
if (dev != grt->dst.dev) {
ip6_rt_put(grt);
goto out;
}
} else {
dev = grt->dst.dev;
idev = grt->rt6i_idev;
dev_hold(dev);
in6_dev_hold(grt->rt6i_idev);
}
if (!(grt->rt6i_flags & RTF_GATEWAY))
err = 0;
ip6_rt_put(grt);
if (err)
goto out;
}
err = -EINVAL;
if (!dev || (dev->flags & IFF_LOOPBACK))
goto out;
}
err = -ENODEV;
if (!dev)
goto out;
if (!ipv6_addr_any(&cfg->fc_prefsrc)) {
if (!ipv6_chk_addr(net, &cfg->fc_prefsrc, dev, 0)) {
err = -EINVAL;
goto out;
}
rt->rt6i_prefsrc.addr = cfg->fc_prefsrc;
rt->rt6i_prefsrc.plen = 128;
} else
rt->rt6i_prefsrc.plen = 0;
rt->rt6i_flags = cfg->fc_flags;
install_route:
if (cfg->fc_mx) {
struct nlattr *nla;
int remaining;
nla_for_each_attr(nla, cfg->fc_mx, cfg->fc_mx_len, remaining) {
int type = nla_type(nla);
if (type) {
if (type > RTAX_MAX) {
err = -EINVAL;
goto out;
}
dst_metric_set(&rt->dst, type, nla_get_u32(nla));
}
}
}
rt->dst.dev = dev;
rt->rt6i_idev = idev;
rt->rt6i_table = table;
cfg->fc_nlinfo.nl_net = dev_net(dev);
return __ip6_ins_rt(rt, &cfg->fc_nlinfo);
out:
if (dev)
dev_put(dev);
if (idev)
in6_dev_put(idev);
if (rt)
dst_free(&rt->dst);
return err;
} | 1 | CVE-2014-2309 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 4,663 |
libxml2 | 1358d157d0bd83be1dfe356a69213df9fac0b539 | static void parseAndPrintFile(char *filename, xmlParserCtxtPtr rectxt) {
xmlDocPtr doc = NULL;
#ifdef LIBXML_TREE_ENABLED
xmlDocPtr tmp;
#endif /* LIBXML_TREE_ENABLED */
if ((timing) && (!repeat))
startTimer();
#ifdef LIBXML_TREE_ENABLED
if (filename == NULL) {
if (generate) {
xmlNodePtr n;
doc = xmlNewDoc(BAD_CAST "1.0");
n = xmlNewDocNode(doc, NULL, BAD_CAST "info", NULL);
xmlNodeSetContent(n, BAD_CAST "abc");
xmlDocSetRootElement(doc, n);
}
}
#endif /* LIBXML_TREE_ENABLED */
#ifdef LIBXML_HTML_ENABLED
#ifdef LIBXML_PUSH_ENABLED
else if ((html) && (push)) {
FILE *f;
if ((filename[0] == '-') && (filename[1] == 0)) {
f = stdin;
} else {
#if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__)
f = fopen(filename, "rb");
#elif defined(__OS400__)
f = fopen(filename, "rb");
#else
f = fopen(filename, "r");
#endif
}
if (f != NULL) {
int res;
char chars[4096];
htmlParserCtxtPtr ctxt;
res = fread(chars, 1, 4, f);
if (res > 0) {
ctxt = htmlCreatePushParserCtxt(NULL, NULL,
chars, res, filename, XML_CHAR_ENCODING_NONE);
xmlCtxtUseOptions(ctxt, options);
while ((res = fread(chars, 1, pushsize, f)) > 0) {
htmlParseChunk(ctxt, chars, res, 0);
}
htmlParseChunk(ctxt, chars, 0, 1);
doc = ctxt->myDoc;
htmlFreeParserCtxt(ctxt);
}
fclose(f);
}
}
#endif /* LIBXML_PUSH_ENABLED */
#ifdef HAVE_MMAP
else if ((html) && (memory)) {
int fd;
struct stat info;
const char *base;
if (stat(filename, &info) < 0)
return;
if ((fd = open(filename, O_RDONLY)) < 0)
return;
base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ;
if (base == (void *) MAP_FAILED) {
close(fd);
fprintf(stderr, "mmap failure for file %s\n", filename);
progresult = XMLLINT_ERR_RDFILE;
return;
}
doc = htmlReadMemory((char *) base, info.st_size, filename,
NULL, options);
munmap((char *) base, info.st_size);
close(fd);
}
#endif
else if (html) {
doc = htmlReadFile(filename, NULL, options);
}
#endif /* LIBXML_HTML_ENABLED */
else {
#ifdef LIBXML_PUSH_ENABLED
/*
* build an XML tree from a string;
*/
if (push) {
FILE *f;
/* '-' Usually means stdin -<[email protected]> */
if ((filename[0] == '-') && (filename[1] == 0)) {
f = stdin;
} else {
#if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__)
f = fopen(filename, "rb");
#elif defined(__OS400__)
f = fopen(filename, "rb");
#else
f = fopen(filename, "r");
#endif
}
if (f != NULL) {
int ret;
int res, size = 1024;
char chars[1024];
xmlParserCtxtPtr ctxt;
/* if (repeat) size = 1024; */
res = fread(chars, 1, 4, f);
if (res > 0) {
ctxt = xmlCreatePushParserCtxt(NULL, NULL,
chars, res, filename);
xmlCtxtUseOptions(ctxt, options);
while ((res = fread(chars, 1, size, f)) > 0) {
xmlParseChunk(ctxt, chars, res, 0);
}
xmlParseChunk(ctxt, chars, 0, 1);
doc = ctxt->myDoc;
ret = ctxt->wellFormed;
xmlFreeParserCtxt(ctxt);
if ((!ret) && (!recovery)) {
xmlFreeDoc(doc);
doc = NULL;
}
}
if (f != stdin)
fclose(f);
}
} else
#endif /* LIBXML_PUSH_ENABLED */
if (testIO) {
if ((filename[0] == '-') && (filename[1] == 0)) {
doc = xmlReadFd(0, NULL, NULL, options);
} else {
FILE *f;
#if defined(_WIN32) || defined (__DJGPP__) && !defined (__CYGWIN__)
f = fopen(filename, "rb");
#elif defined(__OS400__)
f = fopen(filename, "rb");
#else
f = fopen(filename, "r");
#endif
if (f != NULL) {
if (rectxt == NULL)
doc = xmlReadIO(myRead, myClose, f, filename, NULL,
options);
else
doc = xmlCtxtReadIO(rectxt, myRead, myClose, f,
filename, NULL, options);
} else
doc = NULL;
}
} else if (htmlout) {
xmlParserCtxtPtr ctxt;
if (rectxt == NULL)
ctxt = xmlNewParserCtxt();
else
ctxt = rectxt;
if (ctxt == NULL) {
doc = NULL;
} else {
ctxt->sax->error = xmlHTMLError;
ctxt->sax->warning = xmlHTMLWarning;
ctxt->vctxt.error = xmlHTMLValidityError;
ctxt->vctxt.warning = xmlHTMLValidityWarning;
doc = xmlCtxtReadFile(ctxt, filename, NULL, options);
if (rectxt == NULL)
xmlFreeParserCtxt(ctxt);
}
#ifdef HAVE_MMAP
} else if (memory) {
int fd;
struct stat info;
const char *base;
if (stat(filename, &info) < 0)
return;
if ((fd = open(filename, O_RDONLY)) < 0)
return;
base = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, fd, 0) ;
if (base == (void *) MAP_FAILED) {
close(fd);
fprintf(stderr, "mmap failure for file %s\n", filename);
progresult = XMLLINT_ERR_RDFILE;
return;
}
if (rectxt == NULL)
doc = xmlReadMemory((char *) base, info.st_size,
filename, NULL, options);
else
doc = xmlCtxtReadMemory(rectxt, (char *) base, info.st_size,
filename, NULL, options);
munmap((char *) base, info.st_size);
close(fd);
#endif
#ifdef LIBXML_VALID_ENABLED
} else if (valid) {
xmlParserCtxtPtr ctxt = NULL;
if (rectxt == NULL)
ctxt = xmlNewParserCtxt();
else
ctxt = rectxt;
if (ctxt == NULL) {
doc = NULL;
} else {
doc = xmlCtxtReadFile(ctxt, filename, NULL, options);
if (ctxt->valid == 0)
progresult = XMLLINT_ERR_RDFILE;
if (rectxt == NULL)
xmlFreeParserCtxt(ctxt);
}
#endif /* LIBXML_VALID_ENABLED */
} else {
if (rectxt != NULL)
doc = xmlCtxtReadFile(rectxt, filename, NULL, options);
else {
#ifdef LIBXML_SAX1_ENABLED
if (sax1)
doc = xmlParseFile(filename);
else
#endif /* LIBXML_SAX1_ENABLED */
doc = xmlReadFile(filename, NULL, options);
}
}
}
/*
* If we don't have a document we might as well give up. Do we
* want an error message here? <[email protected]> */
if (doc == NULL) {
progresult = XMLLINT_ERR_UNCLASS;
return;
}
if ((timing) && (!repeat)) {
endTimer("Parsing");
}
/*
* Remove DOCTYPE nodes
*/
if (dropdtd) {
xmlDtdPtr dtd;
dtd = xmlGetIntSubset(doc);
if (dtd != NULL) {
xmlUnlinkNode((xmlNodePtr)dtd);
xmlFreeDtd(dtd);
}
}
#ifdef LIBXML_XINCLUDE_ENABLED
if (xinclude) {
if ((timing) && (!repeat)) {
startTimer();
}
if (xmlXIncludeProcessFlags(doc, options) < 0)
progresult = XMLLINT_ERR_UNCLASS;
if ((timing) && (!repeat)) {
endTimer("Xinclude processing");
}
}
#endif
#ifdef LIBXML_XPATH_ENABLED
if (xpathquery != NULL) {
doXPathQuery(doc, xpathquery);
}
#endif
#ifdef LIBXML_DEBUG_ENABLED
#ifdef LIBXML_XPATH_ENABLED
/*
* shell interaction
*/
if (shell) {
xmlXPathOrderDocElems(doc);
xmlShell(doc, filename, xmlShellReadline, stdout);
}
#endif
#endif
#ifdef LIBXML_TREE_ENABLED
/*
* test intermediate copy if needed.
*/
if (copy) {
tmp = doc;
if (timing) {
startTimer();
}
doc = xmlCopyDoc(doc, 1);
if (timing) {
endTimer("Copying");
}
if (timing) {
startTimer();
}
xmlFreeDoc(tmp);
if (timing) {
endTimer("Freeing original");
}
}
#endif /* LIBXML_TREE_ENABLED */
#ifdef LIBXML_VALID_ENABLED
if ((insert) && (!html)) {
const xmlChar* list[256];
int nb, i;
xmlNodePtr node;
if (doc->children != NULL) {
node = doc->children;
while ((node != NULL) && (node->last == NULL)) node = node->next;
if (node != NULL) {
nb = xmlValidGetValidElements(node->last, NULL, list, 256);
if (nb < 0) {
fprintf(stderr, "could not get valid list of elements\n");
} else if (nb == 0) {
fprintf(stderr, "No element can be inserted under root\n");
} else {
fprintf(stderr, "%d element types can be inserted under root:\n",
nb);
for (i = 0;i < nb;i++) {
fprintf(stderr, "%s\n", (char *) list[i]);
}
}
}
}
}else
#endif /* LIBXML_VALID_ENABLED */
#ifdef LIBXML_READER_ENABLED
if (walker) {
walkDoc(doc);
}
#endif /* LIBXML_READER_ENABLED */
#ifdef LIBXML_OUTPUT_ENABLED
if (noout == 0) {
int ret;
/*
* print it.
*/
#ifdef LIBXML_DEBUG_ENABLED
if (!debug) {
#endif
if ((timing) && (!repeat)) {
startTimer();
}
#ifdef LIBXML_HTML_ENABLED
if ((html) && (!xmlout)) {
if (compress) {
htmlSaveFile(output ? output : "-", doc);
}
else if (encoding != NULL) {
if (format == 1) {
htmlSaveFileFormat(output ? output : "-", doc, encoding, 1);
}
else {
htmlSaveFileFormat(output ? output : "-", doc, encoding, 0);
}
}
else if (format == 1) {
htmlSaveFileFormat(output ? output : "-", doc, NULL, 1);
}
else {
FILE *out;
if (output == NULL)
out = stdout;
else {
out = fopen(output,"wb");
}
if (out != NULL) {
if (htmlDocDump(out, doc) < 0)
progresult = XMLLINT_ERR_OUT;
if (output != NULL)
fclose(out);
} else {
fprintf(stderr, "failed to open %s\n", output);
progresult = XMLLINT_ERR_OUT;
}
}
if ((timing) && (!repeat)) {
endTimer("Saving");
}
} else
#endif
#ifdef LIBXML_C14N_ENABLED
if (canonical) {
xmlChar *result = NULL;
int size;
size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_1_0, NULL, 1, &result);
if (size >= 0) {
if (write(1, result, size) == -1) {
fprintf(stderr, "Can't write data\n");
}
xmlFree(result);
} else {
fprintf(stderr, "Failed to canonicalize\n");
progresult = XMLLINT_ERR_OUT;
}
} else if (canonical_11) {
xmlChar *result = NULL;
int size;
size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_1_1, NULL, 1, &result);
if (size >= 0) {
if (write(1, result, size) == -1) {
fprintf(stderr, "Can't write data\n");
}
xmlFree(result);
} else {
fprintf(stderr, "Failed to canonicalize\n");
progresult = XMLLINT_ERR_OUT;
}
} else
if (exc_canonical) {
xmlChar *result = NULL;
int size;
size = xmlC14NDocDumpMemory(doc, NULL, XML_C14N_EXCLUSIVE_1_0, NULL, 1, &result);
if (size >= 0) {
if (write(1, result, size) == -1) {
fprintf(stderr, "Can't write data\n");
}
xmlFree(result);
} else {
fprintf(stderr, "Failed to canonicalize\n");
progresult = XMLLINT_ERR_OUT;
}
} else
#endif
#ifdef HAVE_MMAP
if (memory) {
xmlChar *result;
int len;
if (encoding != NULL) {
if (format == 1) {
xmlDocDumpFormatMemoryEnc(doc, &result, &len, encoding, 1);
} else {
xmlDocDumpMemoryEnc(doc, &result, &len, encoding);
}
} else {
if (format == 1)
xmlDocDumpFormatMemory(doc, &result, &len, 1);
else
xmlDocDumpMemory(doc, &result, &len);
}
if (result == NULL) {
fprintf(stderr, "Failed to save\n");
progresult = XMLLINT_ERR_OUT;
} else {
if (write(1, result, len) == -1) {
fprintf(stderr, "Can't write data\n");
}
xmlFree(result);
}
} else
#endif /* HAVE_MMAP */
if (compress) {
xmlSaveFile(output ? output : "-", doc);
} else if (oldout) {
if (encoding != NULL) {
if (format == 1) {
ret = xmlSaveFormatFileEnc(output ? output : "-", doc,
encoding, 1);
}
else {
ret = xmlSaveFileEnc(output ? output : "-", doc,
encoding);
}
if (ret < 0) {
fprintf(stderr, "failed save to %s\n",
output ? output : "-");
progresult = XMLLINT_ERR_OUT;
}
} else if (format == 1) {
ret = xmlSaveFormatFile(output ? output : "-", doc, 1);
if (ret < 0) {
fprintf(stderr, "failed save to %s\n",
output ? output : "-");
progresult = XMLLINT_ERR_OUT;
}
} else {
FILE *out;
if (output == NULL)
out = stdout;
else {
out = fopen(output,"wb");
}
if (out != NULL) {
if (xmlDocDump(out, doc) < 0)
progresult = XMLLINT_ERR_OUT;
if (output != NULL)
fclose(out);
} else {
fprintf(stderr, "failed to open %s\n", output);
progresult = XMLLINT_ERR_OUT;
}
}
} else {
xmlSaveCtxtPtr ctxt;
int saveOpts = 0;
if (format == 1)
saveOpts |= XML_SAVE_FORMAT;
else if (format == 2)
saveOpts |= XML_SAVE_WSNONSIG;
#if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED)
if (xmlout)
saveOpts |= XML_SAVE_AS_XML;
#endif
if (output == NULL)
ctxt = xmlSaveToFd(1, encoding, saveOpts);
else
ctxt = xmlSaveToFilename(output, encoding, saveOpts);
if (ctxt != NULL) {
if (xmlSaveDoc(ctxt, doc) < 0) {
fprintf(stderr, "failed save to %s\n",
output ? output : "-");
progresult = XMLLINT_ERR_OUT;
}
xmlSaveClose(ctxt);
} else {
progresult = XMLLINT_ERR_OUT;
}
}
if ((timing) && (!repeat)) {
endTimer("Saving");
}
#ifdef LIBXML_DEBUG_ENABLED
} else {
FILE *out;
if (output == NULL)
out = stdout;
else {
out = fopen(output,"wb");
}
if (out != NULL) {
xmlDebugDumpDocument(out, doc);
if (output != NULL)
fclose(out);
} else {
fprintf(stderr, "failed to open %s\n", output);
progresult = XMLLINT_ERR_OUT;
}
}
#endif
}
#endif /* LIBXML_OUTPUT_ENABLED */
#ifdef LIBXML_VALID_ENABLED
/*
* A posteriori validation test
*/
if ((dtdvalid != NULL) || (dtdvalidfpi != NULL)) {
xmlDtdPtr dtd;
if ((timing) && (!repeat)) {
startTimer();
}
if (dtdvalid != NULL)
dtd = xmlParseDTD(NULL, (const xmlChar *)dtdvalid);
else
dtd = xmlParseDTD((const xmlChar *)dtdvalidfpi, NULL);
if ((timing) && (!repeat)) {
endTimer("Parsing DTD");
}
if (dtd == NULL) {
if (dtdvalid != NULL)
xmlGenericError(xmlGenericErrorContext,
"Could not parse DTD %s\n", dtdvalid);
else
xmlGenericError(xmlGenericErrorContext,
"Could not parse DTD %s\n", dtdvalidfpi);
progresult = XMLLINT_ERR_DTD;
} else {
xmlValidCtxtPtr cvp;
if ((cvp = xmlNewValidCtxt()) == NULL) {
xmlGenericError(xmlGenericErrorContext,
"Couldn't allocate validation context\n");
exit(-1);
}
cvp->userData = NULL;
cvp->error = xmlGenericError;
cvp->warning = xmlGenericError;
if ((timing) && (!repeat)) {
startTimer();
}
if (!xmlValidateDtd(cvp, doc, dtd)) {
if (dtdvalid != NULL)
xmlGenericError(xmlGenericErrorContext,
"Document %s does not validate against %s\n",
filename, dtdvalid);
else
xmlGenericError(xmlGenericErrorContext,
"Document %s does not validate against %s\n",
filename, dtdvalidfpi);
progresult = XMLLINT_ERR_VALID;
}
if ((timing) && (!repeat)) {
endTimer("Validating against DTD");
}
xmlFreeValidCtxt(cvp);
xmlFreeDtd(dtd);
}
} else if (postvalid) {
xmlValidCtxtPtr cvp;
if ((cvp = xmlNewValidCtxt()) == NULL) {
xmlGenericError(xmlGenericErrorContext,
"Couldn't allocate validation context\n");
exit(-1);
}
if ((timing) && (!repeat)) {
startTimer();
}
cvp->userData = NULL;
cvp->error = xmlGenericError;
cvp->warning = xmlGenericError;
if (!xmlValidateDocument(cvp, doc)) {
xmlGenericError(xmlGenericErrorContext,
"Document %s does not validate\n", filename);
progresult = XMLLINT_ERR_VALID;
}
if ((timing) && (!repeat)) {
endTimer("Validating");
}
xmlFreeValidCtxt(cvp);
}
#endif /* LIBXML_VALID_ENABLED */
#ifdef LIBXML_SCHEMATRON_ENABLED
if (wxschematron != NULL) {
xmlSchematronValidCtxtPtr ctxt;
int ret;
int flag;
if ((timing) && (!repeat)) {
startTimer();
}
if (debug)
flag = XML_SCHEMATRON_OUT_XML;
else
flag = XML_SCHEMATRON_OUT_TEXT;
if (noout)
flag |= XML_SCHEMATRON_OUT_QUIET;
ctxt = xmlSchematronNewValidCtxt(wxschematron, flag);
#if 0
xmlSchematronSetValidErrors(ctxt, xmlGenericError, xmlGenericError,
NULL);
#endif
ret = xmlSchematronValidateDoc(ctxt, doc);
if (ret == 0) {
if (!quiet) {
fprintf(stderr, "%s validates\n", filename);
}
} else if (ret > 0) {
fprintf(stderr, "%s fails to validate\n", filename);
progresult = XMLLINT_ERR_VALID;
} else {
fprintf(stderr, "%s validation generated an internal error\n",
filename);
progresult = XMLLINT_ERR_VALID;
}
xmlSchematronFreeValidCtxt(ctxt);
if ((timing) && (!repeat)) {
endTimer("Validating");
}
}
#endif
#ifdef LIBXML_SCHEMAS_ENABLED
if (relaxngschemas != NULL) {
xmlRelaxNGValidCtxtPtr ctxt;
int ret;
if ((timing) && (!repeat)) {
startTimer();
}
ctxt = xmlRelaxNGNewValidCtxt(relaxngschemas);
xmlRelaxNGSetValidErrors(ctxt, xmlGenericError, xmlGenericError, NULL);
ret = xmlRelaxNGValidateDoc(ctxt, doc);
if (ret == 0) {
if (!quiet) {
fprintf(stderr, "%s validates\n", filename);
}
} else if (ret > 0) {
fprintf(stderr, "%s fails to validate\n", filename);
progresult = XMLLINT_ERR_VALID;
} else {
fprintf(stderr, "%s validation generated an internal error\n",
filename);
progresult = XMLLINT_ERR_VALID;
}
xmlRelaxNGFreeValidCtxt(ctxt);
if ((timing) && (!repeat)) {
endTimer("Validating");
}
} else if (wxschemas != NULL) {
xmlSchemaValidCtxtPtr ctxt;
int ret;
if ((timing) && (!repeat)) {
startTimer();
}
ctxt = xmlSchemaNewValidCtxt(wxschemas);
xmlSchemaSetValidErrors(ctxt, xmlGenericError, xmlGenericError, NULL);
ret = xmlSchemaValidateDoc(ctxt, doc);
if (ret == 0) {
if (!quiet) {
fprintf(stderr, "%s validates\n", filename);
}
} else if (ret > 0) {
fprintf(stderr, "%s fails to validate\n", filename);
progresult = XMLLINT_ERR_VALID;
} else {
fprintf(stderr, "%s validation generated an internal error\n",
filename);
progresult = XMLLINT_ERR_VALID;
}
xmlSchemaFreeValidCtxt(ctxt);
if ((timing) && (!repeat)) {
endTimer("Validating");
}
}
#endif
#ifdef LIBXML_DEBUG_ENABLED
#if defined(LIBXML_HTML_ENABLED) || defined(LIBXML_VALID_ENABLED)
if ((debugent) && (!html))
xmlDebugDumpEntities(stderr, doc);
#endif
#endif
/*
* free it.
*/
if ((timing) && (!repeat)) {
startTimer();
}
xmlFreeDoc(doc);
if ((timing) && (!repeat)) {
endTimer("Freeing");
}
} | 1 | CVE-2021-3516 | CWE-416 | Use After Free | The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer. |
Phase: Architecture and Design
Strategy: Language Selection
Choose a language that provides automatic memory management.
Phase: Implementation
Strategy: Attack Surface Reduction
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization of multiple or complex data structures may lower the usefulness of this strategy.
Effectiveness: Defense in Depth
Note: If a bug causes an attempted access of this pointer, then a NULL dereference could still lead to a crash or other unexpected behavior, but it will reduce or eliminate the risk of code execution. | 6,487 |
abrt | 50ee8130fb4cd4ef1af7682a2c85dd99cb99424e | int main(int argc, char **argv)
{
/* I18n */
setlocale(LC_ALL, "");
#if ENABLE_NLS
bindtextdomain(PACKAGE, LOCALEDIR);
textdomain(PACKAGE);
#endif
abrt_init(argv);
/* Can't keep these strings/structs static: _() doesn't support that */
const char *program_usage_string = _(
"& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n"
"\t[-r REPO]\n"
"\n"
"Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n"
"ABRT system cache."
);
enum {
OPT_v = 1 << 0,
OPT_y = 1 << 1,
OPT_i = 1 << 2,
OPT_e = 1 << 3,
OPT_r = 1 << 4,
OPT_s = 1 << 5,
};
const char *build_ids = "build_ids";
const char *exact = NULL;
const char *repo = NULL;
const char *size_mb = NULL;
struct options program_options[] = {
OPT__VERBOSE(&g_verbose),
OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")),
OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")),
OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")),
OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")),
OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")),
OPT_END()
};
const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string);
const gid_t egid = getegid();
const gid_t rgid = getgid();
const uid_t euid = geteuid();
const gid_t ruid = getuid();
/* We need to open the build ids file under the caller's UID/GID to avoid
* information disclosures when reading files with changed UID.
* Unfortunately, we cannot replace STDIN with the new fd because ABRT uses
* STDIN to communicate with the caller. So, the following code opens a
* dummy file descriptor to the build ids file and passes the new fd's proc
* path to the wrapped program in the ids argument.
* The new fd remains opened, the OS will close it for us. */
char *build_ids_self_fd = NULL;
if (strcmp("-", build_ids) != 0)
{
if (setregid(egid, rgid) < 0)
perror_msg_and_die("setregid(egid, rgid)");
if (setreuid(euid, ruid) < 0)
perror_msg_and_die("setreuid(euid, ruid)");
const int build_ids_fd = open(build_ids, O_RDONLY);
if (setregid(rgid, egid) < 0)
perror_msg_and_die("setregid(rgid, egid)");
if (setreuid(ruid, euid) < 0 )
perror_msg_and_die("setreuid(ruid, euid)");
if (build_ids_fd < 0)
perror_msg_and_die("Failed to open file '%s'", build_ids);
/* We are not going to free this memory. There is no place to do so. */
build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd);
}
char tmp_directory[] = LARGE_DATA_TMP_DIR"/abrt-tmp-debuginfo.XXXXXX";
if (mkdtemp(tmp_directory) == NULL)
perror_msg_and_die("Failed to create working directory");
log_info("Created working directory: %s", tmp_directory);
/* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, -t, PATH, --, NULL */
const char *args[13];
{
const char *verbs[] = { "", "-v", "-vv", "-vvv" };
unsigned i = 0;
args[i++] = EXECUTABLE;
args[i++] = "--ids";
args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-";
if (g_verbose > 0)
args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3];
if ((opts & OPT_y))
args[i++] = "-y";
if ((opts & OPT_e))
{
args[i++] = "--exact";
args[i++] = exact;
}
if ((opts & OPT_r))
{
args[i++] = "--repo";
args[i++] = repo;
}
args[i++] = "--tmpdir";
args[i++] = tmp_directory;
args[i++] = "--";
args[i] = NULL;
}
/* Switch real user/group to effective ones.
* Otherwise yum library gets confused - gets EPERM (why??).
*/
/* do setregid only if we have to, to not upset selinux needlessly */
if (egid != rgid)
IGNORE_RESULT(setregid(egid, egid));
if (euid != ruid)
{
IGNORE_RESULT(setreuid(euid, euid));
/* We are suid'ed! */
/* Prevent malicious user from messing up with suid'ed process: */
#if 1
static const char *whitelist[] = {
"REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave
"LANG",
};
const size_t wlsize = sizeof(whitelist)/sizeof(char*);
char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 };
char *p = NULL;
for (size_t i = 0; i < wlsize; i++)
if ((p = getenv(whitelist[i])) != NULL)
setlist[i] = xstrdup(p);
clearenv();
for (size_t i = 0; i < wlsize; i++)
if (setlist[i] != NULL)
{
xsetenv(whitelist[i], setlist[i]);
free(setlist[i]);
}
#else
/* Clear dangerous stuff from env */
static const char forbid[] =
"LD_LIBRARY_PATH" "\0"
"LD_PRELOAD" "\0"
"LD_TRACE_LOADED_OBJECTS" "\0"
"LD_BIND_NOW" "\0"
"LD_AOUT_LIBRARY_PATH" "\0"
"LD_AOUT_PRELOAD" "\0"
"LD_NOWARN" "\0"
"LD_KEEPDIR" "\0"
;
const char *p = forbid;
do {
unsetenv(p);
p += strlen(p) + 1;
} while (*p);
#endif
/* Set safe PATH */
char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR;
if (euid != 0)
strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR);
putenv(path_env);
/* Use safe umask */
umask(0022);
}
pid_t pid = fork();
if (pid < 0)
perror_msg_and_die("fork");
if (pid == 0)
{
execvp(EXECUTABLE, (char **)args);
error_msg_and_die("Can't execute %s", EXECUTABLE);
}
int status;
if (safe_waitpid(pid, &status, 0) < 0)
perror_msg_and_die("waitpid");
if (rmdir(tmp_directory) >= 0)
log_info("Removed working directory: %s", tmp_directory);
else if (errno != ENOENT)
perror_msg("Failed to remove working directory");
/* Normal execution should exit here. */
if (WIFEXITED(status))
return WEXITSTATUS(status);
if (WIFSIGNALED(status))
error_msg_and_die("Child terminated with signal %d", WTERMSIG(status));
error_msg_and_die("Child exit failed");
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 22,181 |
libzmq | 77f14aad95cdf0d2a244ae9b4a025e5ba0adf01a | int zmq::stream_engine_t::pull_msg_from_session (msg_t *msg_)
{
return session->pull_msg (msg_);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 10,843 |
linux | a399b29dfbaaaf91162b2dc5a5875dd51bbfa2a1 | static bool shm_may_destroy(struct ipc_namespace *ns, struct shmid_kernel *shp)
{
return (shp->shm_nattch == 0) &&
(ns->shm_rmid_forced ||
(shp->shm_perm.mode & SHM_DEST));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,678 |
Android | 4cff1f49ff95d990d6c2614da5d5a23d02145885 | static inline jboolean boolTojboolean(bool value) {
return value ? JNI_TRUE : JNI_FALSE;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 17,750 |
vlc | 204291467724867b79735c0ee3aeb0dbc2200f97 | static int rtp_packetize_g726_32( sout_stream_id_sys_t *id, block_t *in )
{
return rtp_packetize_g726( id, in, 2 );
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,953 |
linux | df453700e8d81b1bdafdf684365ee2b9431fb702 | __be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
| 1 | CVE-2019-10638 | CWE-200 | Exposure of Sensitive Information to an Unauthorized Actor | The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. |
Phase: Architecture and Design
Strategy: Separation of Privilege
Compartmentalize the system to have "safe" areas where trust boundaries can be unambiguously drawn. Do not allow sensitive data to go outside of the trust boundary and always be careful when interfacing with a compartment outside of the safe area.
Ensure that appropriate compartmentalization is built into the system design, and the compartmentalization allows for and reinforces privilege separation functionality. Architects and designers should rely on the principle of least privilege to decide the appropriate time to use privileges and the time to drop privileges. | 2,210 |
openexr | bc88cdb6c97fbf5bc5d11ad8ca55306da931283a | ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
{
#if ILMBASE_THREADING_ENABLED
std::lock_guard<std::mutex> lock (*_streamData);
#endif
const ChannelList &channels = _data->header.channels();
for (FrameBuffer::ConstIterator j = frameBuffer.begin();
j != frameBuffer.end();
++j)
{
ChannelList::ConstIterator i = channels.find (j.name());
if (i == channels.end())
continue;
if (i.channel().xSampling != j.slice().xSampling ||
i.channel().ySampling != j.slice().ySampling)
THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors "
"of \"" << i.name() << "\" channel "
"of input file \"" << fileName() << "\" are "
"not compatible with the frame buffer's "
"subsampling factors.");
}
// optimization is possible if this is a little endian system
// and both inputs and outputs are half floats
//
bool optimizationPossible = true;
if (!GLOBAL_SYSTEM_LITTLE_ENDIAN)
{
optimizationPossible =false;
}
vector<sliceOptimizationData> optData;
//
// Initialize the slice table for readPixels().
//
vector<InSliceInfo> slices;
ChannelList::ConstIterator i = channels.begin();
// current offset of channel: pixel data starts at offset*width into the
// decompressed scanline buffer
size_t offset = 0;
for (FrameBuffer::ConstIterator j = frameBuffer.begin();
j != frameBuffer.end();
++j)
{
while (i != channels.end() && strcmp (i.name(), j.name()) < 0)
{
//
// Channel i is present in the file but not
// in the frame buffer; data for channel i
// will be skipped during readPixels().
//
slices.push_back (InSliceInfo (i.channel().type,
i.channel().type,
0, // base
0, // xStride
0, // yStride
i.channel().xSampling,
i.channel().ySampling,
false, // fill
true, // skip
0.0)); // fillValue
switch(i.channel().type)
{
case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
offset++;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
offset+=2;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
offset+=2;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES:
default:
// not possible.
break;
}
//
// optimization mode cannot currently skip subsampled channels
//
if (i.channel().xSampling!=1 || i.channel().ySampling!=1)
{
optimizationPossible = false;
}
++i;
}
bool fill = false;
if (i == channels.end() || strcmp (i.name(), j.name()) > 0)
{
//
// Channel i is present in the frame buffer, but not in the file.
// In the frame buffer, slice j will be filled with a default value.
//
fill = true;
}
slices.push_back (InSliceInfo (j.slice().type,
fill? j.slice().type:
i.channel().type,
j.slice().base,
j.slice().xStride,
j.slice().yStride,
j.slice().xSampling,
j.slice().ySampling,
fill,
false, // skip
j.slice().fillValue));
if(!fill && i.channel().type!=OPENEXR_IMF_INTERNAL_NAMESPACE::HALF)
{
optimizationPossible = false;
}
if(j.slice().type != OPENEXR_IMF_INTERNAL_NAMESPACE::HALF)
{
optimizationPossible = false;
}
if(j.slice().xSampling!=1 || j.slice().ySampling!=1)
{
optimizationPossible = false;
}
if(optimizationPossible)
{
sliceOptimizationData dat;
dat.base = j.slice().base;
dat.fill = fill;
dat.fillValue = j.slice().fillValue;
dat.offset = offset;
dat.xStride = j.slice().xStride;
dat.yStride = j.slice().yStride;
dat.xSampling = j.slice().xSampling;
dat.ySampling = j.slice().ySampling;
optData.push_back(dat);
}
if(!fill)
{
switch(i.channel().type)
{
case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF :
offset++;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT :
offset+=2;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT :
offset+=2;
break;
case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES:
default:
// not possible.
break;
}
}
if (i != channels.end() && !fill)
++i;
}
if(optimizationPossible)
{
//
// check optimisibility
// based on channel ordering and fill channel positions
//
sort(optData.begin(),optData.end());
_data->optimizationMode = detectOptimizationMode(optData);
}
if(!optimizationPossible || _data->optimizationMode._optimizable==false)
{
optData = vector<sliceOptimizationData>();
_data->optimizationMode._optimizable=false;
}
//
// Store the new frame buffer.
//
_data->frameBuffer = frameBuffer;
_data->slices = slices;
_data->optimizationData = optData;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,079 |
Chrome | c90c6ca59378d7e86d1a2f28fe96bada35df1508 | void FindBarController::EndFindSession(SelectionAction action) {
find_bar_->Hide(true);
if (tab_contents_) {
FindManager* find_manager = tab_contents_->GetFindManager();
find_manager->StopFinding(action);
if (action != kKeepSelection)
find_bar_->ClearResults(find_manager->find_result());
find_bar_->RestoreSavedFocus();
}
}
| 1 | CVE-2011-1296 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 9,422 |
lighttpd1.4 | 32120d5b8b3203fc21ccb9eafb0eaf824bb59354 | static void test_burl_normalize (void) {
buffer *psrc = buffer_init();
buffer *ptmp = buffer_init();
int flags;
flags = HTTP_PARSEOPT_URL_NORMALIZE_UNRESERVED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("no-slash"), CONST_STR_LEN("no-slash"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/%2B"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/%3A"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags = HTTP_PARSEOPT_URL_NORMALIZE_REQUIRED;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/"), CONST_STR_LEN("/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc"), CONST_STR_LEN("/abc"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/"), CONST_STR_LEN("/abc/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc/def"), CONST_STR_LEN("/abc/def"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?"), CONST_STR_LEN("/abc?"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d"), CONST_STR_LEN("/abc?d"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d="), CONST_STR_LEN("/abc?d="));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e"), CONST_STR_LEN("/abc?d=e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&"), CONST_STR_LEN("/abc?d=e&"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f"), CONST_STR_LEN("/abc?d=e&f"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/abc?d=e&f=g#any"), CONST_STR_LEN("/abc?d=e&f=g"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2F"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2f"), CONST_STR_LEN("/%2F"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%20"), CONST_STR_LEN("/%20"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2b"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%2B"), CONST_STR_LEN("/+"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3a"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/%3A"), CONST_STR_LEN("/:"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/~test%20ä_"), CONST_STR_LEN("/~test%20%C3%A4_"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\375"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\376"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\377"), "", (size_t)-2);
flags |= HTTP_PARSEOPT_URL_NORMALIZE_CTRLS_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\a"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\t"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\r"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/\177"), "", (size_t)-2);
#if defined(__WIN32) || defined(__CYGWIN__)
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_BACKSLASH_TRANS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a\\b"), CONST_STR_LEN("/a/b"));
#endif
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=/"), CONST_STR_LEN("/a/b?c=/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_DECODE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a%2Fb"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=%2f"), CONST_STR_LEN("/a/b?c=/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_2F_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), CONST_STR_LEN("/a/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), CONST_STR_LEN("/b"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), CONST_STR_LEN("/a/b/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), CONST_STR_LEN("/a/"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b/.."), CONST_STR_LEN("/"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REMOVE;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("./a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("../a/b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/./b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/../b"), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/."), "", (size_t)-2);
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b/.."), "", (size_t)-2);
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_PATH_DOTSEG_REJECT;
flags |= HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d+e"), CONST_STR_LEN("/a/b?c=d+e"));
run_burl_normalize(psrc, ptmp, flags, __LINE__, CONST_STR_LEN("/a/b?c=d%20e"), CONST_STR_LEN("/a/b?c=d+e"));
flags &= ~HTTP_PARSEOPT_URL_NORMALIZE_QUERY_20_PLUS;
buffer_free(psrc);
buffer_free(ptmp);
}
| 1 | CVE-2019-11072 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 6,286 |
mysql-server | dc45e408250c582eb532417a42cef5b5a8e2fe77 | allocset(p)
register struct parse *p;
{
register int no = p->g->ncsets++;
register size_t nc;
register size_t nbytes;
register cset *cs;
register size_t css = (size_t)p->g->csetsize;
register int i;
if (no >= p->ncsalloc) { /* need another column of space */
p->ncsalloc += CHAR_BIT;
nc = p->ncsalloc;
assert(nc % CHAR_BIT == 0);
nbytes = nc / CHAR_BIT * css;
if (p->g->sets == NULL)
p->g->sets = (cset *)malloc(nc * sizeof(cset));
else
p->g->sets = (cset *)realloc((char *)p->g->sets,
nc * sizeof(cset));
if (p->g->setbits == NULL)
p->g->setbits = (uch *)malloc(nbytes);
else {
p->g->setbits = (uch *)realloc((char *)p->g->setbits,
nbytes);
/* xxx this isn't right if setbits is now NULL */
for (i = 0; i < no; i++)
p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
}
if (p->g->sets != NULL && p->g->setbits != NULL)
(void) memset((char *)p->g->setbits + (nbytes - css),
0, css);
else {
no = 0;
SETERROR(REG_ESPACE);
/* caller's responsibility not to do set ops */
}
}
assert(p->g->sets != NULL); /* xxx */
cs = &p->g->sets[no];
cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
cs->mask = 1 << ((no) % CHAR_BIT);
cs->hash = 0;
cs->smultis = 0;
cs->multis = NULL;
return(cs);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,991 |
libplist | 4765d9a60ca4248a8f89289271ac69cbffcc29bc | static plist_t parse_array_node(struct bplist_data *bplist, const char** bnode, uint64_t size)
{
uint64_t j;
uint32_t str_j = 0;
uint32_t index1;
plist_data_t data = plist_new_plist_data();
data->type = PLIST_ARRAY;
data->length = size;
plist_t node = node_create(NULL, data);
for (j = 0; j < data->length; j++) {
str_j = j * bplist->ref_size;
index1 = UINT_TO_HOST((*bnode) + str_j, bplist->ref_size);
if (index1 >= bplist->num_objects) {
plist_free(node);
return NULL;
}
/* process value node */
plist_t val = parse_bin_node_at_index(bplist, index1);
if (!val) {
plist_free(node);
return NULL;
}
node_attach(node, val);
}
return node;
} | 1 | CVE-2017-5834 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 5,661 |
pgbouncer | 4b92112b820830b30cd7bc91bef3dd8f35305525 | int get_active_server_count(void)
{
return slab_active_count(server_cache);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,335 |
jasper | d678ccd27b8a062e3bfd4c80d8ce2676a8166a27 | static jas_stream_t *jas_stream_create()
{
jas_stream_t *stream;
if (!(stream = jas_malloc(sizeof(jas_stream_t)))) {
return 0;
}
stream->openmode_ = 0;
stream->bufmode_ = 0;
stream->flags_ = 0;
stream->bufbase_ = 0;
stream->bufstart_ = 0;
stream->bufsize_ = 0;
stream->ptr_ = 0;
stream->cnt_ = 0;
stream->ops_ = 0;
stream->obj_ = 0;
stream->rwcnt_ = 0;
stream->rwlimit_ = -1;
return stream;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,287 |
tcpreplay | 6b830a1640ca20528032c89a4fdd8291a4d2d8b2 | _our_safe_strdup(const char *str, const char *funcname, const int line, const char *file)
{
char *newstr;
if ((newstr = (char *)malloc(strlen(str) + 1)) == NULL) {
fprintf(stderr, "ERROR in %s:%s() line %d: Unable to strdup() %zu bytes\n", file, funcname, line, strlen(str));
exit(-1);
}
memcpy(newstr, str, strlen(str) + 1);
return newstr;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,922 |
zziplib | 596d9dfce2624e849417d4301e8d67935608aa5e | zzip_disk_entry_fopen (ZZIP_DISK* disk, ZZIP_DISK_ENTRY* entry)
{
ZZIP_DISK_FILE* file = malloc(sizeof(ZZIP_DISK_FILE));
if (! file) return file;
file->buffer = disk->buffer;
file->endbuf = disk->endbuf;
file->header = zzip_disk_entry_to_file_header (disk, entry);
if (! file->header) { free (file); return 0; }
file->avail = zzip_file_header_usize (file->header);
if (! file->avail || zzip_file_header_data_stored (file->header))
{ file->stored = zzip_file_header_to_data (file->header); return file; }
file->stored = 0;
file->zlib.opaque = 0;
file->zlib.zalloc = Z_NULL;
file->zlib.zfree = Z_NULL;
file->zlib.avail_in = zzip_file_header_csize (file->header);
file->zlib.next_in = zzip_file_header_to_data (file->header);
if (! zzip_file_header_data_deflated (file->header) ||
inflateInit2 (& file->zlib, -MAX_WBITS) != Z_OK)
{ free (file); return 0; }
return file;
} | 1 | CVE-2018-7725 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 7,508 |
file | 93e063ee374b6a75729df9e7201fb511e47e259d | cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,855 |
ImageMagick6 | 3449a06f0122d4d9e68b4739417a3eaad0b24265 | static Image *ReadJNGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
logging,
status;
MngInfo
*mng_info;
char
magic_number[MaxTextExtent];
size_t
count;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging=LogMagickEvent(CoderEvent,GetMagickModule(),"Enter ReadJNGImage()");
image=AcquireImage(image_info);
mng_info=(MngInfo *) NULL;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (LocaleCompare(image_info->magick,"JNG") != 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/* Verify JNG signature. */
count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number);
if ((count < 8) || (memcmp(magic_number,"\213JNG\r\n\032\n",8) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Verify that file size large enough to contain a JNG datastream.
*/
if (GetBlobSize(image) < 147)
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
/* Allocate a MngInfo structure. */
mng_info=(MngInfo *) AcquireMagickMemory(sizeof(*mng_info));
if (mng_info == (MngInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
/* Initialize members of the MngInfo structure. */
(void) memset(mng_info,0,sizeof(MngInfo));
mng_info->image=image;
image=ReadOneJNGImage(mng_info,image_info,exception);
mng_info=MngInfoFreeStruct(mng_info);
if (image == (Image *) NULL)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
return((Image *) NULL);
}
(void) CloseBlob(image);
if (image->columns == 0 || image->rows == 0)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"exit ReadJNGImage() with error");
ThrowReaderException(CorruptImageError,"CorruptImage");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"exit ReadJNGImage()");
return(image);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,703 |
libsndfile | aaea680337267bfb6d2544da878890ee7f1c5077 | main (int argc, char **argv)
{ STATE state ;
SF_INFO sfinfo ;
char pathname [512], ext [32], *cptr ;
int ch, double_split ;
if (argc != 2)
{ if (argc != 1)
puts ("\nError : need a single input file.\n") ;
usage_exit () ;
} ;
memset (&state, 0, sizeof (state)) ;
memset (&sfinfo, 0, sizeof (sfinfo)) ;
if ((state.infile = sf_open (argv [1], SFM_READ, &sfinfo)) == NULL)
{ printf ("\nError : Not able to open input file '%s'\n%s\n", argv [1], sf_strerror (NULL)) ;
exit (1) ;
} ;
if (sfinfo.channels < 2)
{ printf ("\nError : Input file '%s' only has one channel.\n", argv [1]) ;
exit (1) ;
} ;
state.channels = sfinfo.channels ;
sfinfo.channels = 1 ;
if (snprintf (pathname, sizeof (pathname), "%s", argv [1]) > (int) sizeof (pathname))
{ printf ("\nError : Length of provided filename '%s' exceeds MAX_PATH (%d).\n", argv [1], (int) sizeof (pathname)) ;
exit (1) ;
} ;
if ((cptr = strrchr (pathname, '.')) == NULL)
ext [0] = 0 ;
else
{ snprintf (ext, sizeof (ext), "%s", cptr) ;
cptr [0] = 0 ;
} ;
printf ("Input file : %s\n", pathname) ;
puts ("Output files :") ;
for (ch = 0 ; ch < state.channels ; ch++)
{ char filename [520] ;
snprintf (filename, sizeof (filename), "%s_%02d%s", pathname, ch, ext) ;
if ((state.outfile [ch] = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
{ printf ("Not able to open output file '%s'\n%s\n", filename, sf_strerror (NULL)) ;
exit (1) ;
} ;
printf (" %s\n", filename) ;
} ;
switch (sfinfo.format & SF_FORMAT_SUBMASK)
{ case SF_FORMAT_FLOAT :
case SF_FORMAT_DOUBLE :
case SF_FORMAT_VORBIS :
double_split = 1 ;
break ;
default :
double_split = 0 ;
break ;
} ;
if (double_split)
deinterleave_double (&state) ;
else
deinterleave_int (&state) ;
sf_close (state.infile) ;
for (ch = 0 ; ch < MAX_CHANNELS ; ch++)
if (state.outfile [ch] != NULL)
sf_close (state.outfile [ch]) ;
return 0 ;
} /* main */ | 1 | CVE-2018-19432 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 7,339 |
linux | 2f36db71009304b3f0b95afacd8eba1f9f046b87 | int __init ecryptfs_init_kthread(void)
{
int rc = 0;
mutex_init(&ecryptfs_kthread_ctl.mux);
init_waitqueue_head(&ecryptfs_kthread_ctl.wait);
INIT_LIST_HEAD(&ecryptfs_kthread_ctl.req_list);
ecryptfs_kthread = kthread_run(&ecryptfs_threadfn, NULL,
"ecryptfs-kthread");
if (IS_ERR(ecryptfs_kthread)) {
rc = PTR_ERR(ecryptfs_kthread);
printk(KERN_ERR "%s: Failed to create kernel thread; rc = [%d]"
"\n", __func__, rc);
}
return rc;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,435 |
linux | 5d2e73a5f80a5b5aff3caf1ec6d39b5b3f54b26e | static int zr364xx_vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct zr364xx_camera *cam = video_drvdata(file);
strscpy(cap->driver, DRIVER_DESC, sizeof(cap->driver));
strscpy(cap->card, cam->udev->product, sizeof(cap->card));
strscpy(cap->bus_info, dev_name(&cam->udev->dev),
sizeof(cap->bus_info));
cap->device_caps = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_READWRITE |
V4L2_CAP_STREAMING;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
} | 1 | CVE-2019-15217 | CWE-476 | NULL Pointer Dereference | The product dereferences a pointer that it expects to be valid but is NULL. | Phase: Implementation
If all pointers that could have been modified are checked for NULL before use, nearly all NULL pointer dereferences can be prevented.
Phase: Requirements
Select a programming language that is not susceptible to these issues.
Phase: Implementation
Check the results of all functions that return a value and verify that the value is non-null before acting upon it.
Effectiveness: Moderate
Note: Checking the return value of the function will typically be sufficient, however beware of race conditions (CWE-362) in a concurrent environment. This solution does not handle the use of improperly initialized variables (CWE-665).
Phase: Architecture and Design
Identify all variables and data stores that receive information from external sources, and apply input validation to make sure that they are only initialized to expected values.
Phase: Implementation
Explicitly initialize all variables and other data stores, either during declaration or just before the first usage. | 7,307 |
univention-corporate-server | a28053045bd2e778c50ed1acaf4e52e1e34f6e34 | int data_on_connection(int fd, callback_remove_handler remove)
{
int nread;
char *network_packet;
char network_line[8192];
char *p;
unsigned long id;
char string[1024];
unsigned long msg_id = UINT32_MAX;
enum network_protocol version = network_client_get_version(fd);
ioctl(fd, FIONREAD, &nread);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "new connection data = %d\n",nread);
if(nread == 0)
{
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "%d failed, got 0 close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
network_client_dump ();
return 0;
}
if ( nread >= 8192 ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, more than 8192 close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
}
/* read the whole package */
network_packet=malloc((nread+1) * sizeof(char));
read(fd, network_packet, nread);
network_packet[nread]='\0';
memset(network_line, 0, 8192);
p=network_packet;
p_sem(sem_id);
while ( get_network_line(p, network_line) ) {
if ( strlen(network_line) > 0 ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "line = [%s]",network_line);
}
if ( !strncmp(network_line, "MSGID: ", strlen("MSGID: ")) ) {
/* read message id */
msg_id=strtoul(&(network_line[strlen("MSGID: ")]), NULL, 10);
p+=strlen(network_line);
} else if ( !strncmp(network_line, "Version: ", strlen("Version: ")) ) {
char *head = network_line, *end;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: VERSION");
version = strtoul(head + 9, &end, 10);
if (!head[9] || *end)
goto failed;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "VERSION=%d", version);
if (version < network_procotol_version) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Forbidden VERSION=%d < %d, close connection to listener", version, network_procotol_version);
goto close;
} else if (version >= PROTOCOL_LAST) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Future VERSION=%d", version);
version = PROTOCOL_LAST - 1;
}
network_client_set_version(fd, version);
/* reset message id */
msg_id = UINT32_MAX;
p+=strlen(network_line);
} else if ( !strncmp(network_line, "Capabilities: ", strlen("Capabilities: ")) ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: Capabilities");
if ( version > PROTOCOL_UNKNOWN ) {
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "Version: %d\nCapabilities: \n\n", version);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "SEND: %s", string);
write(fd, string, strlen(string));
} else {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "Capabilities recv, but no version line");
}
p+=strlen(network_line);
} else if ( !strncmp(network_line, "GET_DN ", strlen("GET_DN ")) && msg_id != UINT32_MAX && version > PROTOCOL_UNKNOWN && version < PROTOCOL_3) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_DN");
id=strtoul(&(network_line[strlen("GET_DN ")]), NULL, 10);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld",id);
if ( id <= notify_last_id.id) {
char *dn_string = NULL;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "try to read %ld from cache", id);
/* try to read from cache */
if ( (dn_string = notifier_cache_get(id)) == NULL ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld not found in cache", id);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld get one dn", id);
/* read from transaction file, because not in cache */
if( (dn_string=notify_transcation_get_one_dn ( id )) == NULL ) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "%ld failed ", id);
/* TODO: maybe close connection? */
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "%d failed, close connection to listener ", fd);
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
}
}
if ( dn_string != NULL ) {
snprintf(string, sizeof(string), "MSGID: %ld\n%s\n\n",msg_id,dn_string);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string);
write(fd, string, strlen(string));
free(dn_string);
}
} else {
/* set wanted id */
network_client_set_next_id(fd, id);
network_client_set_msg_id(fd, msg_id);
}
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if (!strncmp(p, "WAIT_ID ", 8) && msg_id != UINT32_MAX && version >= PROTOCOL_3) {
char *head = network_line, *end;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: WAIT_ID");
id = strtoul(head + 8, &end, 10);
if (!head[8] || *end)
goto failed;
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "id: %ld", id);
if (id <= notify_last_id.id) {
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n", msg_id, notify_last_id.id);
write(fd, string, strlen(string));
} else {
/* set wanted id */
network_client_set_next_id(fd, id);
network_client_set_msg_id(fd, msg_id);
}
p += strlen(network_line) + 1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "GET_ID", strlen("GET_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_ID");
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,notify_last_id.id);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "GET_SCHEMA_ID", strlen("GET_SCHEMA_ID")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: GET_SCHEMA_ID");
memset(string, 0, sizeof(string));
snprintf(string, sizeof(string), "MSGID: %ld\n%ld\n\n",msg_id,SCHEMA_ID);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "--> %d: [%s]",fd, string);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else if ( !strncmp(network_line, "ALIVE", strlen("ALIVE")) && msg_id != UINT32_MAX && network_client_get_version(fd) > 0) {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "RECV: ALIVE");
snprintf(string, sizeof(string), "MSGID: %ld\nOKAY\n\n",msg_id);
write(fd, string, strlen(string));
p+=strlen(network_line)+1;
msg_id = UINT32_MAX;
} else {
p+=strlen(network_line);
if (strlen(network_line) == 0 ) {
p+=1;
} else {
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ERROR, "Drop package [%s]", network_line);
}
}
}
v_sem(sem_id);
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_ALL, "END Package");
network_client_dump ();
return 0;
failed:
univention_debug(UV_DEBUG_TRANSFILE, UV_DEBUG_PROCESS, "Failed parsing [%s]", p);
close:
close(fd);
FD_CLR(fd, &readfds);
remove(fd);
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 23,502 |
Chrome | 56a84aa67bb071a33a48ac1481b555c48e0a9a59 | bool IsBlockedNavigation(net::Error error_code) {
switch (error_code) {
case net::ERR_BLOCKED_BY_CLIENT:
case net::ERR_BLOCKED_BY_RESPONSE:
case net::ERR_BLOCKED_BY_XSS_AUDITOR:
case net::ERR_UNSAFE_REDIRECT:
return true;
default:
return false;
}
}
| 1 | CVE-2017-15420 | CWE-20 | Improper Input Validation | The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. |
Phase: Architecture and Design
Strategy: Attack Surface Reduction
Consider using language-theoretic security (LangSec) techniques that characterize inputs using a formal language and build "recognizers" for that language. This effectively requires parsing to be a distinct layer that effectively enforces a boundary between raw input and internal data representations, instead of allowing parser code to be scattered throughout the program, where it could be subject to errors or inconsistencies that create weaknesses. [REF-1109] [REF-1110] [REF-1111]
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use an input validation framework such as Struts or the OWASP ESAPI Validation API. Note that using a framework does not automatically address all input validation problems; be mindful of weaknesses that could arise from misusing the framework itself (CWE-1173).
Phases: Architecture and Design; Implementation
Strategy: Attack Surface Reduction
Understand all the potential areas where untrusted inputs can enter your software: parameters or arguments, cookies, anything read from the network, environment variables, reverse DNS lookups, query results, request headers, URL components, e-mail, files, filenames, databases, and any external systems that provide data to the application. Remember that such inputs may be obtained indirectly through API calls.
Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
Effectiveness: High
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Even though client-side checks provide minimal benefits with respect to server-side security, they are still useful. First, they can support intrusion detection. If the server receives input that should have been rejected by the client, then it may be an indication of an attack. Second, client-side error-checking can provide helpful feedback to the user about the expectations for valid input. Third, there may be a reduction in server-side processing time for accidental input errors, although this is typically a small savings.
Phase: Implementation
When your application combines data from multiple sources, perform the validation after the sources have been combined. The individual data elements may pass the validation step but violate the intended restrictions after they have been combined.
Phase: Implementation
Be especially careful to validate all input when invoking code that crosses language boundaries, such as from an interpreted language to native code. This could create an unexpected interaction between the language boundaries. Ensure that you are not violating any of the expectations of the language with which you are interfacing. For example, even though Java may not be susceptible to buffer overflows, providing a large argument in a call to native code might trigger an overflow.
Phase: Implementation
Directly convert your input type into the expected data type, such as using a conversion function that translates a string into a number. After converting to the expected data type, ensure that the input's values fall within the expected range of allowable values and that multi-field consistencies are maintained.
Phase: Implementation
Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180, CWE-181). Make sure that your application does not inadvertently decode the same input twice (CWE-174). Such errors could be used to bypass allowlist schemes by introducing dangerous inputs after they have been checked. Use libraries such as the OWASP ESAPI Canonicalization control.
Consider performing repeated canonicalization until your input does not change any more. This will avoid double-decoding and similar scenarios, but it might inadvertently modify inputs that are allowed to contain properly-encoded dangerous content.
Phase: Implementation
When exchanging data between components, ensure that both components are using the same character encoding. Ensure that the proper encoding is applied at each interface. Explicitly set the encoding you are using whenever the protocol allows you to do so. | 8,933 |
leptonica | 3c18c43b6a3f753f0dfff99610d46ad46b8bfac4 | pixFillMapHoles(PIX *pix,
l_int32 nx,
l_int32 ny,
l_int32 filltype)
{
l_int32 w, h, y, nmiss, goodcol, i, j, found, ival, valtest;
l_uint32 val, lastval;
NUMA *na; /* indicates if there is any data in the column */
PIX *pixt;
PROCNAME("pixFillMapHoles");
if (!pix || pixGetDepth(pix) != 8)
return ERROR_INT("pix not defined or not 8 bpp", procName, 1);
if (pixGetColormap(pix))
return ERROR_INT("pix is colormapped", procName, 1);
/* ------------- Fill holes in the mapping image columns ----------- */
pixGetDimensions(pix, &w, &h, NULL);
na = numaCreate(0); /* holds flag for which columns have data */
nmiss = 0;
valtest = (filltype == L_FILL_WHITE) ? 255 : 0;
for (j = 0; j < nx; j++) { /* do it by columns */
found = FALSE;
for (i = 0; i < ny; i++) {
pixGetPixel(pix, j, i, &val);
if (val != valtest) {
y = i;
found = TRUE;
break;
}
}
if (found == FALSE) {
numaAddNumber(na, 0); /* no data in the column */
nmiss++;
}
else {
numaAddNumber(na, 1); /* data in the column */
for (i = y - 1; i >= 0; i--) /* replicate upwards to top */
pixSetPixel(pix, j, i, val);
pixGetPixel(pix, j, 0, &lastval);
for (i = 1; i < h; i++) { /* set going down to bottom */
pixGetPixel(pix, j, i, &val);
if (val == valtest)
pixSetPixel(pix, j, i, lastval);
else
lastval = val;
}
}
}
numaAddNumber(na, 0); /* last column */
if (nmiss == nx) { /* no data in any column! */
numaDestroy(&na);
L_WARNING("no bg found; no data in any column\n", procName);
return 1;
}
/* ---------- Fill in missing columns by replication ----------- */
if (nmiss > 0) { /* replicate columns */
pixt = pixCopy(NULL, pix);
/* Find the first good column */
goodcol = 0;
for (j = 0; j < w; j++) {
numaGetIValue(na, j, &ival);
if (ival == 1) {
goodcol = j;
break;
}
}
if (goodcol > 0) { /* copy cols backward */
for (j = goodcol - 1; j >= 0; j--) {
pixRasterop(pix, j, 0, 1, h, PIX_SRC, pixt, j + 1, 0);
pixRasterop(pixt, j, 0, 1, h, PIX_SRC, pix, j, 0);
}
}
for (j = goodcol + 1; j < w; j++) { /* copy cols forward */
numaGetIValue(na, j, &ival);
if (ival == 0) {
/* Copy the column to the left of j */
pixRasterop(pix, j, 0, 1, h, PIX_SRC, pixt, j - 1, 0);
pixRasterop(pixt, j, 0, 1, h, PIX_SRC, pix, j, 0);
}
}
pixDestroy(&pixt);
}
if (w > nx) { /* replicate the last column */
for (i = 0; i < h; i++) {
pixGetPixel(pix, w - 2, i, &val);
pixSetPixel(pix, w - 1, i, val);
}
}
numaDestroy(&na);
return 0;
} | 1 | CVE-2020-36279 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 5,677 |
Chrome | 70bcb6b3396a395e871e10b2ff883d92b8218e9f | void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN || !m_imageResource->hasImage())
return;
FloatRect boundingBox = repaintRectInLocalCoordinates();
if (!SVGRenderSupport::paintInfoIntersectsRepaintRect(boundingBox, m_localTransform, paintInfo))
return;
PaintInfo childPaintInfo(paintInfo);
bool drawsOutline = style()->outlineWidth() && (childPaintInfo.phase == PaintPhaseOutline || childPaintInfo.phase == PaintPhaseSelfOutline);
if (drawsOutline || childPaintInfo.phase == PaintPhaseForeground) {
GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
childPaintInfo.applyTransform(m_localTransform);
if (childPaintInfo.phase == PaintPhaseForeground) {
SVGRenderingContext renderingContext(this, childPaintInfo);
if (renderingContext.isRenderingPrepared()) {
if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
return;
paintForeground(childPaintInfo);
}
}
if (drawsOutline)
paintOutline(childPaintInfo, IntRect(boundingBox));
}
}
| 1 | CVE-2013-6649 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 2,754 |
xserver | d2f813f7db157fc83abc4b3726821c36ee7e40b1 | fbStore_a1 (FbBits *bits, const CARD32 *values, int x, int width, miIndexedPtr indexed)
{
int i;
for (i = 0; i < width; ++i) {
CARD32 *pixel = ((CARD32 *) bits) + ((i+x) >> 5);
CARD32 mask = FbStipMask((i+x) & 0x1f, 1);
CARD32 v = READ(values + i) & 0x80000000 ? mask : 0;
WRITE(pixel, (READ(pixel) & ~mask) | v);
}
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 11,104 |
xterm-snapshots | 82ba55b8f994ab30ff561a347b82ea340ba7075c | InterpretButton(XtermWidget xw, XButtonEvent *event)
{
Bool result = False;
if (ShiftOverride(xw, event->state, (int) event->button)) {
TRACE(("...shift-button #%d overrides mouse-protocol\n", event->button));
result = True;
}
return result;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,249 |
pango | 797d46714d27f147277fdd5346648d838c68fb8c | hb_ot_layout_build_glyph_classes (hb_face_t *face,
uint16_t num_total_glyphs,
hb_codepoint_t *glyphs,
unsigned char *klasses,
uint16_t count)
{
if (HB_OBJECT_IS_INERT (face))
return;
hb_ot_layout_t *layout = &face->ot_layout;
if (HB_UNLIKELY (!count || !glyphs || !klasses))
return;
if (layout->new_gdef.len == 0) {
layout->new_gdef.klasses = (unsigned char *) calloc (num_total_glyphs, sizeof (unsigned char));
layout->new_gdef.len = count;
}
for (unsigned int i = 0; i < count; i++)
_hb_ot_layout_set_glyph_class (face, glyphs[i], (hb_ot_layout_glyph_class_t) klasses[i]);
} | 1 | CVE-2010-0421 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 6,547 |
openssl | af58be768ebb690f78530f796e92b8ae5c9a4401 | void RECORD_LAYER_init(RECORD_LAYER *rl, SSL *s)
{
rl->s = s;
RECORD_LAYER_set_first_record(&s->rlayer);
SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,993 |
util-linux | 1c9143d0c1f979c3daf10e1c37b5b1e916c22a1c | static void get_sem_elements(struct sem_data *p)
{
size_t i;
if (!p || !p->sem_nsems || p->sem_perm.id < 0)
return;
p->elements = xcalloc(p->sem_nsems, sizeof(struct sem_elem));
for (i = 0; i < p->sem_nsems; i++) {
struct sem_elem *e = &p->elements[i];
union semun arg = { .val = 0 };
e->semval = semctl(p->sem_perm.id, i, GETVAL, arg);
if (e->semval < 0)
err(EXIT_FAILURE, _("%s failed"), "semctl(GETVAL)");
e->ncount = semctl(p->sem_perm.id, i, GETNCNT, arg);
if (e->ncount < 0)
err(EXIT_FAILURE, _("%s failed"), "semctl(GETNCNT)");
e->zcount = semctl(p->sem_perm.id, i, GETZCNT, arg);
if (e->zcount < 0)
err(EXIT_FAILURE, _("%s failed"), "semctl(GETZCNT)");
e->pid = semctl(p->sem_perm.id, i, GETPID, arg);
if (e->pid < 0)
err(EXIT_FAILURE, _("%s failed"), "semctl(GETPID)");
}
} | 1 | CVE-2021-37600 | CWE-190 | Integer Overflow or Wraparound | The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value. This occurs when an integer value is incremented to a value that is too large to store in the associated representation. When this occurs, the value may become a very small or negative number. | Phase: Requirements
Ensure that all protocols are strictly defined, such that all out-of-bounds behavior can be identified simply, and require strict conformance to the protocol.
Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
If possible, choose a language or compiler that performs automatic bounds checking.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Use libraries or frameworks that make it easier to handle numbers without unexpected consequences.
Examples include safe integer handling packages such as SafeInt (C++) or IntegerLib (C or C++). [REF-106]
Phase: Implementation
Strategy: Input Validation
Perform input validation on any numeric input by ensuring that it is within the expected range. Enforce that the input meets both the minimum and maximum requirements for the expected range.
Use unsigned integers where possible. This makes it easier to perform validation for integer overflows. When signed integers are required, ensure that the range check includes minimum values as well as maximum values.
Phase: Implementation
Understand the programming language's underlying representation and how it interacts with numeric calculation (CWE-681). Pay close attention to byte size discrepancies, precision, signed/unsigned distinctions, truncation, conversion and casting between types, "not-a-number" calculations, and how the language handles numbers that are too large or too small for its underlying representation. [REF-7]
Also be careful to account for 32-bit, 64-bit, and other potential differences that may affect the numeric representation.
Phase: Architecture and Design
For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Phase: Implementation
Strategy: Compilation or Build Hardening
Examine compiler warnings closely and eliminate problems with potential security implications, such as signed / unsigned mismatch in memory operations, or use of uninitialized variables. Even if the weakness is rarely exploitable, a single failure may lead to the compromise of the entire system. | 6,856 |
openssl | 259b664f950c2ba66fbf4b0fe5281327904ead21 | SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username)
{
int i;
SRP_user_pwd *user;
unsigned char digv[SHA_DIGEST_LENGTH];
unsigned char digs[SHA_DIGEST_LENGTH];
EVP_MD_CTX ctxt;
if (vb == NULL)
return NULL;
for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) {
user = sk_SRP_user_pwd_value(vb->users_pwd, i);
if (strcmp(user->id, username) == 0)
return user;
}
if ((vb->seed_key == NULL) ||
(vb->default_g == NULL) || (vb->default_N == NULL))
return NULL;
if (!(len = t_fromb64(tmp, N)))
goto err;
N_bn = BN_bin2bn(tmp, len, NULL);
if (!(len = t_fromb64(tmp, g)))
goto err;
g_bn = BN_bin2bn(tmp, len, NULL);
defgNid = "*";
} else {
SRP_gN *gN = SRP_get_gN_by_id(g, NULL);
if (gN == NULL)
goto err;
N_bn = gN->N;
g_bn = gN->g;
defgNid = gN->id;
}
| 1 | CVE-2016-0798 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 3,558 |
wget | 692d5c5215de0db482c252492a92fc424cc6a97c | do_conversion (const char *tocode, const char *fromcode, char const *in_org, size_t inlen, char **out)
{
iconv_t cd;
/* sXXXav : hummm hard to guess... */
size_t len, done, outlen;
int invalid = 0, tooshort = 0;
char *s, *in, *in_save;
cd = iconv_open (tocode, fromcode);
if (cd == (iconv_t)(-1))
{
logprintf (LOG_VERBOSE, _("Conversion from %s to %s isn't supported\n"),
quote (fromcode), quote (tocode));
*out = NULL;
return false;
}
/* iconv() has to work on an unescaped string */
in_save = in = xstrndup (in_org, inlen);
url_unescape_except_reserved (in);
inlen = strlen(in);
len = outlen = inlen * 2;
*out = s = xmalloc (outlen + 1);
done = 0;
for (;;)
{
if (iconv (cd, (ICONV_CONST char **) &in, &inlen, out, &outlen) != (size_t)(-1) &&
iconv (cd, NULL, NULL, out, &outlen) != (size_t)(-1))
{
*out = s;
*(s + len - outlen - done) = '\0';
xfree(in_save);
iconv_close(cd);
IF_DEBUG
{
/* not not print out embedded passwords, in_org might be an URL */
if (!strchr(in_org, '@') && !strchr(*out, '@'))
debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode);
else
debug_logprintf ("logging suppressed, strings may contain password\n");
}
return true;
}
/* Incomplete or invalid multibyte sequence */
if (errno == EINVAL || errno == EILSEQ)
{
if (!invalid)
logprintf (LOG_VERBOSE,
_("Incomplete or invalid multibyte sequence encountered\n"));
invalid++;
**out = *in;
in++;
inlen--;
(*out)++;
outlen--;
}
else if (errno == E2BIG) /* Output buffer full */
{
tooshort++;
done = len;
len = outlen = done + inlen * 2;
s = xrealloc (s, outlen + 1);
*out = s + done;
}
else /* Weird, we got an unspecified error */
{
logprintf (LOG_VERBOSE, _("Unhandled errno %d\n"), errno);
break;
}
}
xfree(in_save);
iconv_close(cd);
IF_DEBUG
{
/* not not print out embedded passwords, in_org might be an URL */
if (!strchr(in_org, '@') && !strchr(*out, '@'))
debug_logprintf ("converted '%s' (%s) -> '%s' (%s)\n", in_org, fromcode, *out, tocode);
else
debug_logprintf ("logging suppressed, strings may contain password\n");
}
return false;
} | 1 | CVE-2019-5953 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 58 |
linux | df7e40425813c50cd252e6f5e348a81ef1acae56 | static int hns_roce_query_pkey(struct ib_device *ib_dev, u8 port, u16 index,
u16 *pkey)
{
*pkey = PKEY_ID;
return 0;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 19,584 |
openexr | db217f29dfb24f6b4b5100c24ac5e7490e1c57d0 | readSampleCountForLineBlock(InputStreamMutex* streamData,
DeepScanLineInputFile::Data* data,
int lineBlockId)
{
streamData->is->seekg(data->lineOffsets[lineBlockId]);
if (isMultiPart(data->version))
{
int partNumber;
OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, partNumber);
if (partNumber != data->partNumber)
throw IEX_NAMESPACE::ArgExc("Unexpected part number.");
}
int minY;
OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, minY);
//
// Check the correctness of minY.
//
if (minY != data->minY + lineBlockId * data->linesInBuffer)
throw IEX_NAMESPACE::ArgExc("Unexpected data block y coordinate.");
int maxY;
maxY = min(minY + data->linesInBuffer - 1, data->maxY);
uint64_t sampleCountTableDataSize;
OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, sampleCountTableDataSize);
if(sampleCountTableDataSize>static_cast<uint64_t>(data->maxSampleCountTableSize))
{
THROW (IEX_NAMESPACE::ArgExc, "Bad sampleCountTableDataSize read from chunk "<< lineBlockId << ": expected " << data->maxSampleCountTableSize << " or less, got "<< sampleCountTableDataSize);
}
uint64_t packedDataSize;
uint64_t unpackedDataSize;
OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, packedDataSize);
OPENEXR_IMF_INTERNAL_NAMESPACE::Xdr::read <OPENEXR_IMF_INTERNAL_NAMESPACE::StreamIO> (*streamData->is, unpackedDataSize);
//
// We make a check on the data size requirements here.
// Whilst we wish to store 64bit sizes on disk, not all the compressors
// have been made to work with such data sizes and are still limited to
// using signed 32 bit (int) for the data size. As such, this version
// insists that we validate that the data size does not exceed the data
// type max limit.
// @TODO refactor the compressor code to ensure full 64-bit support.
//
int compressorMaxDataSize = std::numeric_limits<int>::max();
if (sampleCountTableDataSize > uint64_t(compressorMaxDataSize))
{
THROW (IEX_NAMESPACE::ArgExc, "This version of the library does not "
<< "support the allocation of data with size > "
<< compressorMaxDataSize
<< " file table size :" << sampleCountTableDataSize << ".\n");
}
streamData->is->read(data->sampleCountTableBuffer, static_cast<int>(sampleCountTableDataSize));
const char* readPtr;
//
// If the sample count table is compressed, we'll uncompress it.
//
if (sampleCountTableDataSize < static_cast<uint64_t>(data->maxSampleCountTableSize))
{
if(!data->sampleCountTableComp)
{
THROW(IEX_NAMESPACE::ArgExc,"Deep scanline data corrupt at chunk " << lineBlockId << " (sampleCountTableDataSize error)");
}
data->sampleCountTableComp->uncompress(data->sampleCountTableBuffer,
static_cast<int>(sampleCountTableDataSize),
minY,
readPtr);
}
else readPtr = data->sampleCountTableBuffer;
char* base = data->sampleCountSliceBase;
int xStride = data->sampleCountXStride;
int yStride = data->sampleCountYStride;
// total number of samples in block: used to check samplecount table doesn't
// reference more data than exists
size_t cumulative_total_samples=0;
for (int y = minY; y <= maxY; y++)
{
int yInDataWindow = y - data->minY;
data->lineSampleCount[yInDataWindow] = 0;
int lastAccumulatedCount = 0;
for (int x = data->minX; x <= data->maxX; x++)
{
int accumulatedCount, count;
//
// Read the sample count for pixel (x, y).
//
Xdr::read <CharPtrIO> (readPtr, accumulatedCount);
// sample count table should always contain monotonically
// increasing values.
if (accumulatedCount < lastAccumulatedCount)
{
THROW(IEX_NAMESPACE::ArgExc,"Deep scanline sampleCount data corrupt at chunk " << lineBlockId << " (negative sample count detected)");
}
count = accumulatedCount - lastAccumulatedCount;
lastAccumulatedCount = accumulatedCount;
//
// Store the data in both internal and external data structure.
//
data->sampleCount[yInDataWindow][x - data->minX] = count;
data->lineSampleCount[yInDataWindow] += count;
sampleCount(base, xStride, yStride, x, y) = count;
}
cumulative_total_samples+=data->lineSampleCount[yInDataWindow];
if(cumulative_total_samples*data->combinedSampleSize > unpackedDataSize)
{
THROW(IEX_NAMESPACE::ArgExc,"Deep scanline sampleCount data corrupt at chunk " << lineBlockId << ": pixel data only contains " << unpackedDataSize
<< " bytes of data but table references at least " << cumulative_total_samples*data->combinedSampleSize << " bytes of sample data" );
}
data->gotSampleCount[y - data->minY] = true;
}
} | 1 | CVE-2021-45942 | CWE-787 | Out-of-bounds Write | The product writes data past the end, or before the beginning, of the intended buffer. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333].
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 1,621 |
Chrome | f5ef337d8fffd10ab327069467ccaedb843cf9db | MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
| 1 | CVE-2018-18340 | CWE-119 | Improper Restriction of Operations within the Bounds of a Memory Buffer | The product performs operations on a memory buffer, but it reads from or writes to a memory location outside the buffer's intended boundary. This may result in read or write operations on unexpected memory locations that could be linked to other variables, data structures, or internal program data. | Phase: Requirements
Strategy: Language Selection
Use a language that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
For example, many languages that perform their own memory management, such as Java and Perl, are not subject to buffer overflows. Other languages, such as Ada and C#, typically provide overflow protection, but the protection can be disabled by the programmer.
Be wary that a language's interface to native code may still be subject to overflows, even if the language itself is theoretically safe.
Phase: Architecture and Design
Strategy: Libraries or Frameworks
Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.
Examples include the Safe C String Library (SafeStr) by Messier and Viega [REF-57], and the Strsafe.h library from Microsoft [REF-56]. These libraries provide safer versions of overflow-prone string-handling functions.
Note: This is not a complete solution, since many buffer overflows are not related to strings.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Use automatic buffer overflow detection mechanisms that are offered by certain compilers or compiler extensions. Examples include: the Microsoft Visual Studio /GS flag, Fedora/Red Hat FORTIFY_SOURCE GCC flag, StackGuard, and ProPolice, which provide various mechanisms including canary-based detection and range/index checking.
D3-SFCV (Stack Frame Canary Validation) from D3FEND [REF-1334] discusses canary-based detection in detail.
Effectiveness: Defense in Depth
Note:
This is not necessarily a complete solution, since these mechanisms only detect certain types of overflows. In addition, the result is still a denial of service, since the typical response is to exit the application.
Phase: Implementation
Consider adhering to the following rules when allocating and managing an application's memory:
Double check that the buffer is as large as specified.
When using functions that accept a number of bytes to copy, such as strncpy(), be aware that if the destination buffer size is equal to the source buffer size, it may not NULL-terminate the string.
Check buffer boundaries if accessing the buffer in a loop and make sure there is no danger of writing past the allocated space.
If necessary, truncate all input strings to a reasonable length before passing them to the copy and concatenation functions.
Phases: Operation; Build and Compilation
Strategy: Environment Hardening
Run or compile the software using features or extensions that randomly arrange the positions of a program's executable and libraries in memory. Because this makes the addresses unpredictable, it can prevent an attacker from reliably jumping to exploitable code.
Examples include Address Space Layout Randomization (ASLR) [REF-58] [REF-60] and Position-Independent Executables (PIE) [REF-64]. Imported modules may be similarly realigned if their default memory addresses conflict with other modules, in a process known as "rebasing" (for Windows) and "prelinking" (for Linux) [REF-1332] using randomly generated addresses. ASLR for libraries cannot be used in conjunction with prelink since it would require relocating the libraries at run-time, defeating the whole purpose of prelinking.
For more information on these techniques see D3-SAOR (Segment Address Offset Randomization) from D3FEND [REF-1335].
Effectiveness: Defense in Depth
Note: These techniques do not provide a complete solution. For instance, exploits frequently use a bug that discloses memory addresses in order to maximize reliability of code execution [REF-1337]. It has also been shown that a side-channel attack can bypass ASLR [REF-1333]
Phase: Operation
Strategy: Environment Hardening
Use a CPU and operating system that offers Data Execution Protection (using hardware NX or XD bits) or the equivalent techniques that simulate this feature in software, such as PaX [REF-60] [REF-61]. These techniques ensure that any instruction executed is exclusively at a memory address that is part of the code segment.
For more information on these techniques see D3-PSEP (Process Segment Execution Prevention) from D3FEND [REF-1336].
Effectiveness: Defense in Depth
Note: This is not a complete solution, since buffer overflows could be used to overwrite nearby variables to modify the software's state in dangerous ways. In addition, it cannot be used in cases in which self-modifying code is required. Finally, an attack could still cause a denial of service, since the typical response is to exit the application.
Phase: Implementation
Replace unbounded copy functions with analogous functions that support length arguments, such as strcpy with strncpy. Create these if they are not available.
Effectiveness: Moderate
Note: This approach is still susceptible to calculation errors, including issues such as off-by-one errors (CWE-193) and incorrectly calculating buffer lengths (CWE-131). | 7,292 |
linux | a8b0ca17b80e92faab46ee7179ba9e99ccb61233 | int __kprobes do_page_fault(struct pt_regs *regs, unsigned long address,
unsigned long error_code)
{
struct vm_area_struct * vma;
struct mm_struct *mm = current->mm;
siginfo_t info;
int code = SEGV_MAPERR;
int is_write = 0, ret;
int trap = TRAP(regs);
int is_exec = trap == 0x400;
#if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE))
/*
* Fortunately the bit assignments in SRR1 for an instruction
* fault and DSISR for a data fault are mostly the same for the
* bits we are interested in. But there are some bits which
* indicate errors in DSISR but can validly be set in SRR1.
*/
if (trap == 0x400)
error_code &= 0x48200000;
else
is_write = error_code & DSISR_ISSTORE;
#else
is_write = error_code & ESR_DST;
#endif /* CONFIG_4xx || CONFIG_BOOKE */
if (notify_page_fault(regs))
return 0;
if (unlikely(debugger_fault_handler(regs)))
return 0;
/* On a kernel SLB miss we can only check for a valid exception entry */
if (!user_mode(regs) && (address >= TASK_SIZE))
return SIGSEGV;
#if !(defined(CONFIG_4xx) || defined(CONFIG_BOOKE) || \
defined(CONFIG_PPC_BOOK3S_64))
if (error_code & DSISR_DABRMATCH) {
/* DABR match */
do_dabr(regs, address, error_code);
return 0;
}
#endif
if (in_atomic() || mm == NULL) {
if (!user_mode(regs))
return SIGSEGV;
/* in_atomic() in user mode is really bad,
as is current->mm == NULL. */
printk(KERN_EMERG "Page fault in user mode with "
"in_atomic() = %d mm = %p\n", in_atomic(), mm);
printk(KERN_EMERG "NIP = %lx MSR = %lx\n",
regs->nip, regs->msr);
die("Weird page fault", regs, SIGSEGV);
}
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
/* When running in the kernel we expect faults to occur only to
* addresses in user space. All other faults represent errors in the
* kernel and should generate an OOPS. Unfortunately, in the case of an
* erroneous fault occurring in a code path which already holds mmap_sem
* we will deadlock attempting to validate the fault against the
* address space. Luckily the kernel only validly references user
* space from well defined areas of code, which are listed in the
* exceptions table.
*
* As the vast majority of faults will be valid we will only perform
* the source reference check when there is a possibility of a deadlock.
* Attempt to lock the address space, if we cannot we then validate the
* source. If this is invalid we can skip the address space check,
* thus avoiding the deadlock.
*/
if (!down_read_trylock(&mm->mmap_sem)) {
if (!user_mode(regs) && !search_exception_tables(regs->nip))
goto bad_area_nosemaphore;
down_read(&mm->mmap_sem);
}
vma = find_vma(mm, address);
if (!vma)
goto bad_area;
if (vma->vm_start <= address)
goto good_area;
if (!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
/*
* N.B. The POWER/Open ABI allows programs to access up to
* 288 bytes below the stack pointer.
* The kernel signal delivery code writes up to about 1.5kB
* below the stack pointer (r1) before decrementing it.
* The exec code can write slightly over 640kB to the stack
* before setting the user r1. Thus we allow the stack to
* expand to 1MB without further checks.
*/
if (address + 0x100000 < vma->vm_end) {
/* get user regs even if this fault is in kernel mode */
struct pt_regs *uregs = current->thread.regs;
if (uregs == NULL)
goto bad_area;
/*
* A user-mode access to an address a long way below
* the stack pointer is only valid if the instruction
* is one which would update the stack pointer to the
* address accessed if the instruction completed,
* i.e. either stwu rs,n(r1) or stwux rs,r1,rb
* (or the byte, halfword, float or double forms).
*
* If we don't check this then any write to the area
* between the last mapped region and the stack will
* expand the stack rather than segfaulting.
*/
if (address + 2048 < uregs->gpr[1]
&& (!user_mode(regs) || !store_updates_sp(regs)))
goto bad_area;
}
if (expand_stack(vma, address))
goto bad_area;
good_area:
code = SEGV_ACCERR;
#if defined(CONFIG_6xx)
if (error_code & 0x95700000)
/* an error such as lwarx to I/O controller space,
address matching DABR, eciwx, etc. */
goto bad_area;
#endif /* CONFIG_6xx */
#if defined(CONFIG_8xx)
/* 8xx sometimes need to load a invalid/non-present TLBs.
* These must be invalidated separately as linux mm don't.
*/
if (error_code & 0x40000000) /* no translation? */
_tlbil_va(address, 0, 0, 0);
/* The MPC8xx seems to always set 0x80000000, which is
* "undefined". Of those that can be set, this is the only
* one which seems bad.
*/
if (error_code & 0x10000000)
/* Guarded storage error. */
goto bad_area;
#endif /* CONFIG_8xx */
if (is_exec) {
#ifdef CONFIG_PPC_STD_MMU
/* Protection fault on exec go straight to failure on
* Hash based MMUs as they either don't support per-page
* execute permission, or if they do, it's handled already
* at the hash level. This test would probably have to
* be removed if we change the way this works to make hash
* processors use the same I/D cache coherency mechanism
* as embedded.
*/
if (error_code & DSISR_PROTFAULT)
goto bad_area;
#endif /* CONFIG_PPC_STD_MMU */
/*
* Allow execution from readable areas if the MMU does not
* provide separate controls over reading and executing.
*
* Note: That code used to not be enabled for 4xx/BookE.
* It is now as I/D cache coherency for these is done at
* set_pte_at() time and I see no reason why the test
* below wouldn't be valid on those processors. This -may-
* break programs compiled with a really old ABI though.
*/
if (!(vma->vm_flags & VM_EXEC) &&
(cpu_has_feature(CPU_FTR_NOEXECUTE) ||
!(vma->vm_flags & (VM_READ | VM_WRITE))))
goto bad_area;
/* a write */
} else if (is_write) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
/* a read */
} else {
/* protection fault */
if (error_code & 0x08000000)
goto bad_area;
if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
goto bad_area;
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
ret = handle_mm_fault(mm, vma, address, is_write ? FAULT_FLAG_WRITE : 0);
if (unlikely(ret & VM_FAULT_ERROR)) {
if (ret & VM_FAULT_OOM)
goto out_of_memory;
else if (ret & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (ret & VM_FAULT_MAJOR) {
current->maj_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, 0,
regs, address);
#ifdef CONFIG_PPC_SMLPAR
if (firmware_has_feature(FW_FEATURE_CMO)) {
preempt_disable();
get_lppaca()->page_ins += (1 << PAGE_FACTOR);
preempt_enable();
}
#endif
} else {
current->min_flt++;
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, 0,
regs, address);
}
up_read(&mm->mmap_sem);
return 0;
bad_area:
up_read(&mm->mmap_sem);
bad_area_nosemaphore:
/* User mode accesses cause a SIGSEGV */
if (user_mode(regs)) {
_exception(SIGSEGV, regs, code, address);
return 0;
}
if (is_exec && (error_code & DSISR_PROTFAULT)
&& printk_ratelimit())
printk(KERN_CRIT "kernel tried to execute NX-protected"
" page (%lx) - exploit attempt? (uid: %d)\n",
address, current_uid());
return SIGSEGV;
/*
* We ran out of memory, or some other thing happened to us that made
* us unable to handle the page fault gracefully.
*/
out_of_memory:
up_read(&mm->mmap_sem);
if (!user_mode(regs))
return SIGKILL;
pagefault_out_of_memory();
return 0;
do_sigbus:
up_read(&mm->mmap_sem);
if (user_mode(regs)) {
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void __user *)address;
force_sig_info(SIGBUS, &info, current);
return 0;
}
return SIGBUS;
}
| 1 | CVE-2011-2918 | CWE-399 | Resource Management Errors | Weaknesses in this category are related to improper management of system resources. | Not Found in CWE Page | 7,546 |
openssl | 746c6f3a533b1eb50b909147b35fa1b0e5c61f59 | static void sha1_update(SHA_CTX *c,const void *data,size_t len)
{ const unsigned char *ptr = data;
size_t res;
if ((res = c->num)) {
res = SHA_CBLOCK-res;
if (len<res) res=len;
SHA1_Update (c,ptr,res);
ptr += res;
len -= res;
}
res = len % SHA_CBLOCK;
len -= res;
if (len) {
sha1_block_data_order(c,ptr,len/SHA_CBLOCK);
ptr += len;
c->Nh += len>>29;
c->Nl += len<<=3;
if (c->Nl<(unsigned int)len) c->Nh++;
}
if (res)
SHA1_Update(c,ptr,res);
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 20,807 |
jasper | a712a2041085e7cd5f2b153e1532ac2a2954ffaa | static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile)
{
jpc_dec_tcomp_t *tcomp;
int compno;
int bandno;
int rlvlno;
jpc_dec_band_t *band;
jpc_dec_rlvl_t *rlvl;
int prcno;
jpc_dec_prc_t *prc;
jpc_dec_seg_t *seg;
jpc_dec_cblk_t *cblk;
int cblkno;
if (tile->tcomps) {
for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps;
++compno, ++tcomp) {
for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls;
++rlvlno, ++rlvl) {
if (!rlvl->bands) {
continue;
}
for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands;
++bandno, ++band) {
if (band->prcs) {
for (prcno = 0, prc = band->prcs; prcno <
rlvl->numprcs; ++prcno, ++prc) {
if (!prc->cblks) {
continue;
}
for (cblkno = 0, cblk = prc->cblks; cblkno <
prc->numcblks; ++cblkno, ++cblk) {
while (cblk->segs.head) {
seg = cblk->segs.head;
jpc_seglist_remove(&cblk->segs, seg);
jpc_seg_destroy(seg);
}
jas_matrix_destroy(cblk->data);
if (cblk->mqdec) {
jpc_mqdec_destroy(cblk->mqdec);
}
if (cblk->nulldec) {
jpc_bitstream_close(cblk->nulldec);
}
if (cblk->flags) {
jas_matrix_destroy(cblk->flags);
}
}
if (prc->incltagtree) {
jpc_tagtree_destroy(prc->incltagtree);
}
if (prc->numimsbstagtree) {
jpc_tagtree_destroy(prc->numimsbstagtree);
}
if (prc->cblks) {
jas_free(prc->cblks);
}
}
}
if (band->data) {
jas_matrix_destroy(band->data);
}
if (band->prcs) {
jas_free(band->prcs);
}
}
if (rlvl->bands) {
jas_free(rlvl->bands);
}
}
if (tcomp->rlvls) {
jas_free(tcomp->rlvls);
}
if (tcomp->data) {
jas_matrix_destroy(tcomp->data);
}
if (tcomp->tsfb) {
jpc_tsfb_destroy(tcomp->tsfb);
}
}
}
if (tile->cp) {
jpc_dec_cp_destroy(tile->cp);
//tile->cp = 0;
}
if (tile->tcomps) {
jas_free(tile->tcomps);
//tile->tcomps = 0;
}
if (tile->pi) {
jpc_pi_destroy(tile->pi);
//tile->pi = 0;
}
if (tile->pkthdrstream) {
jas_stream_close(tile->pkthdrstream);
//tile->pkthdrstream = 0;
}
if (tile->pptstab) {
jpc_ppxstab_destroy(tile->pptstab);
//tile->pptstab = 0;
}
tile->state = JPC_TILE_DONE;
return 0;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,761 |
libjpeg-turbo | 9c78a04df4e44ef6487eee99c4258397f4fdca55 | start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
U_CHAR bmpfileheader[14];
U_CHAR bmpinfoheader[64];
#define GET_2B(array, offset) \
((unsigned short)UCH(array[offset]) + \
(((unsigned short)UCH(array[offset + 1])) << 8))
#define GET_4B(array, offset) \
((unsigned int)UCH(array[offset]) + \
(((unsigned int)UCH(array[offset + 1])) << 8) + \
(((unsigned int)UCH(array[offset + 2])) << 16) + \
(((unsigned int)UCH(array[offset + 3])) << 24))
unsigned int bfOffBits;
unsigned int headerSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned int biCompression;
int biXPelsPerMeter, biYPelsPerMeter;
unsigned int biClrUsed = 0;
int mapentrysize = 0; /* 0 indicates no colormap */
int bPad;
JDIMENSION row_width = 0;
/* Read and verify the bitmap file header */
if (!ReadOK(source->pub.input_file, bmpfileheader, 14))
ERREXIT(cinfo, JERR_INPUT_EOF);
if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */
ERREXIT(cinfo, JERR_BMP_NOT);
bfOffBits = GET_4B(bmpfileheader, 10);
/* We ignore the remaining fileheader fields */
/* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
* or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which.
*/
if (!ReadOK(source->pub.input_file, bmpinfoheader, 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
headerSize = GET_4B(bmpinfoheader, 0);
if (headerSize < 12 || headerSize > 64)
ERREXIT(cinfo, JERR_BMP_BADHEADER);
if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
switch (headerSize) {
case 12:
/* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
biWidth = (int)GET_2B(bmpinfoheader, 4);
biHeight = (int)GET_2B(bmpinfoheader, 6);
biPlanes = GET_2B(bmpinfoheader, 8);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10);
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
break;
case 40:
case 64:
/* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
/* or OS/2 2.x header, which has additional fields that we ignore */
biWidth = (int)GET_4B(bmpinfoheader, 4);
biHeight = (int)GET_4B(bmpinfoheader, 8);
biPlanes = GET_2B(bmpinfoheader, 12);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14);
biCompression = GET_4B(bmpinfoheader, 16);
biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24);
biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28);
biClrUsed = GET_4B(bmpinfoheader, 32);
/* biSizeImage, biClrImportant fields are ignored */
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 4; /* Windows uses RGBQUAD colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
case 32: /* RGB image + Alpha channel */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
if (biCompression != 0)
ERREXIT(cinfo, JERR_BMP_COMPRESSED);
if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
/* Set JFIF density parameters from the BMP data */
cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */
cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100);
cinfo->density_unit = 2; /* dots/cm */
}
break;
default:
ERREXIT(cinfo, JERR_BMP_BADHEADER);
return;
}
if (biWidth <= 0 || biHeight <= 0)
ERREXIT(cinfo, JERR_BMP_EMPTY);
if (biPlanes != 1)
ERREXIT(cinfo, JERR_BMP_BADPLANES);
/* Compute distance to bitmap data --- will adjust for colormap below */
bPad = bfOffBits - (headerSize + 14);
/* Read the colormap, if any */
if (mapentrysize > 0) {
if (biClrUsed <= 0)
biClrUsed = 256; /* assume it's 256 */
else if (biClrUsed > 256)
ERREXIT(cinfo, JERR_BMP_BADCMAP);
/* Allocate space to store the colormap */
source->colormap = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3);
/* and read it from the file */
read_colormap(source, (int)biClrUsed, mapentrysize);
/* account for size of colormap */
bPad -= biClrUsed * mapentrysize;
}
/* Skip any remaining pad bytes */
if (bPad < 0) /* incorrect bfOffBits value? */
ERREXIT(cinfo, JERR_BMP_BADHEADER);
while (--bPad >= 0) {
(void)read_byte(source);
}
/* Compute row width in file, including padding to 4-byte boundary */
switch (source->bits_per_pixel) {
case 8:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)biWidth;
break;
case 24:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGR;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 3);
break;
case 32:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGRA;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 4);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
while ((row_width & 3) != 0) row_width++;
source->row_width = row_width;
if (source->use_inversion_array) {
/* Allocate space for inversion array, prepare for preload pass */
source->whole_image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,
row_width, (JDIMENSION)biHeight, (JDIMENSION)1);
source->pub.get_pixel_rows = preload_image;
if (cinfo->progress != NULL) {
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
progress->total_extra_passes++; /* count file input as separate pass */
}
} else {
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width);
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
}
/* Ensure that biWidth * cinfo->input_components doesn't exceed the maximum
value of the JDIMENSION type. This is only a danger with BMP files, since
their width and height fields are 32-bit integers. */
if ((unsigned long long)biWidth *
(unsigned long long)cinfo->input_components > 0xFFFFFFFFULL)
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
/* Allocate one-row buffer for returned data */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1);
source->pub.buffer_height = 1;
cinfo->data_precision = 8;
cinfo->image_width = (JDIMENSION)biWidth;
cinfo->image_height = (JDIMENSION)biHeight;
}
| 1 | CVE-2018-14498 | CWE-125 | Out-of-bounds Read | The product reads data past the end, or before the beginning, of the intended buffer. | Phase: Implementation
Strategy: Input Validation
Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does.
When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue."
Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.
To reduce the likelihood of introducing an out-of-bounds read, ensure that you validate and ensure correct calculations for any length argument, buffer size calculation, or offset. Be especially careful of relying on a sentinel (i.e. special character such as NUL) in untrusted inputs.
Phase: Architecture and Design
Strategy: Language Selection
Use a language that provides appropriate memory abstractions. | 16 |
Android | 25c0ffbe6a181b4a373c3c9b421ea449d457e6ed | IHEVCD_ERROR_T ihevcd_parse_mastering_disp_params_sei(codec_t *ps_codec)
{
parse_ctxt_t *ps_parse = &ps_codec->s_parse;
bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
UWORD32 value;
mastering_dis_col_vol_sei_params_t *ps_mastering_dis_col_vol;
WORD32 i;
ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1;
ps_mastering_dis_col_vol = &ps_parse->s_sei_params.s_mastering_dis_col_vol_sei_params;
for(i = 0; i < 3; i++)
{
BITS_PARSE("display_primaries_x[c]", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->au2_display_primaries_x[i] = value;
BITS_PARSE("display_primaries_y[c]", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->au2_display_primaries_y[i] = value;
}
BITS_PARSE("white_point_x", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->u2_white_point_x = value;
BITS_PARSE("white_point_y", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->u2_white_point_y = value;
BITS_PARSE("max_display_mastering_luminance", value, ps_bitstrm, 32);
ps_mastering_dis_col_vol->u4_max_display_mastering_luminance = value;
BITS_PARSE("min_display_mastering_luminance", value, ps_bitstrm, 32);
ps_mastering_dis_col_vol->u4_min_display_mastering_luminance = value;
return (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 15,423 |
Android | 7c88b498fda1c2b608a9dd73960a2fd4d7b7e3f7 | void OMXNodeInstance::signalEvent(OMX_EVENTTYPE event, OMX_U32 arg1, OMX_U32 arg2) {
mOwner->OnEvent(mNodeID, event, arg1, arg2, NULL);
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,325 |
linux | 64620e0a1e712a778095bd35cbb277dc2259281f | static int check_stack_read(struct bpf_verifier_env *env,
int ptr_regno, int off, int size,
int dst_regno)
{
struct bpf_reg_state *reg = reg_state(env, ptr_regno);
struct bpf_func_state *state = func(env, reg);
int err;
/* Some accesses are only permitted with a static offset. */
bool var_off = !tnum_is_const(reg->var_off);
/* The offset is required to be static when reads don't go to a
* register, in order to not leak pointers (see
* check_stack_read_fixed_off).
*/
if (dst_regno < 0 && var_off) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
tn_buf, off, size);
return -EACCES;
}
/* Variable offset is prohibited for unprivileged mode for simplicity
* since it requires corresponding support in Spectre masking for stack
* ALU. See also retrieve_ptr_limit().
*/
if (!env->bypass_spec_v1 && var_off) {
char tn_buf[48];
tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
ptr_regno, tn_buf);
return -EACCES;
}
if (!var_off) {
off += reg->var_off.value;
err = check_stack_read_fixed_off(env, state, off, size,
dst_regno);
} else {
/* Variable offset stack reads need more conservative handling
* than fixed offset ones. Note that dst_regno >= 0 on this
* branch.
*/
err = check_stack_read_var_off(env, ptr_regno, off, size,
dst_regno);
}
return err;
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 13,133 |
tcpdump | f4b9e24c7384d882a7f434cc7413925bf871d63e | rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 18,798 |
linux | c8c2a057fdc7de1cd16f4baa51425b932a42eb39 | static void mlx5_fpga_conn_flush_send_bufs(struct mlx5_fpga_conn *conn)
{
struct mlx5_fpga_dma_buf *buf, *temp;
int ix;
for (ix = 0; ix < conn->qp.sq.size; ix++) {
buf = conn->qp.sq.bufs[ix];
if (!buf)
continue;
conn->qp.sq.bufs[ix] = NULL;
mlx5_fpga_conn_unmap_buf(conn, buf);
if (!buf->complete)
continue;
buf->complete(conn, conn->fdev, buf, MLX5_CQE_SYNDROME_WR_FLUSH_ERR);
}
list_for_each_entry_safe(buf, temp, &conn->qp.sq.backlog, list) {
mlx5_fpga_conn_unmap_buf(conn, buf);
if (!buf->complete)
continue;
buf->complete(conn, conn->fdev, buf, MLX5_CQE_SYNDROME_WR_FLUSH_ERR);
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 16,829 |
tcpdump | 7029d15f148ef24bb7c6668bc640f5470d085e5a | handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 21,827 |
linux | 57ebd808a97d7c5b1e1afb937c2db22beba3c1f8 | compat_do_ipt_set_ctl(struct sock *sk, int cmd, void __user *user,
unsigned int len)
{
int ret;
if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case IPT_SO_SET_REPLACE:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case IPT_SO_SET_ADD_COUNTERS:
ret = do_add_counters(sock_net(sk), user, len, 1);
break;
default:
ret = -EINVAL;
}
return ret;
}
| 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,127 |
vim | 0e8e938d497260dd57be67b4966cb27a5f72376f | fixthisline(int (*get_the_indent)(void))
{
int amount = get_the_indent();
if (amount >= 0)
{
change_indent(INDENT_SET, amount, FALSE, 0, TRUE);
if (linewhite(curwin->w_cursor.lnum))
did_ai = TRUE; // delete the indent if the line stays empty
}
} | 0 | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | NOT_APPLICABLE | 14,919 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.