instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host || host->was_select_cache_called()) return false; host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); return true; } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
bool AppCacheBackendImpl::SelectCache( int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->SelectCache(document_url, cache_document_was_loaded_from, manifest_url); }
171,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (ipc_enabled_) worker_delegate_->OnChannelConnected(); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (!ipc_enabled_) return; // Verify |peer_pid| because it is controlled by the client and cannot be // trusted. DWORD actual_pid = launcher_delegate_->GetProcessId(); if (peer_pid != static_cast<int32>(actual_pid)) { LOG(ERROR) << "The actual client PID " << actual_pid << " does not match the one reported by the client: " << peer_pid; StopWorker(); return; } worker_delegate_->OnChannelConnected(peer_pid); }
171,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ih264d_init_decoder(void * ps_dec_params) { dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params; dec_slice_params_t *ps_cur_slice; pocstruct_t *ps_prev_poc, *ps_cur_poc; /* Free any dynamic buffers that are allocated */ ih264d_free_dynamic_bufs(ps_dec); ps_cur_slice = ps_dec->ps_cur_slice; ps_dec->init_done = 0; ps_dec->u4_num_cores = 1; ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0; ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE; ps_dec->u4_app_disable_deblk_frm = 0; ps_dec->i4_degrade_type = 0; ps_dec->i4_degrade_pics = 0; ps_dec->i4_app_skip_mode = IVD_SKIP_NONE; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; memset(ps_dec->ps_pps, 0, ((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS)); memset(ps_dec->ps_sps, 0, ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS)); /* Initialization of function pointers ih264d_deblock_picture function*/ ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff; ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff; ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec; ps_dec->u4_num_fld_in_frm = 0; ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec; /* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/ ps_dec->ps_sei->u1_is_valid = 0; /* decParams Initializations */ ps_dec->ps_cur_pps = NULL; ps_dec->ps_cur_sps = NULL; ps_dec->u1_init_dec_flag = 0; ps_dec->u1_first_slice_in_stream = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u4_app_disp_width = 0; ps_dec->i4_header_decoded = 0; ps_dec->u4_total_frames_decoded = 0; ps_dec->i4_error_code = 0; ps_dec->i4_content_type = -1; ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0; ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS; ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN; ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT; ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME; ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN; ps_dec->u1_pr_sl_type = 0xFF; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; ps_dec->u2_total_mbs_coded = 0; /* POC initializations */ ps_prev_poc = &ps_dec->s_prev_pic_poc; ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0] = 0; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1] = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count = 0; ps_prev_poc->i4_bottom_field_order_count = ps_cur_poc->i4_bottom_field_order_count = 0; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0; ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = 0; ps_dec->i4_max_poc = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->u1_recon_mb_grp = 4; /* Field PIC initializations */ ps_dec->u1_second_field = 0; ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; /* Set the cropping parameters as zero */ ps_dec->u2_crop_offset_y = 0; ps_dec->u2_crop_offset_uv = 0; /* The Initial Frame Rate Info is not Present */ ps_dec->i4_vui_frame_rate = -1; ps_dec->i4_pic_type = -1; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u1_res_changed = 0; ps_dec->u1_frame_decoded_flag = 0; /* Set the default frame seek mask mode */ ps_dec->u4_skip_frm_mask = SKIP_NONE; /********************************************************/ /* Initialize CAVLC residual decoding function pointers */ /********************************************************/ ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1; ps_dec->pf_cavlc_4x4res_block[1] = ih264d_cavlc_4x4res_block_totalcoeff_2to10; ps_dec->pf_cavlc_4x4res_block[2] = ih264d_cavlc_4x4res_block_totalcoeff_11to16; ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7; ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8; ps_dec->pf_cavlc_parse_8x8block[0] = ih264d_cavlc_parse_8x8block_none_available; ps_dec->pf_cavlc_parse_8x8block[1] = ih264d_cavlc_parse_8x8block_left_available; ps_dec->pf_cavlc_parse_8x8block[2] = ih264d_cavlc_parse_8x8block_top_available; ps_dec->pf_cavlc_parse_8x8block[3] = ih264d_cavlc_parse_8x8block_both_available; /***************************************************************************/ /* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */ /***************************************************************************/ ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice; ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice; ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice; ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice; ps_dec->pf_fill_bs_xtra_left_edge[0] = ih264d_fill_bs_xtra_left_edge_cur_frm; ps_dec->pf_fill_bs_xtra_left_edge[1] = ih264d_fill_bs_xtra_left_edge_cur_fld; /* Initialize Reference Pic Buffers */ ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr); ps_dec->u2_prv_frame_num = 0; ps_dec->u1_top_bottom_decoded = 0; ps_dec->u1_dangling_field = 0; ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table; ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0]; ps_dec->pi1_left_ref_idx_ctxt_inc = &ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0]; ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb; /* ! */ /* Initializing flush frame u4_flag */ ps_dec->u1_flushfrm = 0; { ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec; ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec; ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec; ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec; } memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t)); memset(ps_dec->u4_disp_buf_mapping, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); memset(ps_dec->u4_disp_buf_to_be_freed, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); ih264d_init_arch(ps_dec); ih264d_init_function_ptr(ps_dec); ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT; ps_dec->init_done = 1; } Commit Message: Decoder: Memset few structures to zero to handle error clips Bug: 27907656 Change-Id: I671d135dd5c324c39b4ede990b7225d52ba882cd CWE ID: CWE-20
void ih264d_init_decoder(void * ps_dec_params) { dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params; dec_slice_params_t *ps_cur_slice; pocstruct_t *ps_prev_poc, *ps_cur_poc; WORD32 size; size = sizeof(pred_info_t) * 2 * 32; memset(ps_dec->ps_pred, 0 , size); size = sizeof(disp_mgr_t); memset(ps_dec->pv_disp_buf_mgr, 0 , size); size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size(); memset(ps_dec->pv_pic_buf_mgr, 0, size); size = sizeof(dec_err_status_t); memset(ps_dec->ps_dec_err_status, 0, size); size = sizeof(sei); memset(ps_dec->ps_sei, 0, size); size = sizeof(dpb_commands_t); memset(ps_dec->ps_dpb_cmds, 0, size); size = sizeof(dec_bit_stream_t); memset(ps_dec->ps_bitstrm, 0, size); size = sizeof(dec_slice_params_t); memset(ps_dec->ps_cur_slice, 0, size); size = MAX(sizeof(dec_seq_params_t), sizeof(dec_pic_params_t)); memset(ps_dec->pv_scratch_sps_pps, 0, size); size = sizeof(ctxt_inc_mb_info_t); memset(ps_dec->ps_left_mb_ctxt_info, 0, size); size = (sizeof(neighbouradd_t) << 2); memset(ps_dec->ps_left_mvpred_addr, 0 ,size); size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size(); memset(ps_dec->pv_mv_buf_mgr, 0, size); /* Free any dynamic buffers that are allocated */ ih264d_free_dynamic_bufs(ps_dec); ps_cur_slice = ps_dec->ps_cur_slice; ps_dec->init_done = 0; ps_dec->u4_num_cores = 1; ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0; ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE; ps_dec->u4_app_disable_deblk_frm = 0; ps_dec->i4_degrade_type = 0; ps_dec->i4_degrade_pics = 0; ps_dec->i4_app_skip_mode = IVD_SKIP_NONE; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; memset(ps_dec->ps_pps, 0, ((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS)); memset(ps_dec->ps_sps, 0, ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS)); /* Initialization of function pointers ih264d_deblock_picture function*/ ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff; ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff; ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec; ps_dec->u4_num_fld_in_frm = 0; ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec; /* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/ ps_dec->ps_sei->u1_is_valid = 0; /* decParams Initializations */ ps_dec->ps_cur_pps = NULL; ps_dec->ps_cur_sps = NULL; ps_dec->u1_init_dec_flag = 0; ps_dec->u1_first_slice_in_stream = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u4_app_disp_width = 0; ps_dec->i4_header_decoded = 0; ps_dec->u4_total_frames_decoded = 0; ps_dec->i4_error_code = 0; ps_dec->i4_content_type = -1; ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0; ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS; ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN; ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT; ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME; ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN; ps_dec->u1_pr_sl_type = 0xFF; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; ps_dec->u2_total_mbs_coded = 0; /* POC initializations */ ps_prev_poc = &ps_dec->s_prev_pic_poc; ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0] = 0; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1] = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count = 0; ps_prev_poc->i4_bottom_field_order_count = ps_cur_poc->i4_bottom_field_order_count = 0; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0; ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = 0; ps_dec->i4_max_poc = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->u1_recon_mb_grp = 4; /* Field PIC initializations */ ps_dec->u1_second_field = 0; ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; /* Set the cropping parameters as zero */ ps_dec->u2_crop_offset_y = 0; ps_dec->u2_crop_offset_uv = 0; /* The Initial Frame Rate Info is not Present */ ps_dec->i4_vui_frame_rate = -1; ps_dec->i4_pic_type = -1; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u1_res_changed = 0; ps_dec->u1_frame_decoded_flag = 0; /* Set the default frame seek mask mode */ ps_dec->u4_skip_frm_mask = SKIP_NONE; /********************************************************/ /* Initialize CAVLC residual decoding function pointers */ /********************************************************/ ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1; ps_dec->pf_cavlc_4x4res_block[1] = ih264d_cavlc_4x4res_block_totalcoeff_2to10; ps_dec->pf_cavlc_4x4res_block[2] = ih264d_cavlc_4x4res_block_totalcoeff_11to16; ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7; ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8; ps_dec->pf_cavlc_parse_8x8block[0] = ih264d_cavlc_parse_8x8block_none_available; ps_dec->pf_cavlc_parse_8x8block[1] = ih264d_cavlc_parse_8x8block_left_available; ps_dec->pf_cavlc_parse_8x8block[2] = ih264d_cavlc_parse_8x8block_top_available; ps_dec->pf_cavlc_parse_8x8block[3] = ih264d_cavlc_parse_8x8block_both_available; /***************************************************************************/ /* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */ /***************************************************************************/ ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice; ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice; ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice; ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice; ps_dec->pf_fill_bs_xtra_left_edge[0] = ih264d_fill_bs_xtra_left_edge_cur_frm; ps_dec->pf_fill_bs_xtra_left_edge[1] = ih264d_fill_bs_xtra_left_edge_cur_fld; /* Initialize Reference Pic Buffers */ ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr); ps_dec->u2_prv_frame_num = 0; ps_dec->u1_top_bottom_decoded = 0; ps_dec->u1_dangling_field = 0; ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table; ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0]; ps_dec->pi1_left_ref_idx_ctxt_inc = &ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0]; ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb; /* ! */ /* Initializing flush frame u4_flag */ ps_dec->u1_flushfrm = 0; { ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec; ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec; ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec; ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec; } memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t)); memset(ps_dec->u4_disp_buf_mapping, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); memset(ps_dec->u4_disp_buf_to_be_freed, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); ih264d_init_arch(ps_dec); ih264d_init_function_ptr(ps_dec); ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT; ps_dec->init_done = 1; }
173,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(blink::mojom::WebBluetoothResult::CHOOSER_CANCELLED); } } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
BluetoothDeviceChooserController::~BluetoothDeviceChooserController() { if (scanning_start_time_) { RecordScanningDuration(base::TimeTicks::Now() - scanning_start_time_.value()); } if (chooser_) { DCHECK(!error_callback_.is_null()); error_callback_.Run(WebBluetoothResult::CHOOSER_CANCELLED); } }
172,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; release_sock(sk); return 0; } Commit Message: Bluetooth: HCI - Fix info leak via getsockname() The HCI code fails to initialize the hci_channel member of struct sockaddr_hci and that for leaks two bytes kernel stack via the getsockname() syscall. Initialize hci_channel with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; haddr->hci_channel= 0; release_sock(sk); return 0; }
169,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; } Commit Message: fix buffer overrun in gf_bin128_parse closes #1204 closes #1205 CWE ID: CWE-119
GF_Err gf_bin128_parse(const char *string, bin128 value) { u32 len; u32 i=0; if (!strnicmp(string, "0x", 2)) string += 2; len = (u32) strlen(string); if (len >= 32) { u32 j; for (j=0; j<len; j+=2) { u32 v; char szV[5]; while (string[j] && !isalnum(string[j])) j++; if (!string[j]) break; sprintf(szV, "%c%c", string[j], string[j+1]); sscanf(szV, "%x", &v); value[i] = v; i++; if (i > 15) { // force error check below i++; break; } } } if (i != 16) { GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[CORE] 128bit blob is not 16-bytes long: %s\n", string)); return GF_BAD_PARAM; } return GF_OK; }
169,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rdfa_parse_start(rdfacontext* context) { int rval = RDFA_PARSE_SUCCESS; context->wb_allocated = sizeof(char) * READ_BUFFER_SIZE; context->working_buffer = (char*)malloc(context->wb_allocated + 1); *context->working_buffer = '\0'; #ifndef LIBRDFA_IN_RAPTOR context->parser = XML_ParserCreate(NULL); #endif context->done = 0; context->context_stack = rdfa_create_list(32); rdfa_push_item(context->context_stack, context, RDFALIST_FLAG_CONTEXT); #ifdef LIBRDFA_IN_RAPTOR context->sax2 = raptor_new_sax2(context->world, context->locator, context->context_stack); #else #endif #ifdef LIBRDFA_IN_RAPTOR raptor_sax2_set_start_element_handler(context->sax2, raptor_rdfa_start_element); raptor_sax2_set_end_element_handler(context->sax2, raptor_rdfa_end_element); raptor_sax2_set_characters_handler(context->sax2, raptor_rdfa_character_data); raptor_sax2_set_namespace_handler(context->sax2, raptor_rdfa_namespace_handler); #else XML_SetUserData(context->parser, context->context_stack); XML_SetElementHandler(context->parser, start_element, end_element); XML_SetCharacterDataHandler(context->parser, character_data); #endif rdfa_init_context(context); #ifdef LIBRDFA_IN_RAPTOR if(1) { raptor_parser* rdf_parser = (raptor_parser*)context->callback_data; /* Optionally forbid internal network and file requests in the * XML parser */ raptor_sax2_set_option(context->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(context->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(context->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); } context->base_uri=raptor_new_uri(context->sax2->world, (const unsigned char*)context->base); raptor_sax2_parse_start(context->sax2, context->base_uri); #endif return rval; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
int rdfa_parse_start(rdfacontext* context) { int rval = RDFA_PARSE_SUCCESS; context->wb_allocated = sizeof(char) * READ_BUFFER_SIZE; context->working_buffer = (char*)malloc(context->wb_allocated + 1); *context->working_buffer = '\0'; #ifndef LIBRDFA_IN_RAPTOR context->parser = XML_ParserCreate(NULL); #endif context->done = 0; context->context_stack = rdfa_create_list(32); rdfa_push_item(context->context_stack, context, RDFALIST_FLAG_CONTEXT); #ifdef LIBRDFA_IN_RAPTOR context->sax2 = raptor_new_sax2(context->world, context->locator, context->context_stack); #else #endif #ifdef LIBRDFA_IN_RAPTOR raptor_sax2_set_start_element_handler(context->sax2, raptor_rdfa_start_element); raptor_sax2_set_end_element_handler(context->sax2, raptor_rdfa_end_element); raptor_sax2_set_characters_handler(context->sax2, raptor_rdfa_character_data); raptor_sax2_set_namespace_handler(context->sax2, raptor_rdfa_namespace_handler); #else XML_SetUserData(context->parser, context->context_stack); XML_SetElementHandler(context->parser, start_element, end_element); XML_SetCharacterDataHandler(context->parser, character_data); #endif rdfa_init_context(context); #ifdef LIBRDFA_IN_RAPTOR if(1) { raptor_parser* rdf_parser = (raptor_parser*)context->callback_data; /* Optionally forbid internal network and file requests in the * XML parser */ raptor_sax2_set_option(context->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(context->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); raptor_sax2_set_option(context->sax2, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(context->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); } context->base_uri=raptor_new_uri(context->sax2->world, (const unsigned char*)context->base); raptor_sax2_parse_start(context->sax2, context->base_uri); #endif return rval; }
165,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::InsertSyncPointAndACK( int32 route_id, int gpu_host_id, bool presented, ui::Compositor* compositor) { uint32 sync_point = 0; if (compositor) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); sync_point = factory->InsertSyncPoint(); } RenderWidgetHostImpl::AcknowledgeBufferPresent( route_id, gpu_host_id, presented, sync_point); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::InsertSyncPointAndACK( const BufferPresentedParams& params) { uint32 sync_point = 0; // If we produced a texture, we have to synchronize with the consumer of // that texture. if (params.texture_to_produce) { params.texture_to_produce->Produce(); sync_point = ImageTransportFactory::GetInstance()->InsertSyncPoint(); } RenderWidgetHostImpl::AcknowledgeBufferPresent( params.route_id, params.gpu_host_id, params.surface_handle, sync_point); }
171,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); } Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks. Prevent a possible buffer overread in chdlc_print() and replace the custom check in chdlc_if_print() with a standard check in chdlc_print() so that the latter certainly does not over-read even when reached via juniper_chdlc_print(). Add length checks. CWE ID: CWE-125
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length) { u_int proto; const u_char *bp = p; if (length < CHDLC_HDRLEN) goto trunc; ND_TCHECK2(*p, CHDLC_HDRLEN); proto = EXTRACT_16BITS(&p[2]); if (ndo->ndo_eflag) { ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ", tok2str(chdlc_cast_values, "0x%02x", p[0]), tok2str(ethertype_values, "Unknown", proto), proto, length)); } length -= CHDLC_HDRLEN; p += CHDLC_HDRLEN; switch (proto) { case ETHERTYPE_IP: ip_print(ndo, p, length); break; case ETHERTYPE_IPV6: ip6_print(ndo, p, length); break; case CHDLC_TYPE_SLARP: chdlc_slarp_print(ndo, p, length); break; #if 0 case CHDLC_TYPE_CDP: chdlc_cdp_print(p, length); break; #endif case ETHERTYPE_MPLS: case ETHERTYPE_MPLS_MULTI: mpls_print(ndo, p, length); break; case ETHERTYPE_ISO: /* is the fudge byte set ? lets verify by spotting ISO headers */ if (length < 2) goto trunc; ND_TCHECK_16BITS(p); if (*(p+1) == 0x81 || *(p+1) == 0x82 || *(p+1) == 0x83) isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1); else isoclns_print(ndo, p, length, ndo->ndo_snapend - p); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto)); break; } return (CHDLC_HDRLEN); trunc: ND_PRINT((ndo, "[|chdlc]")); return ndo->ndo_snapend - bp; }
170,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; }
174,488
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "OnDocumentElementCreated", base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated, base::Unretained(this))); } Commit Message: Fix re-entrancy and lifetime issue in RenderFrameObserverNatives::OnDocumentElementCreated BUG=585268,568130 Review URL: https://codereview.chromium.org/1684953002 Cr-Commit-Position: refs/heads/master@{#374758} CWE ID:
RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_ptr_factory_(this) { RouteFunction( "OnDocumentElementCreated", base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated, base::Unretained(this))); }
172,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void build_ntlmssp_negotiate_blob(unsigned char *pbuffer, struct cifs_ses *ses) { NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer; __u32 flags; memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE)); memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmNegotiate; /* BB is NTLMV2 session security format easier to use here? */ flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC; if (ses->server->sign) { flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; } sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->WorkstationName.BufferOffset = 0; sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; /* Domain name is sent on the Challenge not Negotiate NTLMSSP request */ sec_blob->DomainName.BufferOffset = 0; sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; } Commit Message: CIFS: Enable encryption during session setup phase In order to allow encryption on SMB connection we need to exchange a session key and generate encryption and decryption keys. Signed-off-by: Pavel Shilovsky <[email protected]> CWE ID: CWE-476
void build_ntlmssp_negotiate_blob(unsigned char *pbuffer, struct cifs_ses *ses) { NEGOTIATE_MESSAGE *sec_blob = (NEGOTIATE_MESSAGE *)pbuffer; __u32 flags; memset(pbuffer, 0, sizeof(NEGOTIATE_MESSAGE)); memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); sec_blob->MessageType = NtLmNegotiate; /* BB is NTLMV2 session security format easier to use here? */ flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | NTLMSSP_NEGOTIATE_SEAL; if (ses->server->sign) flags |= NTLMSSP_NEGOTIATE_SIGN; if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) flags |= NTLMSSP_NEGOTIATE_KEY_XCH; sec_blob->NegotiateFlags = cpu_to_le32(flags); sec_blob->WorkstationName.BufferOffset = 0; sec_blob->WorkstationName.Length = 0; sec_blob->WorkstationName.MaximumLength = 0; /* Domain name is sent on the Challenge not Negotiate NTLMSSP request */ sec_blob->DomainName.BufferOffset = 0; sec_blob->DomainName.Length = 0; sec_blob->DomainName.MaximumLength = 0; }
169,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void kiocb_batch_free(struct kiocb_batch *batch) { struct kiocb *req, *n; list_for_each_entry_safe(req, n, &batch->head, ki_batch) { list_del(&req->ki_batch); kmem_cache_free(kiocb_cachep, req); } } Commit Message: Unused iocbs in a batch should not be accounted as active. commit 69e4747ee9727d660b88d7e1efe0f4afcb35db1b upstream. Since commit 080d676de095 ("aio: allocate kiocbs in batches") iocbs are allocated in a batch during processing of first iocbs. All iocbs in a batch are automatically added to ctx->active_reqs list and accounted in ctx->reqs_active. If one (not the last one) of iocbs submitted by an user fails, further iocbs are not processed, but they are still present in ctx->active_reqs and accounted in ctx->reqs_active. This causes process to stuck in a D state in wait_for_all_aios() on exit since ctx->reqs_active will never go down to zero. Furthermore since kiocb_batch_free() frees iocb without removing it from active_reqs list the list become corrupted which may cause oops. Fix this by removing iocb from ctx->active_reqs and updating ctx->reqs_active in kiocb_batch_free(). Signed-off-by: Gleb Natapov <[email protected]> Reviewed-by: Jeff Moyer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-399
static void kiocb_batch_free(struct kiocb_batch *batch) static void kiocb_batch_free(struct kioctx *ctx, struct kiocb_batch *batch) { struct kiocb *req, *n; if (list_empty(&batch->head)) return; spin_lock_irq(&ctx->ctx_lock); list_for_each_entry_safe(req, n, &batch->head, ki_batch) { list_del(&req->ki_batch); list_del(&req->ki_list); kmem_cache_free(kiocb_cachep, req); ctx->reqs_active--; } spin_unlock_irq(&ctx->ctx_lock); }
165,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SegmentInfo::SegmentInfo( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_pMuxingAppAsUTF8(NULL), m_pWritingAppAsUTF8(NULL), m_pTitleAsUTF8(NULL) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
SegmentInfo::SegmentInfo(
174,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void registerBlobURLFromTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL); }
170,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ManifestUmaUtil::FetchFailed(FetchFailureReason reason) { ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT; switch (reason) { case FETCH_EMPTY_URL: fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL; break; case FETCH_UNSPECIFIED_REASON: fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED; break; } DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult, fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestUmaUtil::FetchFailed(FetchFailureReason reason) { ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT; switch (reason) { case FETCH_EMPTY_URL: fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL; break; case FETCH_FROM_UNIQUE_ORIGIN: fetch_result_type = MANIFEST_FETCH_ERROR_FROM_UNIQUE_ORIGIN; break; case FETCH_UNSPECIFIED_REASON: fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED; break; } DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult, fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); }
172,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate( TabContents* tab_contents, const string16& utf16_name) : PluginInfoBarDelegate(tab_contents, utf16_name) { UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown")); std::string name = UTF16ToUTF8(utf16_name); if (name == webkit::npapi::PluginGroup::kJavaGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Java")); else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime")); else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave")); else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer")); } Commit Message: Infobar Windows Media Player plug-in by default. BUG=51464 Review URL: http://codereview.chromium.org/7080048 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87500 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate( TabContents* tab_contents, const string16& utf16_name) : PluginInfoBarDelegate(tab_contents, utf16_name) { UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown")); std::string name = UTF16ToUTF8(utf16_name); if (name == webkit::npapi::PluginGroup::kJavaGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Java")); else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime")); else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave")); else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer")); else if (name == webkit::npapi::PluginGroup::kWindowsMediaPlayerGroupName) UserMetrics::RecordAction( UserMetricsAction("BlockedPluginInfobar.Shown.WindowsMediaPlayer")); }
170,299
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; } Commit Message: Fix invalid read in ppapi code BUG=77493 TEST=attached test Review URL: http://codereview.chromium.org/6883059 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@82172 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool PPVarToNPVariant(PP_Var var, NPVariant* result) { switch (var.type) { case PP_VARTYPE_UNDEFINED: VOID_TO_NPVARIANT(*result); break; case PP_VARTYPE_NULL: NULL_TO_NPVARIANT(*result); break; case PP_VARTYPE_BOOL: BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result); break; case PP_VARTYPE_INT32: INT32_TO_NPVARIANT(var.value.as_int, *result); break; case PP_VARTYPE_DOUBLE: DOUBLE_TO_NPVARIANT(var.value.as_double, *result); break; case PP_VARTYPE_STRING: { scoped_refptr<StringVar> string(StringVar::FromPPVar(var)); if (!string) { VOID_TO_NPVARIANT(*result); return false; } const std::string& value = string->value(); char* c_string = static_cast<char*>(malloc(value.size())); memcpy(c_string, value.data(), value.size()); STRINGN_TO_NPVARIANT(c_string, value.size(), *result); break; } case PP_VARTYPE_OBJECT: { scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var)); if (!object) { VOID_TO_NPVARIANT(*result); return false; } OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()), *result); break; } case PP_VARTYPE_ARRAY: case PP_VARTYPE_DICTIONARY: VOID_TO_NPVARIANT(*result); break; } return true; }
170,554
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VarianceTest<VarianceFunctionType>::OneQuarterTest() { memset(src_, 255, block_size_); const int half = block_size_ / 2; memset(ref_, 255, half); memset(ref_ + half, 0, half); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::OneQuarterTest() { const int half = block_size_ / 2; if (!use_high_bit_depth_) { memset(src_, 255, block_size_); memset(ref_, 255, half); memset(ref_ + half, 0, half); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(src_), 255 << (bit_depth_ - 8), block_size_); vpx_memset16(CONVERT_TO_SHORTPTR(ref_), 255 << (bit_depth_ - 8), half); vpx_memset16(CONVERT_TO_SHORTPTR(ref_) + half, 0, half); #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse; unsigned int var; ASM_REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); const unsigned int expected = block_size_ * 255 * 255 / 4; EXPECT_EQ(expected, var); }
174,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: log_result (PolkitBackendInteractiveAuthority *authority, const gchar *action_id, PolkitSubject *subject, PolkitSubject *caller, PolkitAuthorizationResult *result) { PolkitBackendInteractiveAuthorityPrivate *priv; PolkitIdentity *user_of_subject; const gchar *log_result_str; gchar *subject_str; gchar *user_of_subject_str; gchar *caller_str; gchar *subject_cmdline; gchar *caller_cmdline; priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (authority); log_result_str = "DENYING"; if (polkit_authorization_result_get_is_authorized (result)) log_result_str = "ALLOWING"; user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); subject_str = polkit_subject_to_string (subject); if (user_of_subject != NULL) user_of_subject_str = polkit_identity_to_string (user_of_subject); else user_of_subject_str = g_strdup ("<unknown>"); caller_str = polkit_subject_to_string (caller); subject_cmdline = _polkit_subject_get_cmdline (subject); if (subject_cmdline == NULL) subject_cmdline = g_strdup ("<unknown>"); caller_cmdline = _polkit_subject_get_cmdline (caller); if (caller_cmdline == NULL) caller_cmdline = g_strdup ("<unknown>"); polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority), "%s action %s for %s [%s] owned by %s (check requested by %s [%s])", log_result_str, action_id, subject_str, subject_cmdline, user_of_subject_str, caller_str, caller_cmdline); if (user_of_subject != NULL) g_object_unref (user_of_subject); g_free (subject_str); g_free (user_of_subject_str); g_free (caller_str); g_free (subject_cmdline); g_free (caller_cmdline); } Commit Message: CWE ID: CWE-200
log_result (PolkitBackendInteractiveAuthority *authority, const gchar *action_id, PolkitSubject *subject, PolkitSubject *caller, PolkitAuthorizationResult *result) { PolkitBackendInteractiveAuthorityPrivate *priv; PolkitIdentity *user_of_subject; const gchar *log_result_str; gchar *subject_str; gchar *user_of_subject_str; gchar *caller_str; gchar *subject_cmdline; gchar *caller_cmdline; priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (authority); log_result_str = "DENYING"; if (polkit_authorization_result_get_is_authorized (result)) log_result_str = "ALLOWING"; user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL, NULL); subject_str = polkit_subject_to_string (subject); if (user_of_subject != NULL) user_of_subject_str = polkit_identity_to_string (user_of_subject); else user_of_subject_str = g_strdup ("<unknown>"); caller_str = polkit_subject_to_string (caller); subject_cmdline = _polkit_subject_get_cmdline (subject); if (subject_cmdline == NULL) subject_cmdline = g_strdup ("<unknown>"); caller_cmdline = _polkit_subject_get_cmdline (caller); if (caller_cmdline == NULL) caller_cmdline = g_strdup ("<unknown>"); polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority), "%s action %s for %s [%s] owned by %s (check requested by %s [%s])", log_result_str, action_id, subject_str, subject_cmdline, user_of_subject_str, caller_str, caller_cmdline); if (user_of_subject != NULL) g_object_unref (user_of_subject); g_free (subject_str); g_free (user_of_subject_str); g_free (caller_str); g_free (subject_cmdline); g_free (caller_cmdline); }
165,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ while (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) { u16 wTmp; snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead))); wTmp = readw(chip->DSPQ + JQS_wHead) + 1; if (wTmp > readw(chip->DSPQ + JQS_wSize)) writew(0, chip->DSPQ + JQS_wHead); else writew(wTmp, chip->DSPQ + JQS_wHead); } /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; } Commit Message: ALSA: msnd: Optimize / harden DSP and MIDI loops The ISA msnd drivers have loops fetching the ring-buffer head, tail and size values inside the loops. Such codes are inefficient and fragile. This patch optimizes it, and also adds the sanity check to avoid the endless loops. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131 Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133 Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-125
static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; u16 head, tail, size; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ head = readw(chip->DSPQ + JQS_wHead); tail = readw(chip->DSPQ + JQS_wTail); size = readw(chip->DSPQ + JQS_wSize); if (head > size || tail > size) goto out; while (head != tail) { snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * head)); if (++head > size) head = 0; writew(head, chip->DSPQ + JQS_wHead); } out: /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; }
168,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize; i += PCI_VPD_LRDT_TAG_SIZE; if (block_end > vpdlen) goto out_not_found; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_MFR_ID); if (j > 0) { len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_VENDOR0); if (j < 0) goto partno; len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end) goto partno; memcpy(tp->fw_ver, &vpd_data[j], len); strncat(tp->fw_ver, " bc ", vpdlen - len - 1); } partno: i = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_PARTNO); if (i < 0) goto out_not_found; len = pci_vpd_info_field_size(&vpd_data[i]); i += PCI_VPD_INFO_FLD_HDR_SIZE; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } } Commit Message: tg3: fix length overflow in VPD firmware parsing Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version when present") introduced VPD parsing that contained a potential length overflow. Limit the hardware's reported firmware string length (max 255 bytes) to stay inside the driver's firmware string length (32 bytes). On overflow, truncate the formatted firmware string instead of potentially overwriting portions of the tg3 struct. http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf Signed-off-by: Kees Cook <[email protected]> Reported-by: Oded Horovitz <[email protected]> Reported-by: Brad Spengler <[email protected]> Cc: [email protected] Cc: Matt Carlson <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static void tg3_read_vpd(struct tg3 *tp) { u8 *vpd_data; unsigned int block_end, rosize, len; u32 vpdlen; int j, i = 0; vpd_data = (u8 *)tg3_vpd_readblock(tp, &vpdlen); if (!vpd_data) goto out_no_vpd; i = pci_vpd_find_tag(vpd_data, 0, vpdlen, PCI_VPD_LRDT_RO_DATA); if (i < 0) goto out_not_found; rosize = pci_vpd_lrdt_size(&vpd_data[i]); block_end = i + PCI_VPD_LRDT_TAG_SIZE + rosize; i += PCI_VPD_LRDT_TAG_SIZE; if (block_end > vpdlen) goto out_not_found; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_MFR_ID); if (j > 0) { len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end || len != 4 || memcmp(&vpd_data[j], "1028", 4)) goto partno; j = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_VENDOR0); if (j < 0) goto partno; len = pci_vpd_info_field_size(&vpd_data[j]); j += PCI_VPD_INFO_FLD_HDR_SIZE; if (j + len > block_end) goto partno; if (len >= sizeof(tp->fw_ver)) len = sizeof(tp->fw_ver) - 1; memset(tp->fw_ver, 0, sizeof(tp->fw_ver)); snprintf(tp->fw_ver, sizeof(tp->fw_ver), "%.*s bc ", len, &vpd_data[j]); } partno: i = pci_vpd_find_info_keyword(vpd_data, i, rosize, PCI_VPD_RO_KEYWORD_PARTNO); if (i < 0) goto out_not_found; len = pci_vpd_info_field_size(&vpd_data[i]); i += PCI_VPD_INFO_FLD_HDR_SIZE; if (len > TG3_BPN_SIZE || (len + i) > vpdlen) goto out_not_found; memcpy(tp->board_part_number, &vpd_data[i], len); out_not_found: kfree(vpd_data); if (tp->board_part_number[0]) return; out_no_vpd: if (tg3_asic_rev(tp) == ASIC_REV_5717) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717 || tp->pdev->device == TG3PCI_DEVICE_TIGON3_5717_C) strcpy(tp->board_part_number, "BCM5717"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_5718) strcpy(tp->board_part_number, "BCM5718"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57780) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57780) strcpy(tp->board_part_number, "BCM57780"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57760) strcpy(tp->board_part_number, "BCM57760"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57790) strcpy(tp->board_part_number, "BCM57790"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57788) strcpy(tp->board_part_number, "BCM57788"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57765) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57761) strcpy(tp->board_part_number, "BCM57761"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57765) strcpy(tp->board_part_number, "BCM57765"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57781) strcpy(tp->board_part_number, "BCM57781"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57785) strcpy(tp->board_part_number, "BCM57785"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57791) strcpy(tp->board_part_number, "BCM57791"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57795) strcpy(tp->board_part_number, "BCM57795"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_57766) { if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57762) strcpy(tp->board_part_number, "BCM57762"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57766) strcpy(tp->board_part_number, "BCM57766"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57782) strcpy(tp->board_part_number, "BCM57782"); else if (tp->pdev->device == TG3PCI_DEVICE_TIGON3_57786) strcpy(tp->board_part_number, "BCM57786"); else goto nomatch; } else if (tg3_asic_rev(tp) == ASIC_REV_5906) { strcpy(tp->board_part_number, "BCM95906"); } else { nomatch: strcpy(tp->board_part_number, "none"); } }
166,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; } Commit Message: CWE ID: CWE-354
char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; if (protocol_version < 21) { /* Don't allow a weak checksum for the password. */ rprintf(FERROR, "ERROR: protocol version is too old!\n"); exit_cleanup(RERR_PROTOCOL); } gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; }
164,641
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int y; for (y = 0; y < maskHeight; y++) { maskDest = (unsigned char *) (maskBuffer + y * row_stride); pix = maskImgStr->getLine(); maskColorMap->getGrayLine (pix, maskDest, maskWidth); } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; cairo_matrix_t maskMatrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawSoftMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &maskMatrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_pattern_set_filter (maskPattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; } Commit Message: CWE ID: CWE-189
void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, Stream *maskStr, int maskWidth, int maskHeight, GfxImageColorMap *maskColorMap) { ImageStream *maskImgStr; maskImgStr = new ImageStream(maskStr, maskWidth, maskColorMap->getNumPixelComps(), maskColorMap->getBits()); maskImgStr->reset(); int row_stride = (maskWidth + 3) & ~3; unsigned char *maskBuffer; maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); unsigned char *maskDest; cairo_surface_t *maskImage; cairo_pattern_t *maskPattern; Guchar *pix; int y; for (y = 0; y < maskHeight; y++) { maskDest = (unsigned char *) (maskBuffer + y * row_stride); pix = maskImgStr->getLine(); maskColorMap->getGrayLine (pix, maskDest, maskWidth); } maskImage = cairo_image_surface_create_for_data (maskBuffer, CAIRO_FORMAT_A8, maskWidth, maskHeight, row_stride); delete maskImgStr; maskStr->close(); unsigned char *buffer; unsigned int *dest; cairo_surface_t *image; cairo_pattern_t *pattern; ImageStream *imgStr; cairo_matrix_t matrix; cairo_matrix_t maskMatrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3 (width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24, width, height, width * 4); if (image == NULL) { delete imgStr; return; } pattern = cairo_pattern_create_for_surface (image); maskPattern = cairo_pattern_create_for_surface (maskImage); if (pattern == NULL) { delete imgStr; return; } LOG (printf ("drawSoftMaskedImage %dx%d\n", width, height)); cairo_matrix_init_translate (&matrix, 0, height); cairo_matrix_scale (&matrix, width, -height); cairo_matrix_init_translate (&maskMatrix, 0, maskHeight); cairo_matrix_scale (&maskMatrix, maskWidth, -maskHeight); cairo_pattern_set_matrix (pattern, &matrix); cairo_pattern_set_matrix (maskPattern, &maskMatrix); cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR); cairo_pattern_set_filter (maskPattern, CAIRO_FILTER_BILINEAR); cairo_set_source (cairo, pattern); cairo_mask (cairo, maskPattern); if (cairo_shape) { #if 0 cairo_rectangle (cairo_shape, 0., 0., width, height); cairo_fill (cairo_shape); #else cairo_save (cairo_shape); /* this should draw a rectangle the size of the image * we use this instead of rect,fill because of the lack * of EXTEND_PAD */ /* NOTE: this will multiply the edges of the image twice */ cairo_set_source (cairo_shape, pattern); cairo_mask (cairo_shape, pattern); cairo_restore (cairo_shape); #endif } cairo_pattern_destroy (maskPattern); cairo_surface_destroy (maskImage); cairo_pattern_destroy (pattern); cairo_surface_destroy (image); free (buffer); free (maskBuffer); delete imgStr; }
164,607
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; } Commit Message: xkbcomp: Don't explode on invalid virtual modifiers testcase: 'virtualModifiers=LevelThreC' Signed-off-by: Daniel Stone <[email protected]> CWE ID: CWE-476
LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (!str) return false; if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }
169,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num) { dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; WORD32 ret; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } } H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); ret = ih264d_end_of_pic_processing(ps_dec); if(ret != OK) return ret; ps_dec->u2_total_mbs_coded = 0; /*--------------------------------------------------------------------*/ /* ih264d_decode_pic_order_cnt - calculate the Pic Order Cnt */ /* Needed to detect end of picture */ /*--------------------------------------------------------------------*/ { pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc) ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num; if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5) ps_dec->u2_prev_ref_frame_num = 0; if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag) { ret = ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num); if(ret != OK) return ret; } ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num; ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5; if(ps_cur_slice->u1_nal_ref_idc) { ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field; } } H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; } Commit Message: Decoder: Initialize first_pb_nal_in_pic for error slices first_pb_nal_in_pic was uninitialized for error clips Bug: 29023649 Change-Id: Ie4e0a94059c5f675bf619e31534846e2c2ca58ae CWE ID: CWE-172
WORD32 ih264d_end_of_pic(dec_struct_t *ps_dec, UWORD8 u1_is_idr_slice, UWORD16 u2_frame_num) { dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; WORD32 ret; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; { dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; if(ps_err->u1_err_flag & REJECT_CUR_PIC) { ih264d_err_pic_dispbuf_mgr(ps_dec); return ERROR_NEW_FRAME_EXPECTED; } } H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); ret = ih264d_end_of_pic_processing(ps_dec); if(ret != OK) return ret; ps_dec->u2_total_mbs_coded = 0; /*--------------------------------------------------------------------*/ /* ih264d_decode_pic_order_cnt - calculate the Pic Order Cnt */ /* Needed to detect end of picture */ /*--------------------------------------------------------------------*/ { pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc) ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num; if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5) ps_dec->u2_prev_ref_frame_num = 0; if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag) { ret = ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num); if(ret != OK) return ret; } ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num; ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5; if(ps_cur_slice->u1_nal_ref_idc) { ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0]; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1]; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field; } } H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); return OK; }
173,515
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } } Commit Message: ssl: Validate hostnames Closes #524 CWE ID: CWE-310
ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: { X509 *cert = SSL_get_peer_certificate (serv->ssl); int hostname_err; if ((hostname_err = _SSL_check_hostname(cert, serv->hostname)) != 0) { snprintf (buf, sizeof (buf), "* Verify E: Failed to validate hostname? (%d)%s", hostname_err, serv->accept_invalid_cert ? " -- Ignored" : ""); if (serv->accept_invalid_cert) EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); else goto conn_fail; } break; } /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); conn_fail: EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } }
167,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssi_sd_state *s = (ssi_sd_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->mode = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 4; i++) s->cmdarg[i] = qemu_get_be32(f); for (i = 0; i < 5; i++) s->response[i] = qemu_get_be32(f); s->arglen = qemu_get_be32(f); s->response_pos = qemu_get_be32(f); s->stopping = qemu_get_be32(f); ss->cs = qemu_get_be32(f); s->mode = SSI_SD_CMD; dinfo = drive_get_next(IF_SD); s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true); if (s->sd == NULL) { return -1; } register_savevm(dev, "ssi_sd", -1, 1, ssi_sd_save, ssi_sd_load, s); return 0; } Commit Message: CWE ID: CWE-94
static int ssi_sd_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssi_sd_state *s = (ssi_sd_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->mode = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 4; i++) s->cmdarg[i] = qemu_get_be32(f); for (i = 0; i < 5; i++) s->response[i] = qemu_get_be32(f); s->arglen = qemu_get_be32(f); if (s->mode == SSI_SD_CMDARG && (s->arglen < 0 || s->arglen >= ARRAY_SIZE(s->cmdarg))) { return -EINVAL; } s->response_pos = qemu_get_be32(f); s->stopping = qemu_get_be32(f); if (s->mode == SSI_SD_RESPONSE && (s->response_pos < 0 || s->response_pos >= ARRAY_SIZE(s->response) || (!s->stopping && s->arglen > ARRAY_SIZE(s->response)))) { return -EINVAL; } ss->cs = qemu_get_be32(f); s->mode = SSI_SD_CMD; dinfo = drive_get_next(IF_SD); s->sd = sd_init(dinfo ? dinfo->bdrv : NULL, true); if (s->sd == NULL) { return -1; } register_savevm(dev, "ssi_sd", -1, 1, ssi_sd_save, ssi_sd_load, s); return 0; }
165,358
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } } Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak Syzkaller report this: pcd: pcd version 1.07, major 46, nice 0 pcd0: Autoprobe failed pcd: No CD-ROM drive found kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pcd_init+0x95c/0x1000 [pcd] Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2 RSP: 0018:ffff8881e84df880 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935 RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8 R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000 R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003 FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1508000 ? 0xffffffffc1508000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace d873691c3cd69f56 ]--- If alloc_disk fails in pcd_init_units, cd->disk will be NULL, however in pcd_detect and pcd_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476
static void pcd_init_units(void) { struct pcd_unit *cd; int unit; pcd_drive_count = 0; for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) { struct gendisk *disk = alloc_disk(1); if (!disk) continue; disk->queue = blk_mq_init_sq_queue(&cd->tag_set, &pcd_mq_ops, 1, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disk->queue)) { put_disk(disk); disk->queue = NULL; continue; } INIT_LIST_HEAD(&cd->rq_list); disk->queue->queuedata = cd; blk_queue_bounce_limit(disk->queue, BLK_BOUNCE_HIGH); cd->disk = disk; cd->pi = &cd->pia; cd->present = 0; cd->last_sense = 0; cd->changed = 1; cd->drive = (*drives[unit])[D_SLV]; if ((*drives[unit])[D_PRT]) pcd_drive_count++; cd->name = &cd->info.name[0]; snprintf(cd->name, sizeof(cd->info.name), "%s%d", name, unit); cd->info.ops = &pcd_dops; cd->info.handle = cd; cd->info.speed = 0; cd->info.capacity = 1; cd->info.mask = 0; disk->major = major; disk->first_minor = unit; strcpy(disk->disk_name, cd->name); /* umm... */ disk->fops = &pcd_bdops; disk->flags = GENHD_FL_BLOCK_EVENTS_ON_EXCL_WRITE; } }
169,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FaviconSource::SendDefaultResponse(int request_id) { if (!default_favicon_.get()) { default_favicon_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_FAVICON); } SendResponse(request_id, default_favicon_); } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void FaviconSource::SendDefaultResponse(int request_id) { RefCountedMemory* bytes = NULL; if (request_size_map_[request_id] == 32) { if (!default_favicon_large_.get()) { default_favicon_large_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_LARGE_FAVICON); } bytes = default_favicon_large_; } else { if (!default_favicon_.get()) { default_favicon_ = ResourceBundle::GetSharedInstance().LoadDataResourceBytes( IDR_DEFAULT_FAVICON); } bytes = default_favicon_; } request_size_map_.erase(request_id); SendResponse(request_id, bytes); }
170,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ContentSecurityPolicy::postViolationReport( const SecurityPolicyViolationEventInit& violationData, LocalFrame* contextFrame, const Vector<String>& reportEndpoints) { Document* document = contextFrame ? contextFrame->document() : this->document(); if (!document) return; std::unique_ptr<JSONObject> cspReport = JSONObject::create(); cspReport->setString("document-uri", violationData.documentURI()); cspReport->setString("referrer", violationData.referrer()); cspReport->setString("violated-directive", violationData.violatedDirective()); cspReport->setString("effective-directive", violationData.effectiveDirective()); cspReport->setString("original-policy", violationData.originalPolicy()); cspReport->setString("disposition", violationData.disposition()); cspReport->setString("blocked-uri", violationData.blockedURI()); if (violationData.lineNumber()) cspReport->setInteger("line-number", violationData.lineNumber()); if (violationData.columnNumber()) cspReport->setInteger("column-number", violationData.columnNumber()); if (!violationData.sourceFile().isEmpty()) cspReport->setString("source-file", violationData.sourceFile()); cspReport->setInteger("status-code", violationData.statusCode()); if (experimentalFeaturesEnabled()) cspReport->setString("sample", violationData.sample()); std::unique_ptr<JSONObject> reportObject = JSONObject::create(); reportObject->setObject("csp-report", std::move(cspReport)); String stringifiedReport = reportObject->toJSONString(); if (shouldSendViolationReport(stringifiedReport)) { didSendViolationReport(stringifiedReport); RefPtr<EncodedFormData> report = EncodedFormData::create(stringifiedReport.utf8()); LocalFrame* frame = document->frame(); if (!frame) return; for (const String& endpoint : reportEndpoints) { DCHECK(!contextFrame || !m_executionContext); DCHECK(!contextFrame || getDirectiveType(violationData.effectiveDirective()) == DirectiveType::FrameAncestors); KURL url = contextFrame ? frame->document()->completeURLWithOverride( endpoint, KURL(ParsedURLString, violationData.blockedURI())) : completeURL(endpoint); PingLoader::sendViolationReport( frame, url, report, PingLoader::ContentSecurityPolicyViolationReport); } } } Commit Message: CSP: Strip the fragment from reported URLs. We should have been stripping the fragment from the URL we report for CSP violations, but we weren't. Now we are, by running the URLs through `stripURLForUseInReport()`, which implements the stripping algorithm from CSP2: https://www.w3.org/TR/CSP2/#strip-uri-for-reporting Eventually, we will migrate more completely to the CSP3 world that doesn't require such detailed stripping, as it exposes less data to the reports, but we're not there yet. BUG=678776 Review-Url: https://codereview.chromium.org/2619783002 Cr-Commit-Position: refs/heads/master@{#458045} CWE ID: CWE-200
void ContentSecurityPolicy::postViolationReport( const SecurityPolicyViolationEventInit& violationData, LocalFrame* contextFrame, const Vector<String>& reportEndpoints) { Document* document = contextFrame ? contextFrame->document() : this->document(); if (!document) return; // // TODO(mkwst): This justification is BS. Insecure reports are mixed content, // let's kill them. https://crbug.com/695363 std::unique_ptr<JSONObject> cspReport = JSONObject::create(); cspReport->setString("document-uri", violationData.documentURI()); cspReport->setString("referrer", violationData.referrer()); cspReport->setString("violated-directive", violationData.violatedDirective()); cspReport->setString("effective-directive", violationData.effectiveDirective()); cspReport->setString("original-policy", violationData.originalPolicy()); cspReport->setString("disposition", violationData.disposition()); cspReport->setString("blocked-uri", violationData.blockedURI()); if (violationData.lineNumber()) cspReport->setInteger("line-number", violationData.lineNumber()); if (violationData.columnNumber()) cspReport->setInteger("column-number", violationData.columnNumber()); if (!violationData.sourceFile().isEmpty()) cspReport->setString("source-file", violationData.sourceFile()); cspReport->setInteger("status-code", violationData.statusCode()); if (experimentalFeaturesEnabled()) cspReport->setString("sample", violationData.sample()); std::unique_ptr<JSONObject> reportObject = JSONObject::create(); reportObject->setObject("csp-report", std::move(cspReport)); String stringifiedReport = reportObject->toJSONString(); if (shouldSendViolationReport(stringifiedReport)) { didSendViolationReport(stringifiedReport); RefPtr<EncodedFormData> report = EncodedFormData::create(stringifiedReport.utf8()); LocalFrame* frame = document->frame(); if (!frame) return; for (const String& endpoint : reportEndpoints) { DCHECK(!contextFrame || !m_executionContext); DCHECK(!contextFrame || getDirectiveType(violationData.effectiveDirective()) == DirectiveType::FrameAncestors); KURL url = contextFrame ? frame->document()->completeURLWithOverride( endpoint, KURL(ParsedURLString, violationData.blockedURI())) : completeURL(endpoint); PingLoader::sendViolationReport( frame, url, report, PingLoader::ContentSecurityPolicyViolationReport); } } }
172,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; } Commit Message: Btrfs: make xattr replace operations atomic Replacing a xattr consists of doing a lookup for its existing value, delete the current value from the respective leaf, release the search path and then finally insert the new value. This leaves a time window where readers (getxattr, listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs, so this has security implications. This change also fixes 2 other existing issues which were: *) Deleting the old xattr value without verifying first if the new xattr will fit in the existing leaf item (in case multiple xattrs are packed in the same item due to name hash collision); *) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't exist but we have have an existing item that packs muliple xattrs with the same name hash as the input xattr. In this case we should return ENOSPC. A test case for xfstests follows soon. Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace implementation. Reported-by: Alexandre Oliva <[email protected]> Signed-off-by: Filipe Manana <[email protected]> Signed-off-by: Chris Mason <[email protected]> CWE ID: CWE-362
static struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; }
166,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID:
http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(&hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(&hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); }
169,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btsock_thread_wakeup(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h); return FALSE; } sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0}; return send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0) == sizeof(cmd); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int btsock_thread_wakeup(int h) { if(h < 0 || h >= MAX_THREAD) { APPL_TRACE_ERROR("invalid bt thread handle:%d", h); return FALSE; } if(ts[h].cmd_fdw == -1) { APPL_TRACE_ERROR("thread handle:%d, cmd socket is not created", h); return FALSE; } sock_cmd_t cmd = {CMD_WAKEUP, 0, 0, 0, 0}; return TEMP_FAILURE_RETRY(send(ts[h].cmd_fdw, &cmd, sizeof(cmd), 0)) == sizeof(cmd); }
173,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200
char* problem_data_save(problem_data_t *pd) { load_abrt_conf(); struct dump_dir *dd = NULL; if (g_settings_privatereports) dd = create_dump_dir_from_problem_data_ext(pd, g_settings_dump_location, 0); else dd = create_dump_dir_from_problem_data(pd, g_settings_dump_location); char *problem_id = NULL; if (dd) { problem_id = xstrdup(dd->dd_dirname); dd_close(dd); } log_info("problem id: '%s'", problem_id); return problem_id; }
170,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len, u32 __user *optval, int __user *optlen) { const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk); struct tfrc_tx_info tfrc; const void *val; switch (optname) { case DCCP_SOCKOPT_CCID_TX_INFO: if (len < sizeof(tfrc)) return -EINVAL; tfrc.tfrctx_x = hc->tx_x; tfrc.tfrctx_x_recv = hc->tx_x_recv; tfrc.tfrctx_x_calc = hc->tx_x_calc; tfrc.tfrctx_rtt = hc->tx_rtt; tfrc.tfrctx_p = hc->tx_p; tfrc.tfrctx_rto = hc->tx_t_rto; tfrc.tfrctx_ipi = hc->tx_t_ipi; len = sizeof(tfrc); val = &tfrc; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen) || copy_to_user(optval, val, len)) return -EFAULT; return 0; } Commit Message: dccp: fix info leak via getsockopt(DCCP_SOCKOPT_CCID_TX_INFO) The CCID3 code fails to initialize the trailing padding bytes of struct tfrc_tx_info added for alignment on 64 bit architectures. It that for potentially leaks four bytes kernel stack via the getsockopt() syscall. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Gerrit Renker <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len, u32 __user *optval, int __user *optlen) { const struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk); struct tfrc_tx_info tfrc; const void *val; switch (optname) { case DCCP_SOCKOPT_CCID_TX_INFO: if (len < sizeof(tfrc)) return -EINVAL; memset(&tfrc, 0, sizeof(tfrc)); tfrc.tfrctx_x = hc->tx_x; tfrc.tfrctx_x_recv = hc->tx_x_recv; tfrc.tfrctx_x_calc = hc->tx_x_calc; tfrc.tfrctx_rtt = hc->tx_rtt; tfrc.tfrctx_p = hc->tx_p; tfrc.tfrctx_rto = hc->tx_t_rto; tfrc.tfrctx_ipi = hc->tx_t_ipi; len = sizeof(tfrc); val = &tfrc; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen) || copy_to_user(optval, val, len)) return -EFAULT; return 0; }
166,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool RenderFrameHostManager::CanSubframeSwapProcess( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* dest_instance, bool was_server_redirect) { DCHECK(!source_instance || !dest_instance); GURL resolved_url = dest_url; if (url::Origin::Create(resolved_url).unique()) { if (source_instance) { resolved_url = source_instance->GetSiteURL(); } else if (dest_instance) { resolved_url = dest_instance->GetSiteURL(); } else { if (!was_server_redirect) return false; } } if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(), resolved_url)) { DCHECK(!dest_instance || dest_instance == render_frame_host_->GetSiteInstance()); return false; } return true; } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
bool RenderFrameHostManager::CanSubframeSwapProcess( const GURL& dest_url, SiteInstance* source_instance, SiteInstance* dest_instance) { DCHECK(!source_instance || !dest_instance); GURL resolved_url = dest_url; if (url::Origin::Create(resolved_url).unique()) { if (source_instance) { resolved_url = source_instance->GetSiteURL(); } else if (dest_instance) { resolved_url = dest_instance->GetSiteURL(); } else { // then check whether it is safe to put into the parent frame's process. // This is the case for about:blank URLs (with or without fragments), // since they contain no active data. This is also the case for // about:srcdoc, since such URLs only get active content from their parent // frame. Using the parent frame's process avoids putting blank frames // into OOPIFs and preserves scripting for about:srcdoc. // // Allow a process swap for other unique origin URLs, such as data: URLs. // These have active content and may have come from an untrusted source, // such as a restored frame from a different site or a redirect. // (Normally, redirects to data: or about: URLs are disallowed as // example, see ExtensionWebRequestApiTest.WebRequestDeclarative1).) if (resolved_url.IsAboutBlank() || resolved_url == GURL(content::kAboutSrcDocURL)) { return false; } } } if (!IsRendererTransferNeededForNavigation(render_frame_host_.get(), resolved_url)) { DCHECK(!dest_instance || dest_instance == render_frame_host_->GetSiteInstance()); return false; } return true; }
173,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: recvauth_common(krb5_context context, krb5_auth_context * auth_context, /* IN */ krb5_pointer fd, char *appl_version, krb5_principal server, krb5_int32 flags, krb5_keytab keytab, /* OUT */ krb5_ticket ** ticket, krb5_data *version) { krb5_auth_context new_auth_context; krb5_flags ap_option = 0; krb5_error_code retval, problem; krb5_data inbuf; krb5_data outbuf; krb5_rcache rcache = 0; krb5_octet response; krb5_data null_server; int need_error_free = 0; int local_rcache = 0, local_authcon = 0; /* * Zero out problem variable. If problem is set at the end of * the intial version negotiation section, it means that we * need to send an error code back to the client application * and exit. */ problem = 0; response = 0; if (!(flags & KRB5_RECVAUTH_SKIP_VERSION)) { /* * First read the sendauth version string and check it. */ if ((retval = krb5_read_message(context, fd, &inbuf))) return(retval); if (strcmp(inbuf.data, sendauth_version)) { problem = KRB5_SENDAUTH_BADAUTHVERS; response = 1; } free(inbuf.data); } if (flags & KRB5_RECVAUTH_BADAUTHVERS) { problem = KRB5_SENDAUTH_BADAUTHVERS; response = 1; } /* * Do the same thing for the application version string. */ if ((retval = krb5_read_message(context, fd, &inbuf))) return(retval); if (appl_version && strcmp(inbuf.data, appl_version)) { if (!problem) { problem = KRB5_SENDAUTH_BADAPPLVERS; response = 2; } } if (version && !problem) *version = inbuf; else free(inbuf.data); /* * Now we actually write the response. If the response is non-zero, * exit with a return value of problem */ if ((krb5_net_write(context, *((int *)fd), (char *)&response, 1)) < 0) { return(problem); /* We'll return the top-level problem */ } if (problem) return(problem); /* We are clear of errors here */ /* * Now, let's read the AP_REQ message and decode it */ if ((retval = krb5_read_message(context, fd, &inbuf))) return retval; if (*auth_context == NULL) { problem = krb5_auth_con_init(context, &new_auth_context); *auth_context = new_auth_context; local_authcon = 1; } krb5_auth_con_getrcache(context, *auth_context, &rcache); if ((!problem) && rcache == NULL) { /* * Setup the replay cache. */ if (server != NULL && server->length > 0) { problem = krb5_get_server_rcache(context, &server->data[0], &rcache); } else { null_server.length = 7; null_server.data = "default"; problem = krb5_get_server_rcache(context, &null_server, &rcache); } if (!problem) problem = krb5_auth_con_setrcache(context, *auth_context, rcache); local_rcache = 1; } if (!problem) { problem = krb5_rd_req(context, auth_context, &inbuf, server, keytab, &ap_option, ticket); free(inbuf.data); } /* * If there was a problem, send back a krb5_error message, * preceeded by the length of the krb5_error message. If * everything's ok, send back 0 for the length. */ if (problem) { krb5_error error; const char *message; memset(&error, 0, sizeof(error)); krb5_us_timeofday(context, &error.stime, &error.susec); if(server) error.server = server; else { /* If this fails - ie. ENOMEM we are hosed we cannot even send the error if we wanted to... */ (void) krb5_parse_name(context, "????", &error.server); need_error_free = 1; } error.error = problem - ERROR_TABLE_BASE_krb5; if (error.error > 127) error.error = KRB_ERR_GENERIC; message = error_message(problem); error.text.length = strlen(message) + 1; error.text.data = strdup(message); if (!error.text.data) { retval = ENOMEM; goto cleanup; } if ((retval = krb5_mk_error(context, &error, &outbuf))) { free(error.text.data); goto cleanup; } free(error.text.data); if(need_error_free) krb5_free_principal(context, error.server); } else { outbuf.length = 0; outbuf.data = 0; } retval = krb5_write_message(context, fd, &outbuf); if (outbuf.data) { free(outbuf.data); /* We sent back an error, we need cleanup then return */ retval = problem; goto cleanup; } if (retval) goto cleanup; /* Here lies the mutual authentication stuff... */ if ((ap_option & AP_OPTS_MUTUAL_REQUIRED)) { if ((retval = krb5_mk_rep(context, *auth_context, &outbuf))) { return(retval); } retval = krb5_write_message(context, fd, &outbuf); free(outbuf.data); } cleanup:; if (retval) { if (local_authcon) { krb5_auth_con_free(context, *auth_context); } else if (local_rcache && rcache != NULL) { krb5_rc_close(context, rcache); krb5_auth_con_setrcache(context, *auth_context, NULL); } } return retval; } Commit Message: Fix krb5_read_message handling [CVE-2014-5355] In recvauth_common, do not use strcmp against the data fields of krb5_data objects populated by krb5_read_message(), as there is no guarantee that they are C strings. Instead, create an expected krb5_data value and use data_eq(). In the sample user-to-user server application, check that the received client principal name is null-terminated before using it with printf and krb5_parse_name. CVE-2014-5355: In MIT krb5, when a server process uses the krb5_recvauth function, an unauthenticated remote attacker can cause a NULL dereference by sending a zero-byte version string, or a read beyond the end of allocated storage by sending a non-null-terminated version string. The example user-to-user server application (uuserver) is similarly vulnerable to a zero-length or non-null-terminated principal name string. The krb5_recvauth function reads two version strings from the client using krb5_read_message(), which produces a krb5_data structure containing a length and a pointer to an octet sequence. krb5_recvauth assumes that the data pointer is a valid C string and passes it to strcmp() to verify the versions. If the client sends an empty octet sequence, the data pointer will be NULL and strcmp() will dereference a NULL pointer, causing the process to crash. If the client sends a non-null-terminated octet sequence, strcmp() will read beyond the end of the allocated storage, possibly causing the process to crash. uuserver similarly uses krb5_read_message() to read a client principal name, and then passes it to printf() and krb5_parse_name() without verifying that it is a valid C string. The krb5_recvauth function is used by kpropd and the Kerberized versions of the BSD rlogin and rsh daemons. These daemons are usually run out of inetd or in a mode which forks before processing incoming connections, so a process crash will generally not result in a complete denial of service. Thanks to Tim Uglow for discovering this issue. CVSSv2: AV:N/AC:L/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C [[email protected]: CVSS score] ticket: 8050 (new) target_version: 1.13.1 tags: pullup CWE ID:
recvauth_common(krb5_context context, krb5_auth_context * auth_context, /* IN */ krb5_pointer fd, char *appl_version, krb5_principal server, krb5_int32 flags, krb5_keytab keytab, /* OUT */ krb5_ticket ** ticket, krb5_data *version) { krb5_auth_context new_auth_context; krb5_flags ap_option = 0; krb5_error_code retval, problem; krb5_data inbuf; krb5_data outbuf; krb5_rcache rcache = 0; krb5_octet response; krb5_data null_server; krb5_data d; int need_error_free = 0; int local_rcache = 0, local_authcon = 0; /* * Zero out problem variable. If problem is set at the end of * the intial version negotiation section, it means that we * need to send an error code back to the client application * and exit. */ problem = 0; response = 0; if (!(flags & KRB5_RECVAUTH_SKIP_VERSION)) { /* * First read the sendauth version string and check it. */ if ((retval = krb5_read_message(context, fd, &inbuf))) return(retval); d = make_data((char *)sendauth_version, strlen(sendauth_version) + 1); if (!data_eq(inbuf, d)) { problem = KRB5_SENDAUTH_BADAUTHVERS; response = 1; } free(inbuf.data); } if (flags & KRB5_RECVAUTH_BADAUTHVERS) { problem = KRB5_SENDAUTH_BADAUTHVERS; response = 1; } /* * Do the same thing for the application version string. */ if ((retval = krb5_read_message(context, fd, &inbuf))) return(retval); if (appl_version != NULL && !problem) { d = make_data(appl_version, strlen(appl_version) + 1); if (!data_eq(inbuf, d)) { problem = KRB5_SENDAUTH_BADAPPLVERS; response = 2; } } if (version && !problem) *version = inbuf; else free(inbuf.data); /* * Now we actually write the response. If the response is non-zero, * exit with a return value of problem */ if ((krb5_net_write(context, *((int *)fd), (char *)&response, 1)) < 0) { return(problem); /* We'll return the top-level problem */ } if (problem) return(problem); /* We are clear of errors here */ /* * Now, let's read the AP_REQ message and decode it */ if ((retval = krb5_read_message(context, fd, &inbuf))) return retval; if (*auth_context == NULL) { problem = krb5_auth_con_init(context, &new_auth_context); *auth_context = new_auth_context; local_authcon = 1; } krb5_auth_con_getrcache(context, *auth_context, &rcache); if ((!problem) && rcache == NULL) { /* * Setup the replay cache. */ if (server != NULL && server->length > 0) { problem = krb5_get_server_rcache(context, &server->data[0], &rcache); } else { null_server.length = 7; null_server.data = "default"; problem = krb5_get_server_rcache(context, &null_server, &rcache); } if (!problem) problem = krb5_auth_con_setrcache(context, *auth_context, rcache); local_rcache = 1; } if (!problem) { problem = krb5_rd_req(context, auth_context, &inbuf, server, keytab, &ap_option, ticket); free(inbuf.data); } /* * If there was a problem, send back a krb5_error message, * preceeded by the length of the krb5_error message. If * everything's ok, send back 0 for the length. */ if (problem) { krb5_error error; const char *message; memset(&error, 0, sizeof(error)); krb5_us_timeofday(context, &error.stime, &error.susec); if(server) error.server = server; else { /* If this fails - ie. ENOMEM we are hosed we cannot even send the error if we wanted to... */ (void) krb5_parse_name(context, "????", &error.server); need_error_free = 1; } error.error = problem - ERROR_TABLE_BASE_krb5; if (error.error > 127) error.error = KRB_ERR_GENERIC; message = error_message(problem); error.text.length = strlen(message) + 1; error.text.data = strdup(message); if (!error.text.data) { retval = ENOMEM; goto cleanup; } if ((retval = krb5_mk_error(context, &error, &outbuf))) { free(error.text.data); goto cleanup; } free(error.text.data); if(need_error_free) krb5_free_principal(context, error.server); } else { outbuf.length = 0; outbuf.data = 0; } retval = krb5_write_message(context, fd, &outbuf); if (outbuf.data) { free(outbuf.data); /* We sent back an error, we need cleanup then return */ retval = problem; goto cleanup; } if (retval) goto cleanup; /* Here lies the mutual authentication stuff... */ if ((ap_option & AP_OPTS_MUTUAL_REQUIRED)) { if ((retval = krb5_mk_rep(context, *auth_context, &outbuf))) { return(retval); } retval = krb5_write_message(context, fd, &outbuf); free(outbuf.data); } cleanup:; if (retval) { if (local_authcon) { krb5_auth_con_free(context, *auth_context); } else if (local_rcache && rcache != NULL) { krb5_rc_close(context, rcache); krb5_auth_con_setrcache(context, *auth_context, NULL); } } return retval; }
166,812
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; } Commit Message: (for 4.9.3) LMP: Add some missing bounds checks In lmp_print_data_link_subobjs(), these problems were identified through code review. Moreover: Add and use tstr[]. Update two tests outputs accordingly. CWE ID: CWE-20
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { ND_TCHECK_16BITS(obj_tptr + offset); subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_TCHECK_8BITS(obj_tptr + offset + 2); ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_TCHECK_8BITS(obj_tptr + offset + 3); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); ND_TCHECK_32BITS(obj_tptr + offset + 8); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_TCHECK_32BITS(obj_tptr + offset + 4); ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; }
169,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: __imlib_Ellipse_DrawToData(int xc, int yc, int a, int b, DATA32 color, DATA32 * dst, int dstw, int clx, int cly, int clw, int clh, ImlibOp op, char dst_alpha, char blend) { ImlibPointDrawFunction pfunc; int xx, yy, x, y, prev_x, prev_y, ty, by, lx, rx; DATA32 a2, b2, *tp, *bp; DATA64 dx, dy; if (A_VAL(&color) == 0xff) blend = 0; pfunc = __imlib_GetPointDrawFunction(op, dst_alpha, blend); if (!pfunc) return; xc -= clx; yc -= cly; dst += (dstw * cly) + clx; a2 = a * a; b2 = b * b; yy = b << 16; prev_y = b; dx = a2 * b; dy = 0; ty = yc - b - 1; by = yc + b; lx = xc - 1; rx = xc; tp = dst + (dstw * ty) + lx; bp = dst + (dstw * by) + lx; while (dy < dx) { int len; y = yy >> 16; y += ((yy - (y << 16)) >> 15); if (prev_y != y) { prev_y = y; dx -= a2; ty++; by--; tp += dstw; bp -= dstw; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); dy += b2; yy -= ((dy << 16) / dx); lx--; if ((lx < 0) && (rx > clw)) return; if ((ty > clh) || (by < 0)) return; } xx = yy; prev_x = xx >> 16; dx = dy; ty++; by--; tp += dstw; bp -= dstw; while (ty < yc) { int len; x = xx >> 16; x += ((xx - (x << 16)) >> 15); if (prev_x != x) { prev_x = x; dy += b2; lx--; rx++; tp--; bp--; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); dx -= a2; xx += ((dx << 16) / dy); ty++; if ((ty > clh) || (by < 0)) return; } } Commit Message: CWE ID: CWE-189
__imlib_Ellipse_DrawToData(int xc, int yc, int a, int b, DATA32 color, DATA32 * dst, int dstw, int clx, int cly, int clw, int clh, ImlibOp op, char dst_alpha, char blend) { ImlibPointDrawFunction pfunc; int xx, yy, x, y, prev_x, prev_y, ty, by, lx, rx; DATA32 a2, b2, *tp, *bp; DATA64 dx, dy; if (A_VAL(&color) == 0xff) blend = 0; pfunc = __imlib_GetPointDrawFunction(op, dst_alpha, blend); if (!pfunc) return; xc -= clx; yc -= cly; dst += (dstw * cly) + clx; a2 = a * a; b2 = b * b; yy = b << 16; prev_y = b; dx = a2 * b; dy = 0; ty = yc - b - 1; by = yc + b; lx = xc - 1; rx = xc; tp = dst + (dstw * ty) + lx; bp = dst + (dstw * by) + lx; while (dy < dx) { int len; y = yy >> 16; y += ((yy - (y << 16)) >> 15); if (prev_y != y) { prev_y = y; dx -= a2; ty++; by--; tp += dstw; bp -= dstw; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); if (dx < 1) dx = 1; dy += b2; yy -= ((dy << 16) / dx); lx--; if ((lx < 0) && (rx > clw)) return; if ((ty > clh) || (by < 0)) return; } xx = yy; prev_x = xx >> 16; dx = dy; ty++; by--; tp += dstw; bp -= dstw; while (ty < yc) { int len; x = xx >> 16; x += ((xx - (x << 16)) >> 15); if (prev_x != x) { prev_x = x; dy += b2; lx--; rx++; tp--; bp--; } len = rx - lx; if (IN_RANGE(lx, ty, clw, clh)) pfunc(color, tp); if (IN_RANGE(rx, ty, clw, clh)) pfunc(color, tp + len); if (IN_RANGE(lx, by, clw, clh)) pfunc(color, bp); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); if (IN_RANGE(rx, by, clw, clh)) pfunc(color, bp + len); if (dy < 1) dy = 1; dx -= a2; xx += ((dx << 16) / dy); ty++; if ((ty > clh) || (by < 0)) return; } }
165,344
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ptrace_setxregs(struct task_struct *child, void __user *uregs) { struct thread_info *ti = task_thread_info(child); struct pt_regs *regs = task_pt_regs(child); elf_xtregs_t *xtregs = uregs; int ret = 0; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessors before we overwrite them. */ coprocessor_flush_all(ti); coprocessor_release_all(ti); ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_from_user(&regs->xtregs_opt, &xtregs->opt, sizeof(xtregs->opt)); ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; } Commit Message: xtensa: prevent arbitrary read in ptrace Prevent an arbitrary kernel read. Check the user pointer with access_ok() before copying data in. [[email protected]: s/EIO/EFAULT/] Signed-off-by: Dan Rosenberg <[email protected]> Cc: Christian Zankel <[email protected]> Cc: Oleg Nesterov <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
int ptrace_setxregs(struct task_struct *child, void __user *uregs) { struct thread_info *ti = task_thread_info(child); struct pt_regs *regs = task_pt_regs(child); elf_xtregs_t *xtregs = uregs; int ret = 0; if (!access_ok(VERIFY_READ, uregs, sizeof(elf_xtregs_t))) return -EFAULT; #if XTENSA_HAVE_COPROCESSORS /* Flush all coprocessors before we overwrite them. */ coprocessor_flush_all(ti); coprocessor_release_all(ti); ret |= __copy_from_user(&ti->xtregs_cp, &xtregs->cp0, sizeof(xtregs_coprocessor_t)); #endif ret |= __copy_from_user(&regs->xtregs_opt, &xtregs->opt, sizeof(xtregs->opt)); ret |= __copy_from_user(&ti->xtregs_user, &xtregs->user, sizeof(xtregs->user)); return ret ? -EFAULT : 0; }
165,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Get(const std::string& addr, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(addr); if (it == map_.end()) return false; *out_value = it->second; return true; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
bool Get(const std::string& addr, int* out_value) { // Gets the value for |preview_id|. // Returns true and sets |out_value| on success. bool Get(int32 preview_id, int* out_value) { base::AutoLock lock(lock_); PrintPreviewRequestIdMap::const_iterator it = map_.find(preview_id); if (it == map_.end()) return false; *out_value = it->second; return true; }
170,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; s = tcp_recv(NULL, 4); if (s == NULL) return False; if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; s = tcp_recv(s, length); if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; in_uint8s(s, length); if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; token->end = token->p = token->data; out_uint8p(token, s->p, length); s_mark_end(token); } if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; struct stream packet; s = tcp_recv(NULL, 4); if (s == NULL) return False; if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; s = tcp_recv(s, length); packet = *s; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of version from stream would overrun", &packet); } in_uint8s(s, length); if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of token from stream would overrun", &packet); } s_realloc(token, length); s_reset(token); out_uint8p(token, s->p, length); s_mark_end(token); } if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; }
169,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m1[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: convert_to_double_ex(tmp); m2[i] = Z_DVAL_PP(tmp); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageaffinematrixconcat) { double m1[6]; double m2[6]; double mr[6]; zval **tmp; zval *z_m1; zval *z_m2; int i, nelems; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "aa", &z_m1, &z_m2) == FAILURE) { return; } if (((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m1))) != 6) || (nelems = zend_hash_num_elements(Z_ARRVAL_P(z_m2))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine arrays must have six elements"); RETURN_FALSE; } for (i = 0; i < 6; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_m1), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m1[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m1[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m1[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } if (zend_hash_index_find(Z_ARRVAL_P(z_m2), i, (void **) &tmp) == SUCCESS) { switch (Z_TYPE_PP(tmp)) { case IS_LONG: m2[i] = Z_LVAL_PP(tmp); break; case IS_DOUBLE: m2[i] = Z_DVAL_PP(tmp); break; case IS_STRING: { zval dval; dval = **tmp; zval_copy_ctor(&dval); convert_to_double(&dval); m2[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (gdAffineConcat (mr, m1, m2) != GD_TRUE) { RETURN_FALSE; } array_init(return_value); for (i = 0; i < 6; i++) { add_index_double(return_value, i, mr[i]); } }
166,430
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); struct zip_stat sb; struct zip_file *zf; zend_long index = -1; zend_long flags = 0; zend_long len = 0; zend_string *filename; zend_string *buffer; int n = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); } if (sb.size < 1) { RETURN_EMPTY_STRING(); } if (len < 1) { len = sb.size; } if (index >= 0) { zf = zip_fopen_index(intern, index, flags); } else { zf = zip_fopen(intern, ZSTR_VAL(filename), flags); } if (zf == NULL) { RETURN_FALSE; } buffer = zend_string_alloc(len, 0); n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n < 1) { zend_string_free(buffer); RETURN_EMPTY_STRING(); } zip_fclose(zf); ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } /* }}} */ Commit Message: Fix bug #71923 - integer overflow in ZipArchive::getFrom* CWE ID: CWE-190
static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); struct zip_stat sb; struct zip_file *zf; zend_long index = -1; zend_long flags = 0; zend_long len = 0; zend_string *filename; zend_string *buffer; int n = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); } if (sb.size < 1) { RETURN_EMPTY_STRING(); } if (len < 1) { len = sb.size; } if (index >= 0) { zf = zip_fopen_index(intern, index, flags); } else { zf = zip_fopen(intern, ZSTR_VAL(filename), flags); } if (zf == NULL) { RETURN_FALSE; } buffer = zend_string_safe_alloc(1, len, 0, 0); n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n < 1) { zend_string_free(buffer); RETURN_EMPTY_STRING(); } zip_fclose(zf); ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } /* }}} */
167,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_copyright(png_structp png_ptr) { PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef PNG_STRING_COPYRIGHT return PNG_STRING_COPYRIGHT #else #ifdef __STDC__ return ((png_charp) PNG_STRING_NEWLINE \ "libpng version 1.2.52 - November 20, 2014" PNG_STRING_NEWLINE \ "Copyright (c) 1998-2014 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \ "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \ PNG_STRING_NEWLINE); #else return ((png_charp) "libpng version 1.2.52 - November 20, 2014\ Copyright (c) 1998-2014 Glenn Randers-Pehrson\ Copyright (c) 1996-1997 Andreas Dilger\ Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc."); #endif #endif } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_copyright(png_structp png_ptr) { PNG_UNUSED(png_ptr) /* Silence compiler warning about unused png_ptr */ #ifdef PNG_STRING_COPYRIGHT return PNG_STRING_COPYRIGHT #else #ifdef __STDC__ return ((png_charp) PNG_STRING_NEWLINE \ "libpng version 1.2.54 - November 12, 2015" PNG_STRING_NEWLINE \ "Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \ "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \ "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \ PNG_STRING_NEWLINE); #else return ((png_charp) "libpng version 1.2.54 - November 12, 2015\ Copyright (c) 1998-2015 Glenn Randers-Pehrson\ Copyright (c) 1996-1997 Andreas Dilger\ Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc."); #endif #endif }
172,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; } Commit Message: Prevent KDC unset status assertion failures Assign status values if S4U2Self padata fails to decode, if an S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request uses an evidence ticket which does not match the canonicalized request server principal name. Reported by Samuel Cabrero. If a status value is not assigned during KDC processing, default to "UNKNOWN_REASON" rather than failing an assertion. This change will prevent future denial of service bugs due to similar mistakes, and will allow us to omit assigning status values for unlikely errors such as small memory allocation failures. CVE-2017-11368: In MIT krb5 1.7 and later, an authenticated attacker can cause an assertion failure in krb5kdc by sending an invalid S4U2Self or S4U2Proxy request. CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C ticket: 8599 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-617
kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) { *status = "DECODE_PA_FOR_USER"; return code; } code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; }
168,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) { s->avctx->profile = get_bits(gb, 4); s->avctx->level = get_bits(gb, 4); if (s->avctx->profile == 0 && s->avctx->level == 8) { s->avctx->level = 0; } return 0; } Commit Message: avcodec/mpeg4videodec: Check read profile before setting it Fixes: null pointer dereference Fixes: ffmpeg_crash_7.avi Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb) static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level) { *profile = get_bits(gb, 4); *level = get_bits(gb, 4); if (*profile == 0 && *level == 8) { *level = 0; } return 0; }
169,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; LutContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; AVFrame *out; uint8_t *inrow, *outrow, *inrow0, *outrow0; int i, j, plane, direct = 0; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } if (s->is_rgb) { /* packed */ inrow0 = in ->data[0]; outrow0 = out->data[0]; for (i = 0; i < in->height; i ++) { int w = inlink->w; const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut; inrow = inrow0; outrow = outrow0; for (j = 0; j < w; j++) { switch (s->step) { case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through default: outrow[0] = tab[0][inrow[0]]; } outrow += s->step; inrow += s->step; } inrow0 += in ->linesize[0]; outrow0 += out->linesize[0]; } } else { /* planar */ for (plane = 0; plane < 4 && in->data[plane]; plane++) { int vsub = plane == 1 || plane == 2 ? s->vsub : 0; int hsub = plane == 1 || plane == 2 ? s->hsub : 0; int h = FF_CEIL_RSHIFT(inlink->h, vsub); int w = FF_CEIL_RSHIFT(inlink->w, hsub); inrow = in ->data[plane]; outrow = out->data[plane]; for (i = 0; i < h; i++) { const uint8_t *tab = s->lut[plane]; for (j = 0; j < w; j++) outrow[j] = tab[inrow[j]]; inrow += in ->linesize[plane]; outrow += out->linesize[plane]; } } } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; LutContext *s = ctx->priv; AVFilterLink *outlink = ctx->outputs[0]; AVFrame *out; uint8_t *inrow, *outrow, *inrow0, *outrow0; int i, j, plane, direct = 0; if (av_frame_is_writable(in)) { direct = 1; out = in; } else { out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); } if (s->is_rgb) { /* packed */ inrow0 = in ->data[0]; outrow0 = out->data[0]; for (i = 0; i < in->height; i ++) { int w = inlink->w; const uint8_t (*tab)[256] = (const uint8_t (*)[256])s->lut; inrow = inrow0; outrow = outrow0; for (j = 0; j < w; j++) { switch (s->step) { case 4: outrow[3] = tab[3][inrow[3]]; // Fall-through case 3: outrow[2] = tab[2][inrow[2]]; // Fall-through case 2: outrow[1] = tab[1][inrow[1]]; // Fall-through default: outrow[0] = tab[0][inrow[0]]; } outrow += s->step; inrow += s->step; } inrow0 += in ->linesize[0]; outrow0 += out->linesize[0]; } } else { /* planar */ for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) { int vsub = plane == 1 || plane == 2 ? s->vsub : 0; int hsub = plane == 1 || plane == 2 ? s->hsub : 0; int h = FF_CEIL_RSHIFT(inlink->h, vsub); int w = FF_CEIL_RSHIFT(inlink->w, hsub); inrow = in ->data[plane]; outrow = out->data[plane]; for (i = 0; i < h; i++) { const uint8_t *tab = s->lut[plane]; for (j = 0; j < w; j++) outrow[j] = tab[inrow[j]]; inrow += in ->linesize[plane]; outrow += out->linesize[plane]; } } } if (!direct) av_frame_free(&in); return ff_filter_frame(outlink, out); }
166,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: send_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_streams; struct iperf_stream *sp; cJSON *j_stream; int sender_has_retransmits; iperf_size_t bytes_transferred; int retransmits; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddFloatToObject(j, "cpu_util_total", test->cpu_util[0]); cJSON_AddFloatToObject(j, "cpu_util_user", test->cpu_util[1]); cJSON_AddFloatToObject(j, "cpu_util_system", test->cpu_util[2]); if ( ! test->sender ) sender_has_retransmits = -1; else sender_has_retransmits = test->sender_has_retransmits; cJSON_AddIntToObject(j, "sender_has_retransmits", sender_has_retransmits); /* If on the server and sending server output, then do this */ if (test->role == 's' && test->get_server_output) { if (test->json_output) { /* Add JSON output */ cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top); } else { /* Add textual output */ size_t buflen = 0; /* Figure out how much room we need to hold the complete output string */ struct iperf_textline *t; TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { buflen += strlen(t->line); } /* Allocate and build it up from the component lines */ char *output = calloc(buflen + 1, 1); TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { strncat(output, t->line, buflen); buflen -= strlen(t->line); } cJSON_AddStringToObject(j, "server_output_text", output); } } j_streams = cJSON_CreateArray(); if (j_streams == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToObject(j, "streams", j_streams); SLIST_FOREACH(sp, &test->streams, streams) { j_stream = cJSON_CreateObject(); if (j_stream == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToArray(j_streams, j_stream); bytes_transferred = test->sender ? sp->result->bytes_sent : sp->result->bytes_received; retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1; cJSON_AddIntToObject(j_stream, "id", sp->id); cJSON_AddIntToObject(j_stream, "bytes", bytes_transferred); cJSON_AddIntToObject(j_stream, "retransmits", retransmits); cJSON_AddFloatToObject(j_stream, "jitter", sp->jitter); cJSON_AddIntToObject(j_stream, "errors", sp->cnt_error); cJSON_AddIntToObject(j_stream, "packets", sp->packet_count); } } if (r == 0 && test->debug) { printf("send_results\n%s\n", cJSON_Print(j)); } if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDRESULTS; r = -1; } } cJSON_Delete(j); } return r; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
send_results(struct iperf_test *test) { int r = 0; cJSON *j; cJSON *j_streams; struct iperf_stream *sp; cJSON *j_stream; int sender_has_retransmits; iperf_size_t bytes_transferred; int retransmits; j = cJSON_CreateObject(); if (j == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddNumberToObject(j, "cpu_util_total", test->cpu_util[0]); cJSON_AddNumberToObject(j, "cpu_util_user", test->cpu_util[1]); cJSON_AddNumberToObject(j, "cpu_util_system", test->cpu_util[2]); if ( ! test->sender ) sender_has_retransmits = -1; else sender_has_retransmits = test->sender_has_retransmits; cJSON_AddNumberToObject(j, "sender_has_retransmits", sender_has_retransmits); /* If on the server and sending server output, then do this */ if (test->role == 's' && test->get_server_output) { if (test->json_output) { /* Add JSON output */ cJSON_AddItemReferenceToObject(j, "server_output_json", test->json_top); } else { /* Add textual output */ size_t buflen = 0; /* Figure out how much room we need to hold the complete output string */ struct iperf_textline *t; TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { buflen += strlen(t->line); } /* Allocate and build it up from the component lines */ char *output = calloc(buflen + 1, 1); TAILQ_FOREACH(t, &(test->server_output_list), textlineentries) { strncat(output, t->line, buflen); buflen -= strlen(t->line); } cJSON_AddStringToObject(j, "server_output_text", output); } } j_streams = cJSON_CreateArray(); if (j_streams == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToObject(j, "streams", j_streams); SLIST_FOREACH(sp, &test->streams, streams) { j_stream = cJSON_CreateObject(); if (j_stream == NULL) { i_errno = IEPACKAGERESULTS; r = -1; } else { cJSON_AddItemToArray(j_streams, j_stream); bytes_transferred = test->sender ? sp->result->bytes_sent : sp->result->bytes_received; retransmits = (test->sender && test->sender_has_retransmits) ? sp->result->stream_retrans : -1; cJSON_AddNumberToObject(j_stream, "id", sp->id); cJSON_AddNumberToObject(j_stream, "bytes", bytes_transferred); cJSON_AddNumberToObject(j_stream, "retransmits", retransmits); cJSON_AddNumberToObject(j_stream, "jitter", sp->jitter); cJSON_AddNumberToObject(j_stream, "errors", sp->cnt_error); cJSON_AddNumberToObject(j_stream, "packets", sp->packet_count); } } if (r == 0 && test->debug) { printf("send_results\n%s\n", cJSON_Print(j)); } if (r == 0 && JSON_write(test->ctrl_sck, j) < 0) { i_errno = IESENDRESULTS; r = -1; } } cJSON_Delete(j); } return r; }
167,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const BlockEntry* Track::GetEOS() const { return &m_eos; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const BlockEntry* Track::GetEOS() const
174,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user) { struct net_device *dev = skb->dev; int fhoff, nhoff, ret; struct frag_hdr *fhdr; struct frag_queue *fq; struct ipv6hdr *hdr; u8 prevhdr; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return -EINVAL; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return -EINVAL; if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr))) return -ENOMEM; skb_set_transport_header(skb, fhoff); hdr = ipv6_hdr(skb); fhdr = (struct frag_hdr *)skb_transport_header(skb); fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr, skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr)); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); return -ENOMEM; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) { ret = -EINVAL; goto out_unlock; } /* after queue has assumed skb ownership, only 0 or -EINPROGRESS * must be returned. */ ret = -EINPROGRESS; if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len && nf_ct_frag6_reasm(fq, skb, dev)) ret = 0; out_unlock: spin_unlock_bh(&fq->q.lock); inet_frag_put(&fq->q, &nf_frags); return ret; } Commit Message: netfilter: ipv6: nf_defrag: drop mangled skb on ream error Dmitry Vyukov reported GPF in network stack that Andrey traced down to negative nh offset in nf_ct_frag6_queue(). Problem is that all network headers before fragment header are pulled. Normal ipv6 reassembly will drop the skb when errors occur further down the line. netfilter doesn't do this, and instead passed the original fragment along. That was also fine back when netfilter ipv6 defrag worked with cloned fragments, as the original, pristine fragment was passed on. So we either have to undo the pull op, or discard such fragments. Since they're malformed after all (e.g. overlapping fragment) it seems preferrable to just drop them. Same for temporary errors -- it doesn't make sense to accept (and perhaps forward!) only some fragments of same datagram. Fixes: 029f7f3b8701cc7ac ("netfilter: ipv6: nf_defrag: avoid/free clone operations") Reported-by: Dmitry Vyukov <[email protected]> Debugged-by: Andrey Konovalov <[email protected]> Diagnosed-by: Eric Dumazet <Eric Dumazet <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-787
int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user) { struct net_device *dev = skb->dev; int fhoff, nhoff, ret; struct frag_hdr *fhdr; struct frag_queue *fq; struct ipv6hdr *hdr; u8 prevhdr; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return 0; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return 0; if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr))) return -ENOMEM; skb_set_transport_header(skb, fhoff); hdr = ipv6_hdr(skb); fhdr = (struct frag_hdr *)skb_transport_header(skb); fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr, skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr)); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); return -ENOMEM; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) { ret = -EINVAL; goto out_unlock; } /* after queue has assumed skb ownership, only 0 or -EINPROGRESS * must be returned. */ ret = -EINPROGRESS; if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len && nf_ct_frag6_reasm(fq, skb, dev)) ret = 0; out_unlock: spin_unlock_bh(&fq->q.lock); inet_frag_put(&fq->q, &nf_frags); return ret; }
166,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothOptionsHandler::DeviceNotification( const DictionaryValue& device) { web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", device); } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::DeviceNotification( void BluetoothOptionsHandler::SendDeviceNotification( chromeos::BluetoothDevice* device, base::DictionaryValue* params) { // Retrieve properties of the bluetooth device. The properties names are // in title case. Convert to camel case in accordance with our Javascript // naming convention. const DictionaryValue& properties = device->AsDictionary(); base::DictionaryValue js_properties; for (DictionaryValue::key_iterator it = properties.begin_keys(); it != properties.end_keys(); ++it) { base::Value* child = NULL; properties.GetWithoutPathExpansion(*it, &child); if (child) { std::string js_key = *it; js_key[0] = tolower(js_key[0]); js_properties.SetWithoutPathExpansion(js_key, child->DeepCopy()); } } if (params) { js_properties.MergeDictionary(params); } web_ui_->CallJavascriptFunction( "options.SystemOptions.addBluetoothDevice", js_properties); }
170,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: double ConvolverNode::latencyTime() const { return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0; } Commit Message: Fix threading races on ConvolverNode::m_reverb in ConvolverNode::latencyFrames() According to the crash report (https://cluster-fuzz.appspot.com/testcase?key=6515787040817152), ConvolverNode::m_reverb races between ConvolverNode::latencyFrames() and ConvolverNode::setBuffer(). This CL adds a proper lock for ConvolverNode::m_reverb. BUG=223962 No tests because the crash depends on threading races and thus not reproducible. Review URL: https://chromiumcodereview.appspot.com/23514037 git-svn-id: svn://svn.chromium.org/blink/trunk@157245 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
double ConvolverNode::latencyTime() const { MutexTryLocker tryLocker(m_processLock); if (tryLocker.locked()) return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0; // Since we don't want to block the Audio Device thread, we return a large value // instead of trying to acquire the lock. return std::numeric_limits<double>::infinity(); }
171,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if ((num_pages != size) || (num_pages > MAX_SKB_FRAGS - skb_shinfo(skb)->nr_frags)) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; } Commit Message: macvtap: zerocopy: validate vectors before building skb There're several reasons that the vectors need to be validated: - Return error when caller provides vectors whose num is greater than UIO_MAXIOV. - Linearize part of skb when userspace provides vectors grater than MAX_SKB_FRAGS. - Return error when userspace provides vectors whose total length may exceed - MAX_SKB_FRAGS * PAGE_SIZE. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: Michael S. Tsirkin <[email protected]> CWE ID: CWE-119
static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; if (i + size > MAX_SKB_FRAGS) return -EMSGSIZE; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if (num_pages != size) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; }
166,205
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TestCompletionCallback() : callback_(base::Bind(&TestCompletionCallback::SetResult, base::Unretained(this))) {} Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Taiju Tsuiki <[email protected]> Cr-Commit-Position: refs/heads/master@{#478549} CWE ID:
TestCompletionCallback()
171,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { vp9_worker_init(&worker_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { vpx_get_worker_interface()->init(&worker_); }
174,599
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NTPResourceCache::CreateNewTabHTML() { PrefService* prefs = profile_->GetPrefs(); base::DictionaryValue load_time_data; load_time_data.SetBoolean("bookmarkbarattached", prefs->GetBoolean(prefs::kShowBookmarkBar)); load_time_data.SetBoolean("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION)); load_time_data.SetBoolean("showMostvisited", should_show_most_visited_page_); load_time_data.SetBoolean("showAppLauncherPromo", ShouldShowAppLauncherPromo()); load_time_data.SetBoolean("showRecentlyClosed", should_show_recently_closed_menu_); load_time_data.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); load_time_data.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); load_time_data.SetString("suggestions", l10n_util::GetStringUTF16(IDS_NEW_TAB_SUGGESTIONS)); load_time_data.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); load_time_data.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); load_time_data.SetString("webStoreTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)); load_time_data.SetString("webStoreTitleShort", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE_SHORT)); load_time_data.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); load_time_data.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); load_time_data.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); load_time_data.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); load_time_data.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); load_time_data.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); load_time_data.SetString("appuninstall", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); load_time_data.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); load_time_data.SetString("appdetails", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DETAILS)); load_time_data.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); load_time_data.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); load_time_data.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); load_time_data.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); load_time_data.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); load_time_data.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); load_time_data.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); load_time_data.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); load_time_data.SetBoolean("shouldShowSyncLogin", NTPLoginHandler::ShouldShow(profile_)); load_time_data.SetString("otherSessions", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LABEL)); load_time_data.SetString("otherSessionsEmpty", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EMPTY)); load_time_data.SetString("otherSessionsLearnMoreUrl", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LEARN_MORE_URL)); load_time_data.SetString("learnMore", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("webStoreLink", GetUrlWithLang(GURL(extension_urls::GetWebstoreLaunchURL()))); load_time_data.SetString("appInstallHintText", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_INSTALL_HINT_LABEL)); load_time_data.SetBoolean("isDiscoveryInNTPEnabled", NewTabUI::IsDiscoveryInNTPEnabled()); load_time_data.SetString("collapseSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION)); load_time_data.SetString("expandSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION)); load_time_data.SetString("restoreSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL)); load_time_data.SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("tile_grid_screenreader_accessible_description", l10n_util::GetStringUTF16(IDS_NEW_TAB_TILE_GRID_ACCESSIBLE_DESCRIPTION)); load_time_data.SetString("page_switcher_change_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_CHANGE_TITLE)); load_time_data.SetString("page_switcher_same_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_SAME_TITLE)); load_time_data.SetString("appsPromoTitle", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_APPS_PROMO_TITLE)); load_time_data.SetBoolean("isSwipeTrackingFromScrollEventsEnabled", is_swipe_tracking_from_scroll_events_enabled_); if (profile_->IsManaged()) should_show_apps_page_ = false; load_time_data.SetBoolean("showApps", should_show_apps_page_); load_time_data.SetBoolean("showWebStoreIcon", !prefs->GetBoolean(prefs::kHideWebStoreIcon)); bool streamlined_hosted_apps = CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableStreamlinedHostedApps); load_time_data.SetBoolean("enableStreamlinedHostedApps", streamlined_hosted_apps); if (streamlined_hosted_apps) { load_time_data.SetString("applaunchtypetab", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_TAB)); } #if defined(OS_MACOSX) load_time_data.SetBoolean( "disableCreateAppShortcut", CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppShims)); #endif #if defined(OS_CHROMEOS) load_time_data.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &load_time_data); NTPLoginHandler::GetLocalizedValues(profile_, &load_time_data); webui::SetFontAndTextDirection(&load_time_data); load_time_data.SetBoolean("anim", gfx::Animation::ShouldRenderRichAnimation()); ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); int alignment = tp->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT); load_time_data.SetString("themegravity", (alignment & ThemeProperties::ALIGN_RIGHT) ? "right" : ""); if (first_run::IsChromeFirstRun()) { NotificationPromo::HandleClosed(NotificationPromo::NTP_NOTIFICATION_PROMO); } else { NotificationPromo notification_promo; notification_promo.InitFromPrefs(NotificationPromo::NTP_NOTIFICATION_PROMO); if (notification_promo.CanShow()) { load_time_data.SetString("notificationPromoText", notification_promo.promo_text()); DVLOG(1) << "Notification promo:" << notification_promo.promo_text(); } NotificationPromo bubble_promo; bubble_promo.InitFromPrefs(NotificationPromo::NTP_BUBBLE_PROMO); if (bubble_promo.CanShow()) { load_time_data.SetString("bubblePromoText", bubble_promo.promo_text()); DVLOG(1) << "Bubble promo:" << bubble_promo.promo_text(); } } bool show_other_sessions_menu = should_show_other_devices_menu_ && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableNTPOtherSessionsMenu); load_time_data.SetBoolean("showOtherSessionsMenu", show_other_sessions_menu); load_time_data.SetBoolean("isUserSignedIn", !prefs->GetString(prefs::kGoogleServicesUsername).empty()); base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); webui::UseVersion2 version2; std::string full_html = webui::GetI18nTemplateHtml(new_tab_html, &load_time_data); new_tab_html_ = base::RefCountedString::TakeString(&full_html); } Commit Message: Remove --disable-app-shims. App shims have been enabled by default for 3 milestones (since r242711). BUG=350161 Review URL: https://codereview.chromium.org/298953002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void NTPResourceCache::CreateNewTabHTML() { PrefService* prefs = profile_->GetPrefs(); base::DictionaryValue load_time_data; load_time_data.SetBoolean("bookmarkbarattached", prefs->GetBoolean(prefs::kShowBookmarkBar)); load_time_data.SetBoolean("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION)); load_time_data.SetBoolean("showMostvisited", should_show_most_visited_page_); load_time_data.SetBoolean("showAppLauncherPromo", ShouldShowAppLauncherPromo()); load_time_data.SetBoolean("showRecentlyClosed", should_show_recently_closed_menu_); load_time_data.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); load_time_data.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); load_time_data.SetString("suggestions", l10n_util::GetStringUTF16(IDS_NEW_TAB_SUGGESTIONS)); load_time_data.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); load_time_data.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); load_time_data.SetString("webStoreTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)); load_time_data.SetString("webStoreTitleShort", l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE_SHORT)); load_time_data.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); load_time_data.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); load_time_data.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); load_time_data.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); load_time_data.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); load_time_data.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); load_time_data.SetString("appuninstall", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); load_time_data.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); load_time_data.SetString("appdetails", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DETAILS)); load_time_data.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); load_time_data.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); load_time_data.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); load_time_data.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); load_time_data.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); load_time_data.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); load_time_data.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); load_time_data.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); load_time_data.SetBoolean("shouldShowSyncLogin", NTPLoginHandler::ShouldShow(profile_)); load_time_data.SetString("otherSessions", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LABEL)); load_time_data.SetString("otherSessionsEmpty", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EMPTY)); load_time_data.SetString("otherSessionsLearnMoreUrl", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_LEARN_MORE_URL)); load_time_data.SetString("learnMore", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("webStoreLink", GetUrlWithLang(GURL(extension_urls::GetWebstoreLaunchURL()))); load_time_data.SetString("appInstallHintText", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_INSTALL_HINT_LABEL)); load_time_data.SetBoolean("isDiscoveryInNTPEnabled", NewTabUI::IsDiscoveryInNTPEnabled()); load_time_data.SetString("collapseSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_COLLAPSE_SESSION)); load_time_data.SetString("expandSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_EXPAND_SESSION)); load_time_data.SetString("restoreSessionMenuItemText", l10n_util::GetStringUTF16(IDS_NEW_TAB_OTHER_SESSIONS_OPEN_ALL)); load_time_data.SetString("learn_more", l10n_util::GetStringUTF16(IDS_LEARN_MORE)); load_time_data.SetString("tile_grid_screenreader_accessible_description", l10n_util::GetStringUTF16(IDS_NEW_TAB_TILE_GRID_ACCESSIBLE_DESCRIPTION)); load_time_data.SetString("page_switcher_change_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_CHANGE_TITLE)); load_time_data.SetString("page_switcher_same_title", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_SWITCHER_SAME_TITLE)); load_time_data.SetString("appsPromoTitle", l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_APPS_PROMO_TITLE)); load_time_data.SetBoolean("isSwipeTrackingFromScrollEventsEnabled", is_swipe_tracking_from_scroll_events_enabled_); if (profile_->IsManaged()) should_show_apps_page_ = false; load_time_data.SetBoolean("showApps", should_show_apps_page_); load_time_data.SetBoolean("showWebStoreIcon", !prefs->GetBoolean(prefs::kHideWebStoreIcon)); bool streamlined_hosted_apps = CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableStreamlinedHostedApps); load_time_data.SetBoolean("enableStreamlinedHostedApps", streamlined_hosted_apps); if (streamlined_hosted_apps) { load_time_data.SetString("applaunchtypetab", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_TAB)); } #if defined(OS_CHROMEOS) load_time_data.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &load_time_data); NTPLoginHandler::GetLocalizedValues(profile_, &load_time_data); webui::SetFontAndTextDirection(&load_time_data); load_time_data.SetBoolean("anim", gfx::Animation::ShouldRenderRichAnimation()); ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); int alignment = tp->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT); load_time_data.SetString("themegravity", (alignment & ThemeProperties::ALIGN_RIGHT) ? "right" : ""); if (first_run::IsChromeFirstRun()) { NotificationPromo::HandleClosed(NotificationPromo::NTP_NOTIFICATION_PROMO); } else { NotificationPromo notification_promo; notification_promo.InitFromPrefs(NotificationPromo::NTP_NOTIFICATION_PROMO); if (notification_promo.CanShow()) { load_time_data.SetString("notificationPromoText", notification_promo.promo_text()); DVLOG(1) << "Notification promo:" << notification_promo.promo_text(); } NotificationPromo bubble_promo; bubble_promo.InitFromPrefs(NotificationPromo::NTP_BUBBLE_PROMO); if (bubble_promo.CanShow()) { load_time_data.SetString("bubblePromoText", bubble_promo.promo_text()); DVLOG(1) << "Bubble promo:" << bubble_promo.promo_text(); } } bool show_other_sessions_menu = should_show_other_devices_menu_ && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableNTPOtherSessionsMenu); load_time_data.SetBoolean("showOtherSessionsMenu", show_other_sessions_menu); load_time_data.SetBoolean("isUserSignedIn", !prefs->GetString(prefs::kGoogleServicesUsername).empty()); base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); webui::UseVersion2 version2; std::string full_html = webui::GetI18nTemplateHtml(new_tab_html, &load_time_data); new_tab_html_ = base::RefCountedString::TakeString(&full_html); }
171,148
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key_restriction *restrict_link) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->index_key.description) goto no_memory_3; refcount_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; key->restrict_link = restrict_link; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_BUILT_IN) key->flags |= 1 << KEY_FLAG_BUILTIN; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; } Commit Message: KEYS: prevent creating a different user's keyrings It was possible for an unprivileged user to create the user and user session keyrings for another user. For example: sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u keyctl add keyring _uid_ses.4000 "" @u sleep 15' & sleep 1 sudo -u '#4000' keyctl describe @u sudo -u '#4000' keyctl describe @us This is problematic because these "fake" keyrings won't have the right permissions. In particular, the user who created them first will own them and will have full access to them via the possessor permissions, which can be used to compromise the security of a user's keys: -4: alswrv-----v------------ 3000 0 keyring: _uid.4000 -5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000 Fix it by marking user and user session keyrings with a flag KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session keyring by name, skip all keyrings that don't have the flag set. Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed") Cc: <[email protected]> [v2.6.26+] Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID:
struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key_restriction *restrict_link) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->index_key.description) goto no_memory_3; refcount_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; key->restrict_link = restrict_link; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_BUILT_IN) key->flags |= 1 << KEY_FLAG_BUILTIN; if (flags & KEY_ALLOC_UID_KEYRING) key->flags |= 1 << KEY_FLAG_UID_KEYRING; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; }
169,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime) { static PNG_CONST char short_months[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if (png_ptr == NULL) return (NULL); if (png_ptr->time_buffer == NULL) { png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29* png_sizeof(char))); } #ifdef _WIN32_WCE { wchar_t time_buf[29]; wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"), ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29, NULL, NULL); } #else #ifdef USE_FAR_KEYWORD { char near_time_buf[29]; png_snprintf6(near_time_buf, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); png_memcpy(png_ptr->time_buffer, near_time_buf, 29*png_sizeof(char)); } #else png_snprintf6(png_ptr->time_buffer, 29, "%d %s %d %02d:%02d:%02d +0000", ptime->day % 32, short_months[(ptime->month - 1U) % 12], ptime->year, ptime->hour % 24, ptime->minute % 60, ptime->second % 61); #endif #endif /* _WIN32_WCE */ return ((png_charp)png_ptr->time_buffer); }
172,161
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, web_gl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
PassRefPtr<DrawingBuffer> DrawingBuffer::Create( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, Client* client, const IntSize& size, bool premultiplied_alpha, bool want_alpha_channel, bool want_depth_buffer, bool want_stencil_buffer, bool want_antialiasing, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) { DCHECK(context_provider); if (g_should_fail_drawing_buffer_creation_for_testing) { g_should_fail_drawing_buffer_creation_for_testing = false; return nullptr; } std::unique_ptr<Extensions3DUtil> extensions_util = Extensions3DUtil::Create(context_provider->ContextGL()); if (!extensions_util->IsValid()) { return nullptr; } DCHECK(extensions_util->SupportsExtension("GL_OES_packed_depth_stencil")); extensions_util->EnsureExtensionEnabled("GL_OES_packed_depth_stencil"); bool multisample_supported = want_antialiasing && (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample") || extensions_util->SupportsExtension( "GL_EXT_multisampled_render_to_texture")) && extensions_util->SupportsExtension("GL_OES_rgb8_rgba8"); if (multisample_supported) { extensions_util->EnsureExtensionEnabled("GL_OES_rgb8_rgba8"); if (extensions_util->SupportsExtension( "GL_CHROMIUM_framebuffer_multisample")) extensions_util->EnsureExtensionEnabled( "GL_CHROMIUM_framebuffer_multisample"); else extensions_util->EnsureExtensionEnabled( "GL_EXT_multisampled_render_to_texture"); } bool discard_framebuffer_supported = extensions_util->SupportsExtension("GL_EXT_discard_framebuffer"); if (discard_framebuffer_supported) extensions_util->EnsureExtensionEnabled("GL_EXT_discard_framebuffer"); RefPtr<DrawingBuffer> drawing_buffer = AdoptRef(new DrawingBuffer( std::move(context_provider), std::move(extensions_util), client, discard_framebuffer_supported, want_alpha_channel, premultiplied_alpha, preserve, webgl_version, want_depth_buffer, want_stencil_buffer, chromium_image_usage, color_params)); if (!drawing_buffer->Initialize(size, multisample_supported)) { drawing_buffer->BeginDestruction(); return PassRefPtr<DrawingBuffer>(); } return drawing_buffer; }
172,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_GetArrayItem( cJSON *array, int item ) { cJSON *c = array->child; while ( c && item > 0 ) { --item; c = c->next; } return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_GetArrayItem( cJSON *array, int item )
167,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; ret = gss_wrap_iov_length(minor_status, context_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_wrap_iov_length(OM_uint32 *minor_status, gss_ctx_id_t context_handle, int conf_req_flag, gss_qop_t qop_req, int *conf_state, gss_iov_buffer_desc *iov, int iov_count) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_wrap_iov_length(minor_status, sc->ctx_handle, conf_req_flag, qop_req, conf_state, iov, iov_count); return (ret); }
166,674
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mp_join_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_join *mpj = (const struct mp_join *) opt; if (!(opt_len == 12 && flags & TH_SYN) && !(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) && !(opt_len == 24 && flags & TH_ACK)) return 0; if (opt_len != 24) { if (mpj->sub_b & MP_JOIN_B) ND_PRINT((ndo, " backup")); ND_PRINT((ndo, " id %u", mpj->addr_id)); } switch (opt_len) { case 12: /* SYN */ ND_PRINT((ndo, " token 0x%x" " nonce 0x%x", EXTRACT_32BITS(mpj->u.syn.token), EXTRACT_32BITS(mpj->u.syn.nonce))); break; case 16: /* SYN/ACK */ ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x", EXTRACT_64BITS(mpj->u.synack.mac), EXTRACT_32BITS(mpj->u.synack.nonce))); break; case 24: {/* ACK */ size_t i; ND_PRINT((ndo, " hmac 0x")); for (i = 0; i < sizeof(mpj->u.ack.mac); ++i) ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i])); } default: break; } return 1; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
mp_join_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_join *mpj = (const struct mp_join *) opt; if (!(opt_len == 12 && (flags & TH_SYN)) && !(opt_len == 16 && (flags & (TH_SYN | TH_ACK)) == (TH_SYN | TH_ACK)) && !(opt_len == 24 && (flags & TH_ACK))) return 0; if (opt_len != 24) { if (mpj->sub_b & MP_JOIN_B) ND_PRINT((ndo, " backup")); ND_PRINT((ndo, " id %u", mpj->addr_id)); } switch (opt_len) { case 12: /* SYN */ ND_PRINT((ndo, " token 0x%x" " nonce 0x%x", EXTRACT_32BITS(mpj->u.syn.token), EXTRACT_32BITS(mpj->u.syn.nonce))); break; case 16: /* SYN/ACK */ ND_PRINT((ndo, " hmac 0x%" PRIx64 " nonce 0x%x", EXTRACT_64BITS(mpj->u.synack.mac), EXTRACT_32BITS(mpj->u.synack.nonce))); break; case 24: {/* ACK */ size_t i; ND_PRINT((ndo, " hmac 0x")); for (i = 0; i < sizeof(mpj->u.ack.mac); ++i) ND_PRINT((ndo, "%02x", mpj->u.ack.mac[i])); } default: break; } return 1; }
167,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t AMRSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { size_t size; int64_t seekFrame = seekTimeUs / 20000ll; // 20ms per frame. mCurrentTimeUs = seekFrame * 20000ll; size_t index = seekFrame < 0 ? 0 : seekFrame / 50; if (index >= mOffsetTableLength) { index = mOffsetTableLength - 1; } mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6); for (size_t i = 0; i< seekFrame - index * 50; i++) { status_t err; if ((err = getFrameSizeByOffset(mDataSource, mOffset, mIsWide, &size)) != OK) { return err; } mOffset += size; } } uint8_t header; ssize_t n = mDataSource->readAt(mOffset, &header, 1); if (n < 1) { return ERROR_END_OF_STREAM; } if (header & 0x83) { ALOGE("padding bits must be 0, header is 0x%02x", header); return ERROR_MALFORMED; } unsigned FT = (header >> 3) & 0x0f; size_t frameSize = getFrameSize(mIsWide, FT); if (frameSize == 0) { return ERROR_MALFORMED; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } n = mDataSource->readAt(mOffset, buffer->data(), frameSize); if (n != (ssize_t)frameSize) { buffer->release(); buffer = NULL; if (n < 0) { return ERROR_IO; } else { mOffset += n; return ERROR_END_OF_STREAM; } } buffer->set_range(0, frameSize); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); mOffset += frameSize; mCurrentTimeUs += 20000; // Each frame is 20ms *out = buffer; return OK; } Commit Message: Fix integer overflow and divide-by-zero Bug: 35763994 Test: ran CTS with and without fix Change-Id: If835e97ce578d4fa567e33e349e48fb7b2559e0e (cherry picked from commit 8538a603ef992e75f29336499cb783f3ec19f18c) CWE ID: CWE-190
status_t AMRSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (mOffsetTableLength > 0 && options && options->getSeekTo(&seekTimeUs, &mode)) { size_t size; int64_t seekFrame = seekTimeUs / 20000ll; // 20ms per frame. mCurrentTimeUs = seekFrame * 20000ll; size_t index = seekFrame < 0 ? 0 : seekFrame / 50; if (index >= mOffsetTableLength) { index = mOffsetTableLength - 1; } mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6); for (size_t i = 0; i< seekFrame - index * 50; i++) { status_t err; if ((err = getFrameSizeByOffset(mDataSource, mOffset, mIsWide, &size)) != OK) { return err; } mOffset += size; } } uint8_t header; ssize_t n = mDataSource->readAt(mOffset, &header, 1); if (n < 1) { return ERROR_END_OF_STREAM; } if (header & 0x83) { ALOGE("padding bits must be 0, header is 0x%02x", header); return ERROR_MALFORMED; } unsigned FT = (header >> 3) & 0x0f; size_t frameSize = getFrameSize(mIsWide, FT); if (frameSize == 0) { return ERROR_MALFORMED; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } n = mDataSource->readAt(mOffset, buffer->data(), frameSize); if (n != (ssize_t)frameSize) { buffer->release(); buffer = NULL; if (n < 0) { return ERROR_IO; } else { mOffset += n; return ERROR_END_OF_STREAM; } } buffer->set_range(0, frameSize); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); mOffset += frameSize; mCurrentTimeUs += 20000; // Each frame is 20ms *out = buffer; return OK; }
174,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::GetLast() const { if ((m_clusters == NULL) || (m_clusterCount <= 0)) return &m_eos; const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Cluster* Segment::GetLast() const const long idx = m_clusterCount - 1; Cluster* const pCluster = m_clusters[idx]; assert(pCluster); return pCluster; }
174,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, ()); MutexLocker locker(mutex); if (*gc_info_index_slot) return; int index = ++gc_info_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (gc_info_index >= gc_info_table_size_) Resize(); g_gc_info_table[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void GCInfoTable::EnsureGCInfoIndex(const GCInfo* gc_info, size_t* gc_info_index_slot) { DCHECK(gc_info); DCHECK(gc_info_index_slot); // Ensuring a new index involves current index adjustment as well // as potentially resizing the table, both operations that require // a lock. MutexLocker locker(table_mutex_); if (*gc_info_index_slot) return; int index = ++current_index_; size_t gc_info_index = static_cast<size_t>(index); CHECK(gc_info_index < GCInfoTable::kMaxIndex); if (current_index_ >= limit_) Resize(); table_[gc_info_index] = gc_info; ReleaseStore(reinterpret_cast<int*>(gc_info_index_slot), index); }
173,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLES2DecoderImpl::SimulateAttrib0( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; GLuint size_needed = 0; if (num_vertices == 0 || !SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); if (static_cast<GLsizei>(size_needed) > attrib_0_size_) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } attrib_0_buffer_matches_value_ = false; } if (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3]))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; } Commit Message: Always write data to new buffer in SimulateAttrib0 This is to work around linux nvidia driver bug. TEST=asan BUG=118970 Review URL: http://codereview.chromium.org/10019003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131538 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GLES2DecoderImpl::SimulateAttrib0( GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; GLuint size_needed = 0; if (num_vertices == 0 || !SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_; if (new_buffer) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, "glDrawXXX: Simulating attrib 0"); return false; } } if (new_buffer || (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3])))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; }
171,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaControlsProgressView::MediaControlsProgressView( base::RepeatingCallback<void(double)> seek_callback) : seek_callback_(std::move(seek_callback)) { SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, kProgressViewInsets)); progress_bar_ = AddChildView(std::make_unique<views::ProgressBar>(5, false)); progress_bar_->SetBorder(views::CreateEmptyBorder(kProgressBarInsets)); gfx::Font default_font; int font_size_delta = kProgressTimeFontSize - default_font.GetFontSize(); gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL, gfx::Font::Weight::NORMAL); gfx::FontList font_list(font); auto time_view = std::make_unique<views::View>(); auto* time_view_layout = time_view->SetLayoutManager(std::make_unique<views::FlexLayout>()); time_view_layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kCenter) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter) .SetCollapseMargins(true); auto progress_time = std::make_unique<views::Label>(); progress_time->SetFontList(font_list); progress_time->SetEnabledColor(SK_ColorWHITE); progress_time->SetAutoColorReadabilityEnabled(false); progress_time_ = time_view->AddChildView(std::move(progress_time)); auto time_spacing = std::make_unique<views::View>(); time_spacing->SetPreferredSize(kTimeSpacingSize); time_spacing->SetProperty(views::kFlexBehaviorKey, views::FlexSpecification::ForSizeRule( views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kUnbounded)); time_view->AddChildView(std::move(time_spacing)); auto duration = std::make_unique<views::Label>(); duration->SetFontList(font_list); duration->SetEnabledColor(SK_ColorWHITE); duration->SetAutoColorReadabilityEnabled(false); duration_ = time_view->AddChildView(std::move(duration)); AddChildView(std::move(time_view)); } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200
MediaControlsProgressView::MediaControlsProgressView( base::RepeatingCallback<void(double)> seek_callback) : seek_callback_(std::move(seek_callback)) { SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, kProgressViewInsets, kProgressBarAndTimeSpacing)); progress_bar_ = AddChildView( std::make_unique<views::ProgressBar>(kProgressBarHeight, false)); gfx::Font default_font; int font_size_delta = kProgressTimeFontSize - default_font.GetFontSize(); gfx::Font font = default_font.Derive(font_size_delta, gfx::Font::NORMAL, gfx::Font::Weight::NORMAL); gfx::FontList font_list(font); auto time_view = std::make_unique<views::View>(); auto* time_view_layout = time_view->SetLayoutManager(std::make_unique<views::FlexLayout>()); time_view_layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kCenter) .SetCrossAxisAlignment(views::LayoutAlignment::kCenter) .SetCollapseMargins(true); auto progress_time = std::make_unique<views::Label>(); progress_time->SetFontList(font_list); progress_time->SetEnabledColor(SK_ColorWHITE); progress_time->SetAutoColorReadabilityEnabled(false); progress_time_ = time_view->AddChildView(std::move(progress_time)); auto time_spacing = std::make_unique<views::View>(); time_spacing->SetPreferredSize(kTimeSpacingSize); time_spacing->SetProperty(views::kFlexBehaviorKey, views::FlexSpecification::ForSizeRule( views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kUnbounded)); time_view->AddChildView(std::move(time_spacing)); auto duration = std::make_unique<views::Label>(); duration->SetFontList(font_list); duration->SetEnabledColor(SK_ColorWHITE); duration->SetAutoColorReadabilityEnabled(false); duration_ = time_view->AddChildView(std::move(duration)); AddChildView(std::move(time_view)); }
172,346
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); bit_depth_ = GET_PARAM(3); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; inv_txfm_ref = idct16x16_ref; mask_ = (1 << bit_depth_) - 1; #if CONFIG_VP9_HIGHBITDEPTH switch (bit_depth_) { case VPX_BITS_10: inv_txfm_ref = idct16x16_10_ref; break; case VPX_BITS_12: inv_txfm_ref = idct16x16_12_ref; break; default: inv_txfm_ref = idct16x16_ref; break; } #else inv_txfm_ref = idct16x16_ref; #endif }
174,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CloudPolicyController::SetState( CloudPolicyController::ControllerState new_state) { state_ = new_state; backend_.reset(); // Discard any pending requests. base::Time now(base::Time::NowFromSystemTime()); base::Time refresh_at; base::Time last_refresh(cache_->last_policy_refresh_time()); if (last_refresh.is_null()) last_refresh = now; bool inform_notifier_done = false; switch (state_) { case STATE_TOKEN_UNMANAGED: notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_UNAVAILABLE: case STATE_TOKEN_VALID: refresh_at = now; break; case STATE_POLICY_VALID: effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; refresh_at = last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_ERROR: notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::BAD_DMTOKEN, PolicyNotifier::POLICY_CONTROLLER); inform_notifier_done = true; case STATE_POLICY_ERROR: if (!inform_notifier_done) { notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); } refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); effective_policy_refresh_error_delay_ms_ = std::min(effective_policy_refresh_error_delay_ms_ * 2, policy_refresh_rate_ms_); break; case STATE_POLICY_UNAVAILABLE: effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_; refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); break; } scheduler_->CancelDelayedWork(); if (!refresh_at.is_null()) { int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)), delay); } } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void CloudPolicyController::SetState( CloudPolicyController::ControllerState new_state) { state_ = new_state; backend_.reset(); // Stop any pending requests. base::Time now(base::Time::NowFromSystemTime()); base::Time refresh_at; base::Time last_refresh(cache_->last_policy_refresh_time()); if (last_refresh.is_null()) last_refresh = now; bool inform_notifier_done = false; switch (state_) { case STATE_TOKEN_UNMANAGED: notifier_->Inform(CloudPolicySubsystem::UNMANAGED, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_UNAVAILABLE: case STATE_TOKEN_VALID: refresh_at = now; break; case STATE_POLICY_VALID: effective_policy_refresh_error_delay_ms_ = kPolicyRefreshErrorDelayInMilliseconds; refresh_at = last_refresh + base::TimeDelta::FromMilliseconds(GetRefreshDelay()); notifier_->Inform(CloudPolicySubsystem::SUCCESS, CloudPolicySubsystem::NO_DETAILS, PolicyNotifier::POLICY_CONTROLLER); break; case STATE_TOKEN_ERROR: notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::BAD_DMTOKEN, PolicyNotifier::POLICY_CONTROLLER); inform_notifier_done = true; case STATE_POLICY_ERROR: if (!inform_notifier_done) { notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); } refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); effective_policy_refresh_error_delay_ms_ = std::min(effective_policy_refresh_error_delay_ms_ * 2, policy_refresh_rate_ms_); break; case STATE_POLICY_UNAVAILABLE: effective_policy_refresh_error_delay_ms_ = policy_refresh_rate_ms_; refresh_at = now + base::TimeDelta::FromMilliseconds( effective_policy_refresh_error_delay_ms_); notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR, CloudPolicySubsystem::POLICY_NETWORK_ERROR, PolicyNotifier::POLICY_CONTROLLER); break; } scheduler_->CancelDelayedWork(); if (!refresh_at.is_null()) { int64 delay = std::max<int64>((refresh_at - now).InMilliseconds(), 0); scheduler_->PostDelayedWork( base::Bind(&CloudPolicyController::DoWork, base::Unretained(this)), delay); } }
170,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec, pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return -1; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9d, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return -1; } yy = mm = dd = hr = min = sec = csec = 0; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error; return pkt_len; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12395 Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2 Reviewed-on: https://code.wireshark.org/review/15172 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-119
parse_cosine_rec_hdr(struct wtap_pkthdr *phdr, const char *line, static gboolean parse_cosine_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf, char *line, int *err, gchar **err_info) { union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header; int num_items_scanned; int yy, mm, dd, hr, min, sec, csec; guint pkt_len; int pro, off, pri, rm, error; guint code1, code2; char if_name[COSINE_MAX_IF_NAME_LEN] = "", direction[6] = ""; struct tm tm; guint8 *pd; int i, hex_lines, n, caplen = 0; if (sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d:", &yy, &mm, &dd, &hr, &min, &sec, &csec) == 7) { /* appears to be output to a control blade */ num_items_scanned = sscanf(line, "%4d-%2d-%2d,%2d:%2d:%2d.%9d: %5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", &yy, &mm, &dd, &hr, &min, &sec, &csec, direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 17) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: purported control blade line doesn't have code values"); return FALSE; } } else { /* appears to be output to PE */ num_items_scanned = sscanf(line, "%5s (%127[A-Za-z0-9/:]), Length:%9u, Pro:%9d, Off:%9d, Pri:%9d, RM:%9d, Err:%9d [%8x, %8x]", direction, if_name, &pkt_len, &pro, &off, &pri, &rm, &error, &code1, &code2); if (num_items_scanned != 10) { *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup("cosine: header line is neither control blade nor PE output"); return FALSE; } yy = mm = dd = hr = min = sec = csec = 0; } if (pkt_len > WTAP_MAX_PACKET_SIZE) { /* * Probably a corrupt capture file; don't blow up trying * to allocate space for an immensely-large packet. */ *err = WTAP_ERR_BAD_FILE; *err_info = g_strdup_printf("cosine: File has %u-byte packet, bigger than maximum of %u", pkt_len, WTAP_MAX_PACKET_SIZE); return FALSE; } phdr->rec_type = REC_TYPE_PACKET; phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN; tm.tm_year = yy - 1900; tm.tm_mon = mm - 1; tm.tm_mday = dd; tm.tm_hour = hr; tm.tm_min = min; tm.tm_sec = sec; tm.tm_isdst = -1; phdr->ts.secs = mktime(&tm); phdr->ts.nsecs = csec * 10000000; phdr->len = pkt_len; /* XXX need to handle other encapsulations like Cisco HDLC, Frame Relay and ATM */ if (strncmp(if_name, "TEST:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_TEST; } else if (strncmp(if_name, "PPoATM:", 7) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoATM; } else if (strncmp(if_name, "PPoFR:", 6) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPoFR; } else if (strncmp(if_name, "ATM:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ATM; } else if (strncmp(if_name, "FR:", 3) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_FR; } else if (strncmp(if_name, "HDLC:", 5) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_HDLC; } else if (strncmp(if_name, "PPP:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_PPP; } else if (strncmp(if_name, "ETH:", 4) == 0) { pseudo_header->cosine.encap = COSINE_ENCAP_ETH; } else { pseudo_header->cosine.encap = COSINE_ENCAP_UNKNOWN; } if (strncmp(direction, "l2-tx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_TX; } else if (strncmp(direction, "l2-rx", 5) == 0) { pseudo_header->cosine.direction = COSINE_DIR_RX; } g_strlcpy(pseudo_header->cosine.if_name, if_name, COSINE_MAX_IF_NAME_LEN); pseudo_header->cosine.pro = pro; pseudo_header->cosine.off = off; pseudo_header->cosine.pri = pri; pseudo_header->cosine.rm = rm; pseudo_header->cosine.err = error;
169,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostImpl::CreateMediaStreamDispatcherHost( MediaStreamManager* media_stream_manager, mojom::MediaStreamDispatcherHostRequest request) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!media_stream_dispatcher_host_) { media_stream_dispatcher_host_.reset(new MediaStreamDispatcherHost( GetProcess()->GetID(), GetRoutingID(), media_stream_manager)); } media_stream_dispatcher_host_->BindRequest(std::move(request)); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void RenderFrameHostImpl::CreateMediaStreamDispatcherHost(
173,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute) { u8 object_record_type; CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type; const u8 *obj = attribute->object->data; const u8 *attr = NULL; size_t buf_len = attribute->object->length; coolkey_object_header_t *object_head; int attribute_count,i; attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING; attribute->attribute_length = 0; attribute->attribute_value = NULL; if (obj == NULL) { /* cast away const so we can cache the data value */ int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object); if (r < 0) { return r; } obj = attribute->object->data; } /* should be a static assert so we catch this at compile time */ assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t)); /* make sure we have enough of the object to read the record_type */ if (buf_len <= sizeof(coolkey_v0_object_header_t)) { return SC_ERROR_CORRUPTED_DATA; } object_head = (coolkey_object_header_t *)obj; object_record_type = object_head->record_type; /* make sure it's a type we recognize */ if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) { return SC_ERROR_CORRUPTED_DATA; } /* * now loop through all the attributes in the list. first find the start of the list */ attr = coolkey_attribute_start(obj, object_record_type, buf_len); if (attr == NULL) { return SC_ERROR_CORRUPTED_DATA; } buf_len -= (attr-obj); /* now get the count */ attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len); for (i=0; i < attribute_count; i++) { size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len); /* make sure we have the complete record */ if (buf_len < record_len) { return SC_ERROR_CORRUPTED_DATA; } /* does the attribute match the one we are looking for */ if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) { /* yup, return it */ return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute); } /* go to the next attribute on the list */ buf_len -= record_len; attr += record_len; } /* not find in attribute list, check the fixed attribute record */ if (object_record_type == COOLKEY_V1_OBJECT) { unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values); return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute); } return SC_ERROR_DATA_OBJECT_NOT_FOUND; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
coolkey_find_attribute(sc_card_t *card, sc_cardctl_coolkey_attribute_t *attribute) { u8 object_record_type; CK_ATTRIBUTE_TYPE attr_type = attribute->attribute_type; const u8 *obj = attribute->object->data; const u8 *attr = NULL; size_t buf_len = attribute->object->length; coolkey_object_header_t *object_head; int attribute_count,i; attribute->attribute_data_type = SC_CARDCTL_COOLKEY_ATTR_TYPE_STRING; attribute->attribute_length = 0; attribute->attribute_value = NULL; if (obj == NULL) { /* cast away const so we can cache the data value */ int r = coolkey_fill_object(card, (sc_cardctl_coolkey_object_t *)attribute->object); if (r < 0) { return r; } obj = attribute->object->data; } /* should be a static assert so we catch this at compile time */ assert(sizeof(coolkey_object_header_t) >= sizeof(coolkey_v0_object_header_t)); /* make sure we have enough of the object to read the record_type */ if (buf_len <= sizeof(coolkey_v0_object_header_t)) { return SC_ERROR_CORRUPTED_DATA; } object_head = (coolkey_object_header_t *)obj; object_record_type = object_head->record_type; /* make sure it's a type we recognize */ if ((object_record_type != COOLKEY_V1_OBJECT) && (object_record_type != COOLKEY_V0_OBJECT)) { return SC_ERROR_CORRUPTED_DATA; } /* * now loop through all the attributes in the list. first find the start of the list */ attr = coolkey_attribute_start(obj, object_record_type, buf_len); if (attr == NULL) { return SC_ERROR_CORRUPTED_DATA; } buf_len -= (attr-obj); /* now get the count */ attribute_count = coolkey_get_attribute_count(obj, object_record_type, buf_len); for (i=0; i < attribute_count; i++) { size_t record_len = coolkey_get_attribute_record_len(attr, object_record_type, buf_len); /* make sure we have the complete record */ if (buf_len < record_len || record_len < 4) { return SC_ERROR_CORRUPTED_DATA; } /* does the attribute match the one we are looking for */ if (attr_type == coolkey_get_attribute_type(attr, object_record_type, record_len)) { /* yup, return it */ return coolkey_get_attribute_data(attr, object_record_type, record_len, attribute); } /* go to the next attribute on the list */ buf_len -= record_len; attr += record_len; } /* not find in attribute list, check the fixed attribute record */ if (object_record_type == COOLKEY_V1_OBJECT) { unsigned long fixed_attributes = bebytes2ulong(object_head->fixed_attributes_values); return coolkey_get_attribute_data_fixed(attr_type, fixed_attributes, attribute); } return SC_ERROR_DATA_OBJECT_NOT_FOUND; }
169,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::WorkerRestarted(int worker_process_id, int worker_route_id) { DCHECK_EQ(WORKER_TERMINATED, state_); state_ = WORKER_NOT_READY; worker_process_id_ = worker_process_id; worker_route_id_ = worker_route_id; RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_); for (DevToolsSession* session : sessions()) session->SetRenderer(host, nullptr); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::WorkerRestarted(int worker_process_id, int worker_route_id) { DCHECK_EQ(WORKER_TERMINATED, state_); state_ = WORKER_NOT_READY; worker_process_id_ = worker_process_id; worker_route_id_ = worker_route_id; for (DevToolsSession* session : sessions()) session->SetRenderer(worker_process_id_, nullptr); }
172,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; op->addr = addr; r_strbuf_setf (&op->esil, ""); opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; r_strbuf_set (&op->esil, "1,$"); return NULL; } Commit Message: Fix oobread in avr CWE ID: CWE-125
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; if (len < 2) { return NULL; } ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; op->addr = addr; r_strbuf_setf (&op->esil, ""); opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; r_strbuf_set (&op->esil, "1,$"); return NULL; }
170,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC) { zend_hash_destroy(&pglobals->ht_rc); } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC) static void _php_mb_regex_globals_dtor(zend_mb_regex_globals *pglobals TSRMLS_DC) { zend_hash_destroy(&pglobals->ht_rc); }
167,119
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) { blkg_free(new_blkg); return PTR_ERR(blkg); } q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; } Commit Message: blkcg: fix double free of new_blkg in blkcg_init_queue If blkg_create fails, new_blkg passed as an argument will be freed by blkg_create, so there is no need to free it again. Signed-off-by: Hou Tao <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-415
int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) return PTR_ERR(blkg); q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; }
169,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */ Commit Message: Do not allocate memory for zero length strings. Fixes #1821. JerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg [email protected] CWE ID: CWE-476
lexer_process_char_literal (parser_context_t *context_p, /**< context */ const uint8_t *char_p, /**< characters */ size_t length, /**< length of string */ uint8_t literal_type, /**< final literal type */ bool has_escape) /**< has escape sequences */ { parser_list_iterator_t literal_iterator; lexer_literal_t *literal_p; uint32_t literal_index = 0; JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL || literal_type == LEXER_STRING_LITERAL); JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH); JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH); parser_list_iterator_init (&context_p->literal_pool, &literal_iterator); while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL) { if (literal_p->type == literal_type && literal_p->prop.length == length && memcmp (literal_p->u.char_p, char_p, length) == 0) { context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT); return; } literal_index++; } JERRY_ASSERT (literal_index == context_p->literal_count); if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS) { parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED); } if (length == 0) { has_escape = false; } literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool); literal_p->prop.length = (uint16_t) length; literal_p->type = literal_type; literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR; if (has_escape) { literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length); memcpy ((uint8_t *) literal_p->u.char_p, char_p, length); } else { literal_p->u.char_p = char_p; } context_p->lit_object.literal_p = literal_p; context_p->lit_object.index = (uint16_t) literal_index; context_p->literal_count++; } /* lexer_process_char_literal */
168,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cJSON_GetArraySize( cJSON *array ) { cJSON *c = array->child; int i = 0; while ( c ) { ++i; c = c->next; } return i; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
int cJSON_GetArraySize( cJSON *array )
167,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } Commit Message: fs: limit filesystem stacking depth Add a simple read-only counter to super_block that indicates how deep this is in the stack of filesystems. Previously ecryptfs was the only stackable filesystem and it explicitly disallowed multiple layers of itself. Overlayfs, however, can be stacked recursively and also may be stacked on top of ecryptfs or vice versa. To limit the kernel stack usage we must limit the depth of the filesystem stack. Initially the limit is set to 2. Signed-off-by: Miklos Szeredi <[email protected]> CWE ID: CWE-264
static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; s->s_stack_depth = path.dentry->d_sb->s_stack_depth + 1; rc = -EINVAL; if (s->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) { pr_err("eCryptfs: maximum fs stacking depth exceeded\n"); goto out_free; } inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); }
168,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void VarianceTest<VarianceFunctionType>::ZeroTest() { for (int i = 0; i <= 255; ++i) { memset(src_, i, block_size_); for (int j = 0; j <= 255; ++j) { memset(ref_, j, block_size_); unsigned int sse; unsigned int var; REGISTER_STATE_CHECK(var = variance_(src_, width_, ref_, width_, &sse)); EXPECT_EQ(0u, var) << "src values: " << i << "ref values: " << j; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void VarianceTest<VarianceFunctionType>::ZeroTest() { for (int i = 0; i <= 255; ++i) { if (!use_high_bit_depth_) { memset(src_, i, block_size_); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(src_), i << (bit_depth_ - 8), block_size_); #endif // CONFIG_VP9_HIGHBITDEPTH } for (int j = 0; j <= 255; ++j) { if (!use_high_bit_depth_) { memset(ref_, j, block_size_); #if CONFIG_VP9_HIGHBITDEPTH } else { vpx_memset16(CONVERT_TO_SHORTPTR(ref_), j << (bit_depth_ - 8), block_size_); #endif // CONFIG_VP9_HIGHBITDEPTH } unsigned int sse; unsigned int var; ASM_REGISTER_STATE_CHECK( var = variance_(src_, width_, ref_, width_, &sse)); EXPECT_EQ(0u, var) << "src values: " << i << " ref values: " << j; } } }
174,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } vsep = memchr(var->ptr, '&', var->end - var->ptr); if (!vsep) { if (!eof) { return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); return 1; } Commit Message: Fix bug #73807 CWE ID: CWE-400
static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof) { char *start, *ksep, *vsep, *val; size_t klen, vlen; size_t new_vlen; if (var->ptr >= var->end) { return 0; } start = var->ptr + var->already_scanned; vsep = memchr(start, '&', var->end - start); if (!vsep) { if (!eof) { var->already_scanned = var->end - var->ptr; return 0; } else { vsep = var->end; } } ksep = memchr(var->ptr, '=', vsep - var->ptr); if (ksep) { *ksep = '\0'; /* "foo=bar&" or "foo=&" */ klen = ksep - var->ptr; vlen = vsep - ++ksep; } else { ksep = ""; /* "foo&" */ klen = vsep - var->ptr; vlen = 0; } php_url_decode(var->ptr, klen); val = estrndup(ksep, vlen); if (vlen) { vlen = php_url_decode(val, vlen); } if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) { php_register_variable_safe(var->ptr, val, new_vlen, arr); } efree(val); var->ptr = vsep + (vsep != var->end); var->already_scanned = 0; return 1; }
170,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += JPC_QMFB_COLGRPSIZE; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += JPC_QMFB_COLGRPSIZE; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119
void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = joinbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int hstartcol; /* Allocate memory for the join buffer from the heap. */ if (bufsize > QMFB_JOINBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide. */ abort(); } } hstartcol = (numrows + 1 - parity) >> 1; /* Save the samples from the lowpass channel. */ n = hstartcol; srcptr = &a[0]; dstptr = buf; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } srcptr += stride; dstptr += JPC_QMFB_COLGRPSIZE; } /* Copy the samples from the highpass channel into place. */ srcptr = &a[hstartcol * stride]; dstptr = &a[(1 - parity) * stride]; n = numrows - hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += stride; } /* Copy the samples from the lowpass channel into place. */ srcptr = buf; dstptr = &a[parity * stride]; n = hstartcol; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += 2 * stride; srcptr += JPC_QMFB_COLGRPSIZE; } /* If the join buffer was allocated on the heap, free this memory. */ if (buf != joinbuf) { jas_free(buf); } }
169,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int verify_vc_kbmode(int fd) { int curr_mode; /* * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode. * Otherwise we would (likely) interfere with X11's processing of the * key events. * * http://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html */ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0) return -errno; return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY; } Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check VT kbd reset check CWE ID: CWE-255
static int verify_vc_kbmode(int fd) {
169,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (!mTimeToSample.empty() || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } return OK; } Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug 28076789. Detail: Before the original fix (Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the code allowed a time-to-sample table size to be 0. The change made in that fix disallowed such situation, which in fact should be allowed. This current patch allows it again while maintaining the security of the previous fix. Bug: 28288202 Bug: 28076789 Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295 CWE ID: CWE-20
status_t SampleTable::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mHasTimeToSample || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mTimeToSampleCount = U32_AT(&header[4]); if ((uint64_t)mTimeToSampleCount > (uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) { ALOGE(" Error: Time-to-sample table size too large."); return ERROR_OUT_OF_RANGE; } if (!mDataSource->getVector(data_offset + 8, &mTimeToSample, mTimeToSampleCount * 2)) { ALOGE(" Error: Incomplete data read for time-to-sample table."); return ERROR_IO; } for (size_t i = 0; i < mTimeToSample.size(); ++i) { mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]); } mHasTimeToSample = true; return OK; }
173,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlockGroup::BlockGroup( Cluster* pCluster, long idx, long long block_start, long long block_size, long long prev, long long next, long long duration, long long discard_padding) : BlockEntry(pCluster, idx), m_block(block_start, block_size, discard_padding), m_prev(prev), m_next(next), m_duration(duration) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
BlockGroup::BlockGroup(
174,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cib_connect(gboolean full) { int rc = pcmk_ok; static gboolean need_pass = TRUE; CRM_CHECK(cib != NULL, return -EINVAL); if (getenv("CIB_passwd") != NULL) { need_pass = FALSE; } if(watch_fencing && st == NULL) { st = stonith_api_new(); } if(watch_fencing && st->state == stonith_disconnected) { crm_trace("Connecting to stonith"); rc = st->cmds->connect(st, crm_system_name, NULL); if(rc == pcmk_ok) { crm_trace("Setting up stonith callbacks"); st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback); } } if (cib->state != cib_connected_query && cib->state != cib_connected_command) { crm_trace("Connecting to the CIB"); if (as_console && need_pass && cib->variant == cib_remote) { need_pass = FALSE; print_as("Password:"); } rc = cib->cmds->signon(cib, crm_system_name, cib_query); if (rc != pcmk_ok) { return rc; } current_cib = get_cib_copy(cib); mon_refresh_display(NULL); if (full) { if (rc == pcmk_ok) { rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy); if (rc == -EPROTONOSUPPORT) { print_as("Notification setup failed, won't be able to reconnect after failure"); if (as_console) { sleep(2); } rc = pcmk_ok; } } if (rc == pcmk_ok) { cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); } if (rc != pcmk_ok) { print_as("Notification setup failed, could not monitor CIB actions"); if (as_console) { sleep(2); } clean_up(-rc); } } } return rc; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_connect(gboolean full) { int rc = pcmk_ok; static gboolean need_pass = TRUE; CRM_CHECK(cib != NULL, return -EINVAL); if (getenv("CIB_passwd") != NULL) { need_pass = FALSE; } if(watch_fencing && st == NULL) { st = stonith_api_new(); } if(watch_fencing && st->state == stonith_disconnected) { crm_trace("Connecting to stonith"); rc = st->cmds->connect(st, crm_system_name, NULL); if(rc == pcmk_ok) { crm_trace("Setting up stonith callbacks"); st->cmds->register_notification(st, T_STONITH_NOTIFY_FENCE, mon_st_callback); } } if (cib->state != cib_connected_query && cib->state != cib_connected_command) { crm_trace("Connecting to the CIB"); if (as_console && need_pass && cib->variant == cib_remote) { need_pass = FALSE; print_as("Password:"); } rc = cib->cmds->signon(cib, crm_system_name, cib_query); if (rc != pcmk_ok) { return rc; } current_cib = get_cib_copy(cib); mon_refresh_display(NULL); if (full) { if (rc == pcmk_ok) { rc = cib->cmds->set_connection_dnotify(cib, mon_cib_connection_destroy); if (rc == -EPROTONOSUPPORT) { print_as("Notification setup not supported, won't be able to reconnect after failure"); if (as_console) { sleep(2); } rc = pcmk_ok; } } if (rc == pcmk_ok) { cib->cmds->del_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); rc = cib->cmds->add_notify_callback(cib, T_CIB_DIFF_NOTIFY, crm_diff_update); } if (rc != pcmk_ok) { print_as("Notification setup failed, could not monitor CIB actions"); if (as_console) { sleep(2); } clean_up(-rc); } } } return rc; }
166,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FocusFirstNameField() { LOG(WARNING) << "Clicking on the tab."; ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER)); ASSERT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER)); LOG(WARNING) << "Focusing the first name field."; bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( render_view_host(), L"", L"if (document.readyState === 'complete')" L" document.getElementById('firstname').focus();" L"else" L" domAutomationController.send(false);", &result)); ASSERT_TRUE(result); } Commit Message: Convert the autofill interactive browser test to a normal browser_test. I added testing methods to fake input events that don't depend on the OS and being at the front. BUG=121574 Review URL: https://chromiumcodereview.appspot.com/10368010 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@135432 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void FocusFirstNameField() { LOG(WARNING) << "Clicking on the tab."; ui_test_utils::SimulateMouseClick(browser()->GetSelectedWebContents()); LOG(WARNING) << "Focusing the first name field."; bool result = false; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractBool( render_view_host(), L"", L"if (document.readyState === 'complete')" L" document.getElementById('firstname').focus();" L"else" L" domAutomationController.send(false);", &result)); ASSERT_TRUE(result); }
170,721
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt) { unsigned countdown = MAX_DUMPED_DD_COUNT; /* do not report hundreds of oopses */ log_notice("Saving %u oopses as problem dirs", oops_cnt >= countdown ? countdown : oops_cnt); char *cmdline_str = xmalloc_fopen_fgetline_fclose("/proc/cmdline"); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); char *proc_modules = xmalloc_open_read_close("/proc/modules", /*maxsize:*/ NULL); char *suspend_stats = xmalloc_open_read_close("/sys/kernel/debug/suspend_stats", /*maxsize:*/ NULL); time_t t = time(NULL); const char *iso_date = iso_date_string(&t); /* dump should be readable by all if we're run with -x */ uid_t my_euid = (uid_t)-1L; mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH; /* and readable only for the owner otherwise */ if (!world_readable_dump) { mode = DEFAULT_DUMP_DIR_MODE; my_euid = geteuid(); } pid_t my_pid = getpid(); unsigned idx = 0; unsigned errors = 0; while (idx < oops_cnt) { char base[sizeof("oops-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3]; sprintf(base, "oops-%s-%lu-%lu", iso_date, (long)my_pid, (long)idx); char *path = concat_path_file(debug_dumps_dir, base); struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode); if (dd) { dd_create_basic_files(dd, /*uid:*/ my_euid, NULL); save_oops_data_in_dump_dir(dd, (char*)g_list_nth_data(oops_list, idx++), proc_modules); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); dd_save_text(dd, FILENAME_ANALYZER, "Kerneloops"); dd_save_text(dd, FILENAME_TYPE, "Kerneloops"); if (cmdline_str) dd_save_text(dd, FILENAME_CMDLINE, cmdline_str); if (proc_modules) dd_save_text(dd, "proc_modules", proc_modules); if (fips_enabled && strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); if (suspend_stats) dd_save_text(dd, "suspend_stats", suspend_stats); dd_close(dd); notify_new_path(path); } else errors++; free(path); if (--countdown == 0) break; if (dd && throttle_dd_creation) sleep(1); } free(cmdline_str); free(proc_modules); free(fips_enabled); free(suspend_stats); return errors; } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200
static unsigned create_oops_dump_dirs(GList *oops_list, unsigned oops_cnt) { unsigned countdown = MAX_DUMPED_DD_COUNT; /* do not report hundreds of oopses */ log_notice("Saving %u oopses as problem dirs", oops_cnt >= countdown ? countdown : oops_cnt); char *cmdline_str = xmalloc_fopen_fgetline_fclose("/proc/cmdline"); char *fips_enabled = xmalloc_fopen_fgetline_fclose("/proc/sys/crypto/fips_enabled"); char *proc_modules = xmalloc_open_read_close("/proc/modules", /*maxsize:*/ NULL); char *suspend_stats = xmalloc_open_read_close("/sys/kernel/debug/suspend_stats", /*maxsize:*/ NULL); time_t t = time(NULL); const char *iso_date = iso_date_string(&t); /* dump should be readable by all if we're run with -x */ uid_t my_euid = (uid_t)-1L; mode_t mode = DEFAULT_DUMP_DIR_MODE | S_IROTH; /* and readable only for the owner otherwise */ if (!world_readable_dump) { mode = DEFAULT_DUMP_DIR_MODE; my_euid = geteuid(); } if (g_settings_privatereports) { if (world_readable_dump) log("Not going to make dump directories world readable because PrivateReports is on"); mode = DEFAULT_DUMP_DIR_MODE; my_euid = 0; } pid_t my_pid = getpid(); unsigned idx = 0; unsigned errors = 0; while (idx < oops_cnt) { char base[sizeof("oops-YYYY-MM-DD-hh:mm:ss-%lu-%lu") + 2 * sizeof(long)*3]; sprintf(base, "oops-%s-%lu-%lu", iso_date, (long)my_pid, (long)idx); char *path = concat_path_file(debug_dumps_dir, base); struct dump_dir *dd = dd_create(path, /*uid:*/ my_euid, mode); if (dd) { dd_create_basic_files(dd, /*uid:*/ my_euid, NULL); save_oops_data_in_dump_dir(dd, (char*)g_list_nth_data(oops_list, idx++), proc_modules); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); dd_save_text(dd, FILENAME_ANALYZER, "Kerneloops"); dd_save_text(dd, FILENAME_TYPE, "Kerneloops"); if (cmdline_str) dd_save_text(dd, FILENAME_CMDLINE, cmdline_str); if (proc_modules) dd_save_text(dd, "proc_modules", proc_modules); if (fips_enabled && strcmp(fips_enabled, "0") != 0) dd_save_text(dd, "fips_enabled", fips_enabled); if (suspend_stats) dd_save_text(dd, "suspend_stats", suspend_stats); dd_close(dd); notify_new_path(path); } else errors++; free(path); if (--countdown == 0) break; if (dd && throttle_dd_creation) sleep(1); } free(cmdline_str); free(proc_modules); free(fips_enabled); free(suspend_stats); return errors; }
170,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->SetRenderer(frame_host_ ? frame_host_->GetProcess() : nullptr, frame_host_); protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler())); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); if (frame_tree_node_ && !frame_tree_node_->parent()) { session->AddHandler( base::WrapUnique(new protocol::PageHandler(emulation_handler))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); } if (EnsureAgent()) session->AttachToAgent(agent_ptr_); if (sessions().size() == 1) { frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->SetRenderer(frame_host_ ? frame_host_->GetProcess()->GetID() : ChildProcessHost::kInvalidUniqueID, frame_host_); protocol::EmulationHandler* emulation_handler = new protocol::EmulationHandler(); session->AddHandler(base::WrapUnique(new protocol::BrowserHandler())); session->AddHandler(base::WrapUnique(new protocol::DOMHandler())); session->AddHandler(base::WrapUnique(emulation_handler)); session->AddHandler(base::WrapUnique(new protocol::InputHandler())); session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::IOHandler( GetIOContext()))); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler())); session->AddHandler(base::WrapUnique(new protocol::StorageHandler())); session->AddHandler(base::WrapUnique(new protocol::TargetHandler())); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); if (frame_tree_node_ && !frame_tree_node_->parent()) { session->AddHandler( base::WrapUnique(new protocol::PageHandler(emulation_handler))); session->AddHandler(base::WrapUnique(new protocol::SecurityHandler())); } if (EnsureAgent()) session->AttachToAgent(agent_ptr_); if (sessions().size() == 1) { frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder()); GrantPolicy(); #if defined(OS_ANDROID) GetWakeLock()->RequestWakeLock(); #endif } }
172,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) { if (!(gpu_enabled_ && GpuDataManagerImpl::GetInstance()->ShouldUseSoftwareRendering()) && !hardware_gpu_enabled_) { SendOutstandingReplies(); return false; } const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType gpu_launcher = browser_command_line.GetSwitchValueNative(switches::kGpuLauncher); #if defined(OS_LINUX) int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF : ChildProcessHost::CHILD_NORMAL; #else int child_flags = ChildProcessHost::CHILD_NORMAL; #endif FilePath exe_path = ChildProcessHost::GetChildPath(child_flags); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED) cmd_line->AppendSwitch(switches::kDisableGpuSandbox); static const char* const kSwitchNames[] = { switches::kDisableBreakpad, switches::kDisableGLMultisampling, switches::kDisableGpuSandbox, switches::kReduceGpuSandbox, switches::kDisableSeccompFilterSandbox, switches::kDisableGpuSwitching, switches::kDisableGpuVsync, switches::kDisableGpuWatchdog, switches::kDisableImageTransportSurface, switches::kDisableLogging, switches::kEnableGPUServiceLogging, switches::kEnableLogging, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif #if defined(OS_CHROMEOS) switches::kEnableVaapi, #endif switches::kGpuNoContextLost, switches::kGpuStartupDialog, switches::kLoggingLevel, switches::kNoSandbox, switches::kTestGLLib, switches::kTraceStartup, switches::kV, switches::kVModule, }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); cmd_line->CopySwitchesFrom( browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches); content::GetContentClient()->browser()->AppendExtraCommandLineSwitches( cmd_line, process_->GetData().id); GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line); if (cmd_line->HasSwitch(switches::kUseGL)) software_rendering_ = (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader"); UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessSoftwareRendering", software_rendering_); if (!gpu_launcher.empty()) cmd_line->PrependWrapper(gpu_launcher); process_->Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) false, // Never use the zygote (GPU plugin can't be sandboxed). base::EnvironmentVector(), #endif cmd_line); process_launched_ = true; UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents", LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX); return true; } Commit Message: Revert 137988 - VAVDA is the hardware video decode accelerator for Chrome on Linux and ChromeOS for Intel CPUs (Sandy Bridge and newer). This CL enables VAVDA acceleration for ChromeOS, both for HTML5 video and Flash. The feature is currently hidden behind a command line flag and can be enabled by adding the --enable-vaapi parameter to command line. BUG=117062 TEST=Manual runs of test streams. Change-Id: I386e16739e2ef2230f52a0a434971b33d8654699 Review URL: https://chromiumcodereview.appspot.com/9814001 This is causing crbug.com/129103 [email protected] Review URL: https://chromiumcodereview.appspot.com/10411066 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@138208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GpuProcessHost::LaunchGpuProcess(const std::string& channel_id) { if (!(gpu_enabled_ && GpuDataManagerImpl::GetInstance()->ShouldUseSoftwareRendering()) && !hardware_gpu_enabled_) { SendOutstandingReplies(); return false; } const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType gpu_launcher = browser_command_line.GetSwitchValueNative(switches::kGpuLauncher); #if defined(OS_LINUX) int child_flags = gpu_launcher.empty() ? ChildProcessHost::CHILD_ALLOW_SELF : ChildProcessHost::CHILD_NORMAL; #else int child_flags = ChildProcessHost::CHILD_NORMAL; #endif FilePath exe_path = ChildProcessHost::GetChildPath(child_flags); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id); if (kind_ == GPU_PROCESS_KIND_UNSANDBOXED) cmd_line->AppendSwitch(switches::kDisableGpuSandbox); static const char* const kSwitchNames[] = { switches::kDisableBreakpad, switches::kDisableGLMultisampling, switches::kDisableGpuSandbox, switches::kReduceGpuSandbox, switches::kDisableSeccompFilterSandbox, switches::kDisableGpuSwitching, switches::kDisableGpuVsync, switches::kDisableGpuWatchdog, switches::kDisableImageTransportSurface, switches::kDisableLogging, switches::kEnableGPUServiceLogging, switches::kEnableLogging, #if defined(OS_MACOSX) switches::kEnableSandboxLogging, #endif switches::kGpuNoContextLost, switches::kGpuStartupDialog, switches::kLoggingLevel, switches::kNoSandbox, switches::kTestGLLib, switches::kTraceStartup, switches::kV, switches::kVModule, }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); cmd_line->CopySwitchesFrom( browser_command_line, switches::kGpuSwitches, switches::kNumGpuSwitches); content::GetContentClient()->browser()->AppendExtraCommandLineSwitches( cmd_line, process_->GetData().id); GpuDataManagerImpl::GetInstance()->AppendGpuCommandLine(cmd_line); if (cmd_line->HasSwitch(switches::kUseGL)) software_rendering_ = (cmd_line->GetSwitchValueASCII(switches::kUseGL) == "swiftshader"); UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessSoftwareRendering", software_rendering_); if (!gpu_launcher.empty()) cmd_line->PrependWrapper(gpu_launcher); process_->Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) false, // Never use the zygote (GPU plugin can't be sandboxed). base::EnvironmentVector(), #endif cmd_line); process_launched_ = true; UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents", LAUNCHED, GPU_PROCESS_LIFETIME_EVENT_MAX); return true; }
170,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; (void) fputc(c,file); } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199 CWE ID: CWE-20
static Image *ReadPWPImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next_image, *pwp_image; ImageInfo *read_info; int c, unique_file; MagickBooleanType status; register Image *p; register ssize_t i; size_t filesize, length; ssize_t count; unsigned char magick[MagickPathExtent]; /* 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=DestroyImage(image); return((Image *) NULL); } pwp_image=image; memset(magick,0,sizeof(magick)); count=ReadBlob(pwp_image,5,magick); if ((count != 5) || (LocaleNCompare((char *) magick,"SFW95",5) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); read_info=CloneImageInfo(image_info); (void) SetImageInfoProgressMonitor(read_info,(MagickProgressMonitor) NULL, (void *) NULL); SetImageInfoBlob(read_info,(void *) NULL,0); unique_file=AcquireUniqueFileResource(filename); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"sfw:%s", filename); for ( ; ; ) { (void) memset(magick,0,sizeof(magick)); for (c=ReadBlobByte(pwp_image); c != EOF; c=ReadBlobByte(pwp_image)) { for (i=0; i < 17; i++) magick[i]=magick[i+1]; magick[17]=(unsigned char) c; if (LocaleNCompare((char *) (magick+12),"SFW94A",6) == 0) break; } if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (LocaleNCompare((char *) (magick+12),"SFW94A",6) != 0) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } /* Dump SFW image to a temporary file. */ file=(FILE *) NULL; if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowFileException(exception,FileOpenError,"UnableToWriteFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } length=fwrite("SFW94A",1,6,file); (void) length; filesize=65535UL*magick[2]+256L*magick[1]+magick[0]; for (i=0; i < (ssize_t) filesize; i++) { c=ReadBlobByte(pwp_image); if (c == EOF) break; if (fputc(c,file) != c) break; } (void) fclose(file); if (c == EOF) { (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } next_image=ReadImage(read_info,exception); if (next_image == (Image *) NULL) break; (void) FormatLocaleString(next_image->filename,MagickPathExtent, "slide_%02ld.sfw",(long) next_image->scene); if (image == (Image *) NULL) image=next_image; else { /* Link image into image list. */ for (p=image; p->next != (Image *) NULL; p=GetNextImageInList(p)) ; next_image->previous=p; next_image->scene=p->scene+1; p->next=next_image; } if (image_info->number_scenes != 0) if (next_image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageProgress(image,LoadImagesTag,TellBlob(pwp_image), GetBlobSize(pwp_image)); if (status == MagickFalse) break; } if (unique_file != -1) (void) close(unique_file); (void) RelinquishUniqueFileResource(filename); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) { if (EOFBlob(image) != MagickFalse) { char *message; message=GetExceptionMessage(errno); (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageError,"UnexpectedEndOfFile","`%s': %s",image->filename, message); message=DestroyString(message); } (void) CloseBlob(image); } return(GetFirstImageInList(image)); }
169,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GesturePoint::IsSecondClickInsideManhattanSquare( const TouchEvent& event) const { int manhattanDistance = abs(event.x() - last_tap_position_.x()) + abs(event.y() - last_tap_position_.y()); return manhattanDistance < kMaximumTouchMoveInPixelsForClick; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GesturePoint::IsSecondClickInsideManhattanSquare( const TouchEvent& event) const { int manhattanDistance = abs(event.x() - last_tap_position_.x()) + abs(event.y() - last_tap_position_.y()); return manhattanDistance < GestureConfiguration::max_touch_move_in_pixels_for_click(); }
171,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE || pg > 6) { return -1; } ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ if (pg == 6) { return -1; /* avoid page pg + 1 */ } ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK); uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; } Commit Message: CWE ID: CWE-399
static int ehci_process_itd(EHCIState *ehci, EHCIitd *itd, uint32_t addr) { USBDevice *dev; USBEndpoint *ep; uint32_t i, len, pid, dir, devaddr, endp; uint32_t pg, off, ptr1, ptr2, max, mult; ehci->periodic_sched_active = PERIODIC_ACTIVE; dir =(itd->bufptr[1] & ITD_BUFPTR_DIRECTION); devaddr = get_field(itd->bufptr[0], ITD_BUFPTR_DEVADDR); endp = get_field(itd->bufptr[0], ITD_BUFPTR_EP); max = get_field(itd->bufptr[1], ITD_BUFPTR_MAXPKT); mult = get_field(itd->bufptr[2], ITD_BUFPTR_MULT); for(i = 0; i < 8; i++) { if (itd->transact[i] & ITD_XACT_ACTIVE) { pg = get_field(itd->transact[i], ITD_XACT_PGSEL); off = itd->transact[i] & ITD_XACT_OFFSET_MASK; len = get_field(itd->transact[i], ITD_XACT_LENGTH); if (len > max * mult) { len = max * mult; } if (len > BUFF_SIZE || pg > 6) { return -1; } ptr1 = (itd->bufptr[pg] & ITD_BUFPTR_MASK); qemu_sglist_init(&ehci->isgl, ehci->device, 2, ehci->as); if (off + len > 4096) { /* transfer crosses page border */ if (pg == 6) { qemu_sglist_destroy(&ehci->isgl); return -1; /* avoid page pg + 1 */ } ptr2 = (itd->bufptr[pg + 1] & ITD_BUFPTR_MASK); uint32_t len1 = len - len2; qemu_sglist_add(&ehci->isgl, ptr1 + off, len1); qemu_sglist_add(&ehci->isgl, ptr2, len2); } else { qemu_sglist_add(&ehci->isgl, ptr1 + off, len); } pid = dir ? USB_TOKEN_IN : USB_TOKEN_OUT; dev = ehci_find_device(ehci, devaddr); ep = usb_ep_get(dev, pid, endp); if (ep && ep->type == USB_ENDPOINT_XFER_ISOC) { usb_packet_setup(&ehci->ipacket, pid, ep, 0, addr, false, (itd->transact[i] & ITD_XACT_IOC) != 0); usb_packet_map(&ehci->ipacket, &ehci->isgl); usb_handle_packet(dev, &ehci->ipacket); usb_packet_unmap(&ehci->ipacket, &ehci->isgl); } else { DPRINTF("ISOCH: attempt to addess non-iso endpoint\n"); ehci->ipacket.status = USB_RET_NAK; ehci->ipacket.actual_length = 0; } qemu_sglist_destroy(&ehci->isgl); switch (ehci->ipacket.status) { case USB_RET_SUCCESS: break; default: fprintf(stderr, "Unexpected iso usb result: %d\n", ehci->ipacket.status); /* Fall through */ case USB_RET_IOERROR: case USB_RET_NODEV: /* 3.3.2: XACTERR is only allowed on IN transactions */ if (dir) { itd->transact[i] |= ITD_XACT_XACTERR; ehci_raise_irq(ehci, USBSTS_ERRINT); } break; case USB_RET_BABBLE: itd->transact[i] |= ITD_XACT_BABBLE; ehci_raise_irq(ehci, USBSTS_ERRINT); break; case USB_RET_NAK: /* no data for us, so do a zero-length transfer */ ehci->ipacket.actual_length = 0; break; } if (!dir) { set_field(&itd->transact[i], len - ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* OUT */ } else { set_field(&itd->transact[i], ehci->ipacket.actual_length, ITD_XACT_LENGTH); /* IN */ } if (itd->transact[i] & ITD_XACT_IOC) { ehci_raise_irq(ehci, USBSTS_INT); } itd->transact[i] &= ~ITD_XACT_ACTIVE; } } return 0; }
164,912
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: Fix bug #73831 - NULL Pointer Dereference while unserialize php object CWE ID: CWE-476
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ if (object_init_ex(&obj, pce) != SUCCESS || EG(exception)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be instantiated", Z_STRVAL(ent1->data)); } else { /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
168,513
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER("mysqlnd_switch_to_ssl_if_needed"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if ((greet_packet->server_capabilities & CLIENT_SSL) && (mysql_flags & CLIENT_SSL)) { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF("Switching to SSL"); if (!PACKET_WRITE(auth_packet, conn)) { CONN_SET_STATE(conn, CONN_QUIT_SENT); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); goto end; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); } Commit Message: CWE ID: CWE-284
mysqlnd_switch_to_ssl_if_needed( MYSQLND_CONN_DATA * conn, const MYSQLND_PACKET_GREET * const greet_packet, const MYSQLND_OPTIONS * const options, unsigned long mysql_flags TSRMLS_DC ) { enum_func_status ret = FAIL; const MYSQLND_CHARSET * charset; MYSQLND_PACKET_AUTH * auth_packet; DBG_ENTER("mysqlnd_switch_to_ssl_if_needed"); auth_packet = conn->protocol->m.get_auth_packet(conn->protocol, FALSE TSRMLS_CC); if (!auth_packet) { SET_OOM_ERROR(*conn->error_info); goto end; } auth_packet->client_flags = mysql_flags; auth_packet->max_packet_size = MYSQLND_ASSEMBLED_PACKET_MAX_SIZE; if (options->charset_name && (charset = mysqlnd_find_charset_name(options->charset_name))) { auth_packet->charset_no = charset->nr; } else { #if MYSQLND_UNICODE auth_packet->charset_no = 200;/* utf8 - swedish collation, check mysqlnd_charset.c */ #else auth_packet->charset_no = greet_packet->charset_no; #endif } #ifdef MYSQLND_SSL_SUPPORTED if (mysql_flags & CLIENT_SSL) { zend_bool server_has_ssl = (greet_packet->server_capabilities & CLIENT_SSL)? TRUE:FALSE; if (server_has_ssl == FALSE) { goto close_conn; } else { zend_bool verify = mysql_flags & CLIENT_SSL_VERIFY_SERVER_CERT? TRUE:FALSE; DBG_INF("Switching to SSL"); if (!PACKET_WRITE(auth_packet, conn)) { goto close_conn; } conn->net->m.set_client_option(conn->net, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (const char *) &verify TSRMLS_CC); if (FAIL == conn->net->m.enable_ssl(conn->net TSRMLS_CC)) { goto end; } } } #else auth_packet->client_flags &= ~CLIENT_SSL; if (!PACKET_WRITE(auth_packet, conn)) { goto close_conn; } #endif ret = PASS; end: PACKET_FREE(auth_packet); DBG_RETURN(ret); close_conn: CONN_SET_STATE(conn, CONN_QUIT_SENT); conn->m->send_close(conn TSRMLS_CC); SET_CLIENT_ERROR(*conn->error_info, CR_SERVER_GONE_ERROR, UNKNOWN_SQLSTATE, mysqlnd_server_gone); PACKET_FREE(auth_packet); DBG_RETURN(ret); }
165,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BaseRenderingContext2D::drawImage(ScriptState* script_state, CanvasImageSource* image_source, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exception_state) { if (!DrawingCanvas()) return; double start_time = 0; Optional<CustomCountHistogram> timer; if (!IsPaint2D()) { start_time = WTF::MonotonicallyIncreasingTime(); if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_gpu, ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_gpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_gpu, ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_gpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svggpu, ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svggpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_gpu, ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_gpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_gpu, ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_gpu); } } else { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_cpu, ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_cpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_cpu, ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_cpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svgcpu, ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svgcpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_cpu, ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_cpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_cpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_cpu, ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_cpu); } } } scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; if (!image_source->IsVideoElement()) { AccelerationHint hint = (HasImageBuffer() && GetImageBuffer()->IsAccelerated()) ? kPreferAcceleration : kPreferNoAcceleration; image = image_source->GetSourceImageForCanvas(&source_image_status, hint, kSnapshotReasonDrawImage, default_object_size); if (source_image_status == kUndecodableSourceImageStatus) { exception_state.ThrowDOMException( kInvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); } if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize image_size = image_source->ElementSize(default_object_size); ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect, &dst_rect); image_source->AdjustDrawRects(&src_rect, &dst_rect); if (src_rect.IsEmpty()) return; DisableDeferralReason reason = kDisableDeferralReasonUnknown; if (ShouldDisableDeferral(image_source, &reason)) DisableDeferral(reason); else if (image->IsTextureBacked()) DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage); ValidateStateStack(); WillDrawImage(image_source); ValidateStateStack(); ImageBuffer* buffer = GetImageBuffer(); if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) { float src_area = src_rect.Width() * src_rect.Height(); if (src_area > CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) { this->DisableAcceleration(); } else if (src_area > CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimit) { SkRect bounds = dst_rect; SkMatrix ctm = DrawingCanvas()->getTotalMatrix(); ctm.mapRect(&bounds); float dst_area = dst_rect.Width() * dst_rect.Height(); if (src_area > dst_area * CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimitScaleThreshold) { this->DisableAcceleration(); } } } ValidateStateStack(); if (OriginClean() && WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) { SetOriginTainted(); ClearResolvedFilters(); } Draw( [this, &image_source, &image, &src_rect, dst_rect]( PaintCanvas* c, const PaintFlags* flags) // draw lambda { DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect, flags); }, [this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda { return RectContainsTransformedRect(dst_rect, clip_bounds); }, dst_rect, CanvasRenderingContext2DState::kImagePaintType, image_source->IsOpaque() ? CanvasRenderingContext2DState::kOpaqueImage : CanvasRenderingContext2DState::kNonOpaqueImage); ValidateStateStack(); if (!IsPaint2D()) { DCHECK(start_time); timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) * WTF::Time::kMicrosecondsPerSecond); } } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <[email protected]> Commit-Queue: Chris Harrelson <[email protected]> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
void BaseRenderingContext2D::drawImage(ScriptState* script_state, CanvasImageSource* image_source, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exception_state) { if (!DrawingCanvas()) return; double start_time = 0; Optional<CustomCountHistogram> timer; if (!IsPaint2D()) { start_time = WTF::MonotonicallyIncreasingTime(); if (GetImageBuffer() && GetImageBuffer()->IsAccelerated()) { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_gpu, ("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_gpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_gpu, ("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_gpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svggpu, ("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svggpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_gpu, ("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_gpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_gpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_gpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_gpu, ("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_gpu); } } else { if (image_source->IsVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_video_cpu, ("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_video_cpu); } else if (image_source->IsCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_canvas_cpu, ("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_canvas_cpu); } else if (image_source->IsSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_svgcpu, ("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_svgcpu); } else if (image_source->IsImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_image_bitmap_cpu, ("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_image_bitmap_cpu); } else if (image_source->IsOffscreenCanvas()) { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_offscreencanvas_cpu, ("Blink.Canvas.DrawImage.OffscreenCanvas.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_offscreencanvas_cpu); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL( CustomCountHistogram, scoped_us_counter_others_cpu, ("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scoped_us_counter_others_cpu); } } } scoped_refptr<Image> image; FloatSize default_object_size(Width(), Height()); SourceImageStatus source_image_status = kInvalidSourceImageStatus; if (!image_source->IsVideoElement()) { AccelerationHint hint = (HasImageBuffer() && GetImageBuffer()->IsAccelerated()) ? kPreferAcceleration : kPreferNoAcceleration; image = image_source->GetSourceImageForCanvas(&source_image_status, hint, kSnapshotReasonDrawImage, default_object_size); if (source_image_status == kUndecodableSourceImageStatus) { exception_state.ThrowDOMException( kInvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); } if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(image_source)->HasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect src_rect = NormalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dst_rect = NormalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize image_size = image_source->ElementSize(default_object_size); ClipRectsToImageRect(FloatRect(FloatPoint(), image_size), &src_rect, &dst_rect); image_source->AdjustDrawRects(&src_rect, &dst_rect); if (src_rect.IsEmpty()) return; DisableDeferralReason reason = kDisableDeferralReasonUnknown; if (ShouldDisableDeferral(image_source, &reason)) DisableDeferral(reason); else if (image->IsTextureBacked()) DisableDeferral(kDisableDeferralDrawImageWithTextureBackedSourceImage); ValidateStateStack(); WillDrawImage(image_source); ValidateStateStack(); ImageBuffer* buffer = GetImageBuffer(); if (buffer && buffer->IsAccelerated() && !image_source->IsAccelerated()) { float src_area = src_rect.Width() * src_rect.Height(); if (src_area > CanvasHeuristicParameters::kDrawImageTextureUploadHardSizeLimit) { this->DisableAcceleration(); } else if (src_area > CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimit) { SkRect bounds = dst_rect; SkMatrix ctm = DrawingCanvas()->getTotalMatrix(); ctm.mapRect(&bounds); float dst_area = dst_rect.Width() * dst_rect.Height(); if (src_area > dst_area * CanvasHeuristicParameters:: kDrawImageTextureUploadSoftSizeLimitScaleThreshold) { this->DisableAcceleration(); } } } ValidateStateStack(); if (!origin_tainted_by_content_ && WouldTaintOrigin(image_source, ExecutionContext::From(script_state))) SetOriginTaintedByContent(); Draw( [this, &image_source, &image, &src_rect, dst_rect]( PaintCanvas* c, const PaintFlags* flags) // draw lambda { DrawImageInternal(c, image_source, image.get(), src_rect, dst_rect, flags); }, [this, &dst_rect](const SkIRect& clip_bounds) // overdraw test lambda { return RectContainsTransformedRect(dst_rect, clip_bounds); }, dst_rect, CanvasRenderingContext2DState::kImagePaintType, image_source->IsOpaque() ? CanvasRenderingContext2DState::kOpaqueImage : CanvasRenderingContext2DState::kNonOpaqueImage); ValidateStateStack(); if (!IsPaint2D()) { DCHECK(start_time); timer->Count((WTF::MonotonicallyIncreasingTime() - start_time) * WTF::Time::kMicrosecondsPerSecond); } }
172,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt) { vmxnet_tx_pkt_parse(s->tx_pkt); if (s->needs_vlan) { vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; vmxnet_tx_pkt_reset(s->tx_pkt); } } Commit Message: CWE ID: CWE-20
static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx) { struct Vmxnet3_TxDesc txd; uint32_t txd_idx; uint32_t data_len; hwaddr data_pa; for (;;) { if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) { break; } vmxnet3_dump_tx_descr(&txd); if (!s->skip_current_tx_pkt) { data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE; data_pa = le64_to_cpu(txd.addr); if (!vmxnet_tx_pkt_add_raw_fragment(s->tx_pkt, data_pa, data_len)) { s->skip_current_tx_pkt = true; } } if (s->tx_sop) { vmxnet3_tx_retrieve_metadata(s, &txd); s->tx_sop = false; } if (txd.eop) { if (!s->skip_current_tx_pkt && vmxnet_tx_pkt_parse(s->tx_pkt)) { if (s->needs_vlan) { vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci); } vmxnet3_send_packet(s, qidx); } else { vmxnet3_on_tx_done_update_stats(s, qidx, VMXNET3_PKT_STATUS_ERROR); } vmxnet3_complete_packet(s, qidx, txd_idx); s->tx_sop = true; s->skip_current_tx_pkt = false; vmxnet_tx_pkt_reset(s->tx_pkt); } }
165,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcessIdToFilterMap* GetProcessIdToFilterMap() { static base::NoDestructor<ProcessIdToFilterMap> instance; return instance.get(); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
ProcessIdToFilterMap* GetProcessIdToFilterMap() {
173,043