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: zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; } Commit Message: CWE ID:
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
164,638
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SocketStreamDispatcherHost::SocketStreamDispatcherHost( int render_process_id, ResourceMessageFilter::URLRequestContextSelector* selector, content::ResourceContext* resource_context) : ALLOW_THIS_IN_INITIALIZER_LIST(ssl_delegate_weak_factory_(this)), render_process_id_(render_process_id), url_request_context_selector_(selector), resource_context_(resource_context) { DCHECK(selector); net::WebSocketJob::EnsureInit(); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
SocketStreamDispatcherHost::SocketStreamDispatcherHost( int render_process_id, ResourceMessageFilter::URLRequestContextSelector* selector, content::ResourceContext* resource_context) : render_process_id_(render_process_id), url_request_context_selector_(selector), resource_context_(resource_context) { DCHECK(selector); net::WebSocketJob::EnsureInit(); }
170,993
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_plane(uint8 * in, int width, int height, uint8 * out, int size) { UNUSED(size); int indexw; int indexh; int code; int collen; int replen; int color; int x; int revcode; uint8 * last_line; uint8 * this_line; uint8 * org_in; uint8 * org_out; org_in = in; org_out = out; last_line = 0; indexh = 0; while (indexh < height) { out = (org_out + width * height * 4) - ((indexh + 1) * width * 4); color = 0; this_line = out; indexw = 0; if (last_line == 0) { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { color = CVAL(in); *out = color; out += 4; indexw++; collen--; } while (replen > 0) { *out = color; out += 4; indexw++; replen--; } } } else { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (collen > 0) { x = CVAL(in); if (x & 1) { x = x >> 1; x = x + 1; color = -x; } else { x = x >> 1; color = x; } x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; collen--; } while (replen > 0) { x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; replen--; } } } indexh++; last_line = this_line; } return (int) (in - org_in); } 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
process_plane(uint8 * in, int width, int height, uint8 * out, int size) { UNUSED(size); int indexw; int indexh; int code; int collen; int replen; int color; int x; int revcode; uint8 * last_line; uint8 * this_line; uint8 * org_in; uint8 * org_out; org_in = in; org_out = out; last_line = 0; indexh = 0; while (indexh < height) { out = (org_out + width * height * 4) - ((indexh + 1) * width * 4); color = 0; this_line = out; indexw = 0; if (last_line == 0) { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (indexw < width && collen > 0) { color = CVAL(in); *out = color; out += 4; indexw++; collen--; } while (indexw < width && replen > 0) { *out = color; out += 4; indexw++; replen--; } } } else { while (indexw < width) { code = CVAL(in); replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; if ((revcode <= 47) && (revcode >= 16)) { replen = revcode; collen = 0; } while (indexw < width && collen > 0) { x = CVAL(in); if (x & 1) { x = x >> 1; x = x + 1; color = -x; } else { x = x >> 1; color = x; } x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; collen--; } while (indexw < width && replen > 0) { x = last_line[indexw * 4] + color; *out = x; out += 4; indexw++; replen--; } } } indexh++; last_line = this_line; } return (int) (in - org_in); }
169,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllClients(); DCHECK(sessions_.empty()); InnerAttachClient(client); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void DevToolsAgentHostImpl::ForceAttachClient(DevToolsAgentHostClient* client) { if (SessionByClient(client)) return; scoped_refptr<DevToolsAgentHostImpl> protect(this); if (!sessions_.empty()) ForceDetachAllSessions(); DCHECK(sessions_.empty()); InnerAttachClient(client, false /* restricted */); }
173,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hidp_setup_hid(struct hidp_session *session, struct hidp_connadd_req *req) { struct hid_device *hid; int err; session->rd_data = kzalloc(req->rd_size, GFP_KERNEL); if (!session->rd_data) return -ENOMEM; if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) { err = -EFAULT; goto fault; } session->rd_size = req->rd_size; hid = hid_allocate_device(); if (IS_ERR(hid)) { err = PTR_ERR(hid); goto fault; } session->hid = hid; hid->driver_data = session; hid->bus = BUS_BLUETOOTH; hid->vendor = req->vendor; hid->product = req->product; hid->version = req->version; hid->country = req->country; strncpy(hid->name, req->name, 128); snprintf(hid->phys, sizeof(hid->phys), "%pMR", &bt_sk(session->ctrl_sock->sk)->src); snprintf(hid->uniq, sizeof(hid->uniq), "%pMR", &bt_sk(session->ctrl_sock->sk)->dst); hid->dev.parent = &session->conn->dev; hid->ll_driver = &hidp_hid_driver; hid->hid_get_raw_report = hidp_get_raw_report; hid->hid_output_raw_report = hidp_output_raw_report; /* True if device is blacklisted in drivers/hid/hid-core.c */ if (hid_ignore(hid)) { hid_destroy_device(session->hid); session->hid = NULL; return -ENODEV; } return 0; fault: kfree(session->rd_data); session->rd_data = NULL; return err; } Commit Message: Bluetooth: Fix incorrect strncpy() in hidp_setup_hid() The length parameter should be sizeof(req->name) - 1 because there is no guarantee that string provided by userspace will contain the trailing '\0'. Can be easily reproduced by manually setting req->name to 128 non-zero bytes prior to ioctl(HIDPCONNADD) and checking the device name setup on input subsystem: $ cat /sys/devices/pnp0/00\:04/tty/ttyS0/hci0/hci0\:1/input8/name AAAAAA[...]AAAAAAAAf0:af:f0:af:f0:af ("f0:af:f0:af:f0:af" is the device bluetooth address, taken from "phys" field in struct hid_device due to overflow.) Cc: [email protected] Signed-off-by: Anderson Lizardo <[email protected]> Acked-by: Marcel Holtmann <[email protected]> Signed-off-by: Gustavo Padovan <[email protected]> CWE ID: CWE-200
static int hidp_setup_hid(struct hidp_session *session, struct hidp_connadd_req *req) { struct hid_device *hid; int err; session->rd_data = kzalloc(req->rd_size, GFP_KERNEL); if (!session->rd_data) return -ENOMEM; if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) { err = -EFAULT; goto fault; } session->rd_size = req->rd_size; hid = hid_allocate_device(); if (IS_ERR(hid)) { err = PTR_ERR(hid); goto fault; } session->hid = hid; hid->driver_data = session; hid->bus = BUS_BLUETOOTH; hid->vendor = req->vendor; hid->product = req->product; hid->version = req->version; hid->country = req->country; strncpy(hid->name, req->name, sizeof(req->name) - 1); snprintf(hid->phys, sizeof(hid->phys), "%pMR", &bt_sk(session->ctrl_sock->sk)->src); snprintf(hid->uniq, sizeof(hid->uniq), "%pMR", &bt_sk(session->ctrl_sock->sk)->dst); hid->dev.parent = &session->conn->dev; hid->ll_driver = &hidp_hid_driver; hid->hid_get_raw_report = hidp_get_raw_report; hid->hid_output_raw_report = hidp_output_raw_report; /* True if device is blacklisted in drivers/hid/hid-core.c */ if (hid_ignore(hid)) { hid_destroy_device(session->hid); session->hid = NULL; return -ENODEV; } return 0; fault: kfree(session->rd_data); session->rd_data = NULL; return err; }
166,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ihevcd_create(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { ihevcd_cxa_create_op_t *ps_create_op; WORD32 ret; codec_t *ps_codec; ps_create_op = (ihevcd_cxa_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ret = ihevcd_allocate_static_bufs(&ps_codec_obj, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if((IV_FAIL == ret) && (NULL != ps_codec_obj)) { ihevcd_free_static_bufs(ps_codec_obj); ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; ret = ihevcd_init(ps_codec); TRACE_INIT(NULL); STATS_INIT(); return ret; } Commit Message: Decoder: Handle ps_codec_obj memory allocation failure gracefully If memory allocation for ps_codec_obj fails, return gracefully with an error code. All other allocation failures are handled correctly. Bug: 68299873 Test: before/after with always-failing malloc Change-Id: I5e6c07b147b13df81e65476851662d4b55d33b83 (cherry picked from commit a966e2a65dd901151ce7f4481d0084840c9a0f7e) CWE ID: CWE-770
WORD32 ihevcd_create(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) { ihevcd_cxa_create_ip_t *ps_create_ip; ihevcd_cxa_create_op_t *ps_create_op; WORD32 ret; codec_t *ps_codec; ps_create_ip = (ihevcd_cxa_create_ip_t *)pv_api_ip; ps_create_op = (ihevcd_cxa_create_op_t *)pv_api_op; ps_create_op->s_ivd_create_op_t.u4_error_code = 0; ps_codec_obj = NULL; ret = ihevcd_allocate_static_bufs(&ps_codec_obj, pv_api_ip, pv_api_op); /* If allocation of some buffer fails, then free buffers allocated till then */ if(IV_FAIL == ret) { if(NULL != ps_codec_obj) { if(ps_codec_obj->pv_codec_handle) { ihevcd_free_static_bufs(ps_codec_obj); } else { void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf); void *pv_mem_ctxt; pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free; pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt; pf_aligned_free(pv_mem_ctxt, ps_codec_obj); } } ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED; ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR; return IV_FAIL; } ps_codec = (codec_t *)ps_codec_obj->pv_codec_handle; ret = ihevcd_init(ps_codec); TRACE_INIT(NULL); STATS_INIT(); return ret; }
174,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { if (original_skia_image_) { std::unique_ptr<gpu::SyncToken> sync_token = base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken())); if (original_skia_image_thread_id_ != Platform::Current()->CurrentThread()->ThreadId()) { PostCrossThreadTask( *original_skia_image_task_runner_, FROM_HERE, CrossThreadBind( &DestroySkImageOnOriginalThread, std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), WTF::Passed(std::move(sync_token)))); } else { DestroySkImageOnOriginalThread( std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), std::move(sync_token)); } } } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (original_skia_image_) { std::unique_ptr<gpu::SyncToken> sync_token = base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken())); if (!original_skia_image_task_runner_->BelongsToCurrentThread()) { PostCrossThreadTask( *original_skia_image_task_runner_, FROM_HERE, CrossThreadBind( &DestroySkImageOnOriginalThread, std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), WTF::Passed(std::move(sync_token)))); } else { DestroySkImageOnOriginalThread( std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), std::move(sync_token)); } } }
172,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: bool GLES2DecoderImpl::SimulateAttrib0( const char* function_name, 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, function_name, "Simulating attrib 0"); return false; } PerformanceWarning( "Attribute 0 is disabled. This has signficant performance penalty"); 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, function_name, "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; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool GLES2DecoderImpl::SimulateAttrib0( const char* function_name, 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; uint32 size_needed = 0; if (num_vertices == 0 || !SafeMultiplyUint32(num_vertices, sizeof(Vec4), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } PerformanceWarning( "Attribute 0 is disabled. This has signficant performance penalty"); 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, function_name, "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; }
170,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TIFFFlushData1(TIFF* tif) { if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) { if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (!TIFFAppendToStrip(tif, isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, tif->tif_rawdata, tif->tif_rawcc)) return (0); tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; } return (1); } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
TIFFFlushData1(TIFF* tif) { if (tif->tif_rawcc > 0 && tif->tif_flags & TIFF_BUF4WRITE ) { if (!isFillOrder(tif, tif->tif_dir.td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits((uint8*)tif->tif_rawdata, tif->tif_rawcc); if (!TIFFAppendToStrip(tif, isTiled(tif) ? tif->tif_curtile : tif->tif_curstrip, tif->tif_rawdata, tif->tif_rawcc)) { /* We update those variables even in case of error since there's */ /* code that doesn't really check the return code of this */ /* function */ tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; return (0); } tif->tif_rawcc = 0; tif->tif_rawcp = tif->tif_rawdata; } return (1); }
166,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrokerDuplicateHandle(HANDLE source_handle, DWORD target_process_id, HANDLE* target_handle, DWORD desired_access, DWORD options) { if (!g_target_services) { base::win::ScopedHandle target_process(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, target_process_id)); if (!target_process.IsValid()) return false; if (!::DuplicateHandle(::GetCurrentProcess(), source_handle, target_process, target_handle, desired_access, FALSE, options)) { return false; } return true; } ResultCode result = g_target_services->DuplicateHandle(source_handle, target_process_id, target_handle, desired_access, options); return SBOX_ALL_OK == result; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool BrokerDuplicateHandle(HANDLE source_handle, DWORD target_process_id, HANDLE* target_handle, DWORD desired_access, DWORD options) { // If our process is the target just duplicate the handle. if (::GetCurrentProcessId() == target_process_id) { return !!::DuplicateHandle(::GetCurrentProcess(), source_handle, ::GetCurrentProcess(), target_handle, desired_access, FALSE, options); } // Try the broker next if (g_target_services && g_target_services->DuplicateHandle(source_handle, target_process_id, target_handle, desired_access, options) == SBOX_ALL_OK) { return true; } // Finally, see if we already have access to the process. base::win::ScopedHandle target_process; target_process.Set(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, target_process_id)); if (target_process.IsValid()) { return !!::DuplicateHandle(::GetCurrentProcess(), source_handle, target_process, target_handle, desired_access, FALSE, options); } return false; }
170,946
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) { WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (frame) { WebDataSource* data_source = frame->dataSource(); if (data_source) { DocumentState* document_state = DocumentState::FromDataSource(data_source); v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Object> csi = v8::Object::New(isolate); base::Time now = base::Time::Now(); base::Time start = document_state->request_time().is_null() ? document_state->start_load_time() : document_state->request_time(); base::Time onload = document_state->finish_document_load_time(); base::TimeDelta page = now - start; csi->Set(v8::String::NewFromUtf8(isolate, "startE"), v8::Number::New(isolate, floor(start.ToDoubleT() * 1000))); csi->Set(v8::String::NewFromUtf8(isolate, "onloadT"), v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000))); csi->Set(v8::String::NewFromUtf8(isolate, "pageT"), v8::Number::New(isolate, page.InMillisecondsF())); csi->Set( v8::String::NewFromUtf8(isolate, "tran"), v8::Number::New( isolate, GetCSITransitionType(data_source->navigationType()))); args.GetReturnValue().Set(csi); return; } } args.GetReturnValue().SetNull(); return; } Commit Message: Cache csi info before passing it to JS setters. JS setters invalidate the pointers frame, data_source and document_state. BUG=590455 Review URL: https://codereview.chromium.org/1751553002 Cr-Commit-Position: refs/heads/master@{#379047} CWE ID:
static void GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) { args.GetReturnValue().SetNull(); WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); if (!frame) { return; } WebDataSource* data_source = frame->dataSource(); if (!data_source) { return; } DocumentState* document_state = DocumentState::FromDataSource(data_source); if (!document_state) { return; } base::Time now = base::Time::Now(); base::Time start = document_state->request_time().is_null() ? document_state->start_load_time() : document_state->request_time(); base::Time onload = document_state->finish_document_load_time(); base::TimeDelta page = now - start; int navigation_type = GetCSITransitionType(data_source->navigationType()); // Important: |frame|, |data_source| and |document_state| should not be // referred to below this line, as JS setters below can invalidate these // pointers. v8::Isolate* isolate = args.GetIsolate(); v8::Local<v8::Context> ctx = isolate->GetCurrentContext(); v8::Local<v8::Object> csi = v8::Object::New(isolate); if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "startE", v8::NewStringType::kNormal) .ToLocalChecked(), v8::Number::New(isolate, floor(start.ToDoubleT() * 1000))) .FromMaybe(false)) { return; } if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "onloadT", v8::NewStringType::kNormal) .ToLocalChecked(), v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000))) .FromMaybe(false)) { return; } if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "pageT", v8::NewStringType::kNormal) .ToLocalChecked(), v8::Number::New(isolate, page.InMillisecondsF())) .FromMaybe(false)) { return; } if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, "tran", v8::NewStringType::kNormal) .ToLocalChecked(), v8::Number::New(isolate, navigation_type)) .FromMaybe(false)) { return; } args.GetReturnValue().Set(csi); }
172,117
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char* argv[]) { char* name = argv[0]; bool applyColorCorrection = false; #if USE(QCMSLIB) if (argc >= 2 && strcmp(argv[1], "--color-correct") == 0) applyColorCorrection = (--argc, ++argv, true); if (argc < 2) { fprintf(stderr, "Usage: %s [--color-correct] file [iterations] [packetSize]\n", name); exit(1); } #else if (argc < 2) { fprintf(stderr, "Usage: %s file [iterations] [packetSize]\n", name); exit(1); } #endif size_t iterations = 1; if (argc >= 3) { char* end = 0; iterations = strtol(argv[2], &end, 10); if (*end != '\0' || !iterations) { fprintf(stderr, "Second argument should be number of iterations. " "The default is 1. You supplied %s\n", argv[2]); exit(1); } } size_t packetSize = 0; if (argc >= 4) { char* end = 0; packetSize = strtol(argv[3], &end, 10); if (*end != '\0') { fprintf(stderr, "Third argument should be packet size. Default is " "0, meaning to decode the entire image in one packet. You " "supplied %s\n", argv[3]); exit(1); } } class WebPlatform : public blink::Platform { public: const unsigned char* getTraceCategoryEnabledFlag(const char*) override { return reinterpret_cast<const unsigned char *>("nope-none-nada"); } void cryptographicallyRandomValues(unsigned char*, size_t) override { } void screenColorProfile(WebVector<char>* profile) override { getScreenColorProfile(profile); // Returns a whacked color profile. } }; blink::initializeWithoutV8(new WebPlatform()); #if USE(QCMSLIB) ImageDecoder::qcmsOutputDeviceProfile(); // Initialize screen colorProfile. #endif RefPtr<SharedBuffer> data = readFile(argv[1]); if (!data.get() || !data->size()) { fprintf(stderr, "Error reading image data from [%s]\n", argv[1]); exit(2); } data->data(); double totalTime = 0.0; for (size_t i = 0; i < iterations; ++i) { double startTime = getCurrentTime(); bool decoded = decodeImageData(data.get(), applyColorCorrection, packetSize); double elapsedTime = getCurrentTime() - startTime; totalTime += elapsedTime; if (!decoded) { fprintf(stderr, "Image decode failed [%s]\n", argv[1]); exit(3); } } double averageTime = totalTime / static_cast<double>(iterations); printf("%f %f\n", totalTime, averageTime); return 0; } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310
int main(int argc, char* argv[]) { char* name = argv[0]; bool applyColorCorrection = false; #if USE(QCMSLIB) if (argc >= 2 && strcmp(argv[1], "--color-correct") == 0) applyColorCorrection = (--argc, ++argv, true); if (argc < 2) { fprintf(stderr, "Usage: %s [--color-correct] file [iterations] [packetSize]\n", name); exit(1); } #else if (argc < 2) { fprintf(stderr, "Usage: %s file [iterations] [packetSize]\n", name); exit(1); } #endif size_t iterations = 1; if (argc >= 3) { char* end = 0; iterations = strtol(argv[2], &end, 10); if (*end != '\0' || !iterations) { fprintf(stderr, "Second argument should be number of iterations. " "The default is 1. You supplied %s\n", argv[2]); exit(1); } } size_t packetSize = 0; if (argc >= 4) { char* end = 0; packetSize = strtol(argv[3], &end, 10); if (*end != '\0') { fprintf(stderr, "Third argument should be packet size. Default is " "0, meaning to decode the entire image in one packet. You " "supplied %s\n", argv[3]); exit(1); } } class WebPlatform : public blink::Platform { public: const unsigned char* getTraceCategoryEnabledFlag(const char*) override { return reinterpret_cast<const unsigned char *>("nope-none-nada"); } void cryptographicallyRandomValues(unsigned char*, size_t) override { RELEASE_ASSERT_NOT_REACHED(); } void screenColorProfile(WebVector<char>* profile) override { getScreenColorProfile(profile); // Returns a whacked color profile. } }; blink::initializeWithoutV8(new WebPlatform()); #if USE(QCMSLIB) ImageDecoder::qcmsOutputDeviceProfile(); // Initialize screen colorProfile. #endif RefPtr<SharedBuffer> data = readFile(argv[1]); if (!data.get() || !data->size()) { fprintf(stderr, "Error reading image data from [%s]\n", argv[1]); exit(2); } data->data(); double totalTime = 0.0; for (size_t i = 0; i < iterations; ++i) { double startTime = getCurrentTime(); bool decoded = decodeImageData(data.get(), applyColorCorrection, packetSize); double elapsedTime = getCurrentTime() - startTime; totalTime += elapsedTime; if (!decoded) { fprintf(stderr, "Image decode failed [%s]\n", argv[1]); exit(3); } } double averageTime = totalTime / static_cast<double>(iterations); printf("%f %f\n", totalTime, averageTime); return 0; }
172,240
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr_shortform_addname(xfs_da_args_t *args) { int newsize, forkoff, retval; trace_xfs_attr_sf_addname(args); retval = xfs_attr_shortform_lookup(args); if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) { return retval; } else if (retval == -EEXIST) { if (args->flags & ATTR_CREATE) return retval; retval = xfs_attr_shortform_remove(args); ASSERT(retval == 0); } if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX || args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX) return -ENOSPC; newsize = XFS_ATTR_SF_TOTSIZE(args->dp); newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen); forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize); if (!forkoff) return -ENOSPC; xfs_attr_shortform_add(args, forkoff); return 0; } Commit Message: xfs: don't fail when converting shortform attr to long form during ATTR_REPLACE Kanda Motohiro reported that expanding a tiny xattr into a large xattr fails on XFS because we remove the tiny xattr from a shortform fork and then try to re-add it after converting the fork to extents format having not removed the ATTR_REPLACE flag. This fails because the attr is no longer present, causing a fs shutdown. This is derived from the patch in his bug report, but we really shouldn't ignore a nonzero retval from the remove call. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199119 Reported-by: [email protected] Reviewed-by: Dave Chinner <[email protected]> Reviewed-by: Christoph Hellwig <[email protected]> Signed-off-by: Darrick J. Wong <[email protected]> CWE ID: CWE-754
xfs_attr_shortform_addname(xfs_da_args_t *args) { int newsize, forkoff, retval; trace_xfs_attr_sf_addname(args); retval = xfs_attr_shortform_lookup(args); if ((args->flags & ATTR_REPLACE) && (retval == -ENOATTR)) { return retval; } else if (retval == -EEXIST) { if (args->flags & ATTR_CREATE) return retval; retval = xfs_attr_shortform_remove(args); if (retval) return retval; /* * Since we have removed the old attr, clear ATTR_REPLACE so * that the leaf format add routine won't trip over the attr * not being around. */ args->flags &= ~ATTR_REPLACE; } if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX || args->valuelen >= XFS_ATTR_SF_ENTSIZE_MAX) return -ENOSPC; newsize = XFS_ATTR_SF_TOTSIZE(args->dp); newsize += XFS_ATTR_SF_ENTSIZE_BYNAME(args->namelen, args->valuelen); forkoff = xfs_attr_shortform_bytesfit(args->dp, newsize); if (!forkoff) return -ENOSPC; xfs_attr_shortform_add(args, forkoff); return 0; }
169,000
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 udf_readdir(struct file *file, struct dir_context *ctx) { struct inode *dir = file_inode(file); struct udf_inode_info *iinfo = UDF_I(dir); struct udf_fileident_bh fibh = { .sbh = NULL, .ebh = NULL}; struct fileIdentDesc *fi = NULL; struct fileIdentDesc cfi; int block, iblock; loff_t nf_pos; int flen; unsigned char *fname = NULL; unsigned char *nameptr; uint16_t liu; uint8_t lfi; loff_t size = udf_ext0_offset(dir) + dir->i_size; struct buffer_head *tmp, *bha[16]; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; int i, num, ret = 0; struct extent_position epos = { NULL, 0, {0, 0} }; if (ctx->pos == 0) { if (!dir_emit_dot(file, ctx)) return 0; ctx->pos = 1; } nf_pos = (ctx->pos - 1) << 2; if (nf_pos >= size) goto out; fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) { ret = -ENOMEM; goto out; } if (nf_pos == 0) nf_pos = udf_ext0_offset(dir); fibh.soffset = fibh.eoffset = nf_pos & (dir->i_sb->s_blocksize - 1); if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, nf_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) { ret = -ENOENT; goto out; } block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else { offset = 0; } if (!(fibh.sbh = fibh.ebh = udf_tread(dir->i_sb, block))) { ret = -EIO; goto out; } if (!(offset & ((16 >> (dir->i_sb->s_blocksize_bits - 9)) - 1))) { i = 16 >> (dir->i_sb->s_blocksize_bits - 9); if (i + offset > (elen >> dir->i_sb->s_blocksize_bits)) i = (elen >> dir->i_sb->s_blocksize_bits) - offset; for (num = 0; i > 0; i--) { block = udf_get_lb_pblock(dir->i_sb, &eloc, offset + i); tmp = udf_tgetblk(dir->i_sb, block); if (tmp && !buffer_uptodate(tmp) && !buffer_locked(tmp)) bha[num++] = tmp; else brelse(tmp); } if (num) { ll_rw_block(READA, num, bha); for (i = 0; i < num; i++) brelse(bha[i]); } } } while (nf_pos < size) { struct kernel_lb_addr tloc; ctx->pos = (nf_pos >> 2) + 1; fi = udf_fileident_read(dir, &nf_pos, &fibh, &cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out; liu = le16_to_cpu(cfi.lengthOfImpUse); lfi = cfi.lengthFileIdent; if (fibh.sbh == fibh.ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh.soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) { nameptr = (char *)(fibh.ebh->b_data + poffset - lfi); } else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh.ebh->b_data, poffset); } } if ((cfi.fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi.fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if (cfi.fileCharacteristics & FID_FILE_CHAR_PARENT) { if (!dir_emit_dotdot(file, ctx)) goto out; continue; } flen = udf_get_filename(dir->i_sb, nameptr, fname, lfi); if (!flen) continue; tloc = lelb_to_cpu(cfi.icb.extLocation); iblock = udf_get_lb_pblock(dir->i_sb, &tloc, 0); if (!dir_emit(ctx, fname, flen, iblock, DT_UNKNOWN)) goto out; } /* end while */ ctx->pos = (nf_pos >> 2) + 1; out: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); kfree(fname); return ret; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17
static int udf_readdir(struct file *file, struct dir_context *ctx) { struct inode *dir = file_inode(file); struct udf_inode_info *iinfo = UDF_I(dir); struct udf_fileident_bh fibh = { .sbh = NULL, .ebh = NULL}; struct fileIdentDesc *fi = NULL; struct fileIdentDesc cfi; int block, iblock; loff_t nf_pos; int flen; unsigned char *fname = NULL; unsigned char *nameptr; uint16_t liu; uint8_t lfi; loff_t size = udf_ext0_offset(dir) + dir->i_size; struct buffer_head *tmp, *bha[16]; struct kernel_lb_addr eloc; uint32_t elen; sector_t offset; int i, num, ret = 0; struct extent_position epos = { NULL, 0, {0, 0} }; if (ctx->pos == 0) { if (!dir_emit_dot(file, ctx)) return 0; ctx->pos = 1; } nf_pos = (ctx->pos - 1) << 2; if (nf_pos >= size) goto out; fname = kmalloc(UDF_NAME_LEN, GFP_NOFS); if (!fname) { ret = -ENOMEM; goto out; } if (nf_pos == 0) nf_pos = udf_ext0_offset(dir); fibh.soffset = fibh.eoffset = nf_pos & (dir->i_sb->s_blocksize - 1); if (iinfo->i_alloc_type != ICBTAG_FLAG_AD_IN_ICB) { if (inode_bmap(dir, nf_pos >> dir->i_sb->s_blocksize_bits, &epos, &eloc, &elen, &offset) != (EXT_RECORDED_ALLOCATED >> 30)) { ret = -ENOENT; goto out; } block = udf_get_lb_pblock(dir->i_sb, &eloc, offset); if ((++offset << dir->i_sb->s_blocksize_bits) < elen) { if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_SHORT) epos.offset -= sizeof(struct short_ad); else if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_LONG) epos.offset -= sizeof(struct long_ad); } else { offset = 0; } if (!(fibh.sbh = fibh.ebh = udf_tread(dir->i_sb, block))) { ret = -EIO; goto out; } if (!(offset & ((16 >> (dir->i_sb->s_blocksize_bits - 9)) - 1))) { i = 16 >> (dir->i_sb->s_blocksize_bits - 9); if (i + offset > (elen >> dir->i_sb->s_blocksize_bits)) i = (elen >> dir->i_sb->s_blocksize_bits) - offset; for (num = 0; i > 0; i--) { block = udf_get_lb_pblock(dir->i_sb, &eloc, offset + i); tmp = udf_tgetblk(dir->i_sb, block); if (tmp && !buffer_uptodate(tmp) && !buffer_locked(tmp)) bha[num++] = tmp; else brelse(tmp); } if (num) { ll_rw_block(READA, num, bha); for (i = 0; i < num; i++) brelse(bha[i]); } } } while (nf_pos < size) { struct kernel_lb_addr tloc; ctx->pos = (nf_pos >> 2) + 1; fi = udf_fileident_read(dir, &nf_pos, &fibh, &cfi, &epos, &eloc, &elen, &offset); if (!fi) goto out; liu = le16_to_cpu(cfi.lengthOfImpUse); lfi = cfi.lengthFileIdent; if (fibh.sbh == fibh.ebh) { nameptr = fi->fileIdent + liu; } else { int poffset; /* Unpaded ending offset */ poffset = fibh.soffset + sizeof(struct fileIdentDesc) + liu + lfi; if (poffset >= lfi) { nameptr = (char *)(fibh.ebh->b_data + poffset - lfi); } else { nameptr = fname; memcpy(nameptr, fi->fileIdent + liu, lfi - poffset); memcpy(nameptr + lfi - poffset, fibh.ebh->b_data, poffset); } } if ((cfi.fileCharacteristics & FID_FILE_CHAR_DELETED) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNDELETE)) continue; } if ((cfi.fileCharacteristics & FID_FILE_CHAR_HIDDEN) != 0) { if (!UDF_QUERY_FLAG(dir->i_sb, UDF_FLAG_UNHIDE)) continue; } if (cfi.fileCharacteristics & FID_FILE_CHAR_PARENT) { if (!dir_emit_dotdot(file, ctx)) goto out; continue; } flen = udf_get_filename(dir->i_sb, nameptr, lfi, fname, UDF_NAME_LEN); if (!flen) continue; tloc = lelb_to_cpu(cfi.icb.extLocation); iblock = udf_get_lb_pblock(dir->i_sb, &tloc, 0); if (!dir_emit(ctx, fname, flen, iblock, DT_UNKNOWN)) goto out; } /* end while */ ctx->pos = (nf_pos >> 2) + 1; out: if (fibh.sbh != fibh.ebh) brelse(fibh.ebh); brelse(fibh.sbh); brelse(epos.bh); kfree(fname); return ret; }
166,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_@_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_@(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_@_set(PNG_CONST image_transform *this,
173,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp) { if (d_mountpoint(dentry)) return 1; if (nfsd4_is_junction(dentry)) return 1; if (!(exp->ex_flags & NFSEXP_V4ROOT)) return 0; return d_inode(dentry) != NULL; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
int nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp) { if (!d_inode(dentry)) return 0; if (exp->ex_flags & NFSEXP_V4ROOT) return 1; if (nfsd4_is_junction(dentry)) return 1; if (d_mountpoint(dentry)) /* * Might only be a mountpoint in a different namespace, * but we need to check. */ return 2; return 0; }
168,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GDataCache::Pin(const std::string& resource_id, const std::string& md5, FileOperationType file_operation_type, base::PlatformFileError* error) { AssertOnSequencedWorkerPool(); DCHECK(error); FilePath source_path; FilePath dest_path; FilePath symlink_path; bool create_symlink = true; int cache_state = CACHE_STATE_PINNED; CacheSubDirectoryType sub_dir_type = CACHE_TYPE_PERSISTENT; scoped_ptr<CacheEntry> cache_entry = GetCacheEntry(resource_id, md5); if (!cache_entry.get()) { // Entry does not exist in cache. dest_path = FilePath::FromUTF8Unsafe(util::kSymLinkToDevNull); source_path = dest_path; sub_dir_type = CACHE_TYPE_PINNED; } else { // File exists in cache, determines destination path. cache_state |= cache_entry->cache_state; if (cache_entry->IsDirty() || cache_entry->IsMounted()) { DCHECK_EQ(CACHE_TYPE_PERSISTENT, cache_entry->sub_dir_type); dest_path = GetCacheFilePath(resource_id, md5, cache_entry->sub_dir_type, CACHED_FILE_LOCALLY_MODIFIED); source_path = dest_path; } else { source_path = GetCacheFilePath(resource_id, md5, cache_entry->sub_dir_type, CACHED_FILE_FROM_SERVER); if (cache_entry->sub_dir_type == CACHE_TYPE_PINNED) { dest_path = source_path; create_symlink = false; } else { // File exists, move it to persistent dir. dest_path = GetCacheFilePath(resource_id, md5, CACHE_TYPE_PERSISTENT, CACHED_FILE_FROM_SERVER); } } } if (create_symlink) { symlink_path = GetCacheFilePath(resource_id, std::string(), CACHE_TYPE_PINNED, CACHED_FILE_FROM_SERVER); } *error = ModifyCacheState(source_path, dest_path, file_operation_type, symlink_path, create_symlink); if (*error == base::PLATFORM_FILE_OK) { metadata_->UpdateCache(resource_id, md5, sub_dir_type, cache_state); } } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void GDataCache::Pin(const std::string& resource_id, const std::string& md5, FileOperationType file_operation_type, base::PlatformFileError* error) { AssertOnSequencedWorkerPool(); DCHECK(error); FilePath source_path; FilePath dest_path; FilePath symlink_path; bool create_symlink = true; int cache_state = CACHE_STATE_PINNED; CacheSubDirectoryType sub_dir_type = CACHE_TYPE_PERSISTENT; scoped_ptr<CacheEntry> cache_entry = GetCacheEntry(resource_id, md5); if (!cache_entry.get()) { // Entry does not exist in cache. dest_path = FilePath(kSymLinkToDevNull); source_path = dest_path; sub_dir_type = CACHE_TYPE_PINNED; } else { // File exists in cache, determines destination path. cache_state |= cache_entry->cache_state; if (cache_entry->IsDirty() || cache_entry->IsMounted()) { DCHECK_EQ(CACHE_TYPE_PERSISTENT, cache_entry->sub_dir_type); dest_path = GetCacheFilePath(resource_id, md5, cache_entry->sub_dir_type, CACHED_FILE_LOCALLY_MODIFIED); source_path = dest_path; } else { source_path = GetCacheFilePath(resource_id, md5, cache_entry->sub_dir_type, CACHED_FILE_FROM_SERVER); if (cache_entry->sub_dir_type == CACHE_TYPE_PINNED) { dest_path = source_path; create_symlink = false; } else { // File exists, move it to persistent dir. dest_path = GetCacheFilePath(resource_id, md5, CACHE_TYPE_PERSISTENT, CACHED_FILE_FROM_SERVER); } } } if (create_symlink) { symlink_path = GetCacheFilePath(resource_id, std::string(), CACHE_TYPE_PINNED, CACHED_FILE_FROM_SERVER); } *error = ModifyCacheState(source_path, dest_path, file_operation_type, symlink_path, create_symlink); if (*error == base::PLATFORM_FILE_OK) { metadata_->UpdateCache(resource_id, md5, sub_dir_type, cache_state); } }
170,864
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSelection::IsHandleVisible() const { return GetSelectionInDOMTree().IsHandleVisible(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool FrameSelection::IsHandleVisible() const {
171,755
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SaveTestFileSystem() { GDataRootDirectoryProto root; GDataDirectoryProto* root_dir = root.mutable_gdata_directory(); GDataEntryProto* file_base = root_dir->mutable_gdata_entry(); PlatformFileInfoProto* platform_info = file_base->mutable_file_info(); file_base->set_title("drive"); platform_info->set_is_directory(true); GDataFileProto* file = root_dir->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File1"); platform_info->set_is_directory(false); platform_info->set_size(1048576); GDataDirectoryProto* dir1 = root_dir->add_child_directories(); file_base = dir1->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("Dir1"); platform_info->set_is_directory(true); file = dir1->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File2"); platform_info->set_is_directory(false); platform_info->set_size(555); GDataDirectoryProto* dir2 = dir1->add_child_directories(); file_base = dir2->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("SubDir2"); platform_info->set_is_directory(true); file = dir2->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File3"); platform_info->set_is_directory(false); platform_info->set_size(12345); std::string serialized_proto; ASSERT_TRUE(root.SerializeToString(&serialized_proto)); ASSERT_TRUE(!serialized_proto.empty()); FilePath cache_dir_path = profile_->GetPath().Append( FILE_PATH_LITERAL("GCache/v1/meta/")); ASSERT_TRUE(file_util::CreateDirectory(cache_dir_path)); const int file_size = static_cast<int>(serialized_proto.length()); ASSERT_EQ(file_util::WriteFile(cache_dir_path.Append("file_system.pb"), serialized_proto.data(), file_size), file_size); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void SaveTestFileSystem() { GDataRootDirectoryProto root; GDataDirectoryProto* root_dir = root.mutable_gdata_directory(); GDataEntryProto* file_base = root_dir->mutable_gdata_entry(); PlatformFileInfoProto* platform_info = file_base->mutable_file_info(); file_base->set_title("drive"); file_base->set_resource_id(kGDataRootDirectoryResourceId); platform_info->set_is_directory(true); GDataFileProto* file = root_dir->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File1"); platform_info->set_is_directory(false); platform_info->set_size(1048576); GDataDirectoryProto* dir1 = root_dir->add_child_directories(); file_base = dir1->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("Dir1"); platform_info->set_is_directory(true); file = dir1->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File2"); platform_info->set_is_directory(false); platform_info->set_size(555); GDataDirectoryProto* dir2 = dir1->add_child_directories(); file_base = dir2->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("SubDir2"); platform_info->set_is_directory(true); file = dir2->add_child_files(); file_base = file->mutable_gdata_entry(); platform_info = file_base->mutable_file_info(); file_base->set_title("File3"); platform_info->set_is_directory(false); platform_info->set_size(12345); std::string serialized_proto; ASSERT_TRUE(root.SerializeToString(&serialized_proto)); ASSERT_TRUE(!serialized_proto.empty()); FilePath cache_dir_path = profile_->GetPath().Append( FILE_PATH_LITERAL("GCache/v1/meta/")); ASSERT_TRUE(file_util::CreateDirectory(cache_dir_path)); const int file_size = static_cast<int>(serialized_proto.length()); ASSERT_EQ(file_util::WriteFile(cache_dir_path.Append("file_system.pb"), serialized_proto.data(), file_size), file_size); }
170,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; memset(perm_addr, 0, sizeof(perm_addr)); netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); }
166,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: check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } if(verbose) D (debug_file, "Authorization line: %s", buf); s_user = strtok_r (buf, ":", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, "Matched user: %s", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; } Commit Message: util: make sure to close the authfile before returning success fixes #136 CWE ID: CWE-200
check_user_token (const char *authfile, const char *username, const char *otp_id, int verbose, FILE *debug_file) { char buf[1024]; char *s_user, *s_token; int retval = AUTH_ERROR; int fd; struct stat st; FILE *opwfile; fd = open(authfile, O_RDONLY, 0); if (fd < 0) { if(verbose) D (debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); return retval; } if (fstat(fd, &st) < 0) { if(verbose) D (debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); close(fd); return retval; } if (!S_ISREG(st.st_mode)) { if(verbose) D (debug_file, "%s is not a regular file", authfile); close(fd); return retval; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if(verbose) D (debug_file, "fdopen: %s", strerror(errno)); close(fd); return retval; } retval = AUTH_NO_TOKENS; while (fgets (buf, 1024, opwfile)) { char *saveptr = NULL; if (buf[strlen (buf) - 1] == '\n') buf[strlen (buf) - 1] = '\0'; if (buf[0] == '#') { /* This is a comment and we may skip it. */ if(verbose) D (debug_file, "Skipping comment line: %s", buf); continue; } if(verbose) D (debug_file, "Authorization line: %s", buf); s_user = strtok_r (buf, ":", &saveptr); if (s_user && strcmp (username, s_user) == 0) { if(verbose) D (debug_file, "Matched user: %s", s_user); retval = AUTH_NOT_FOUND; /* We found at least one line for the user */ do { s_token = strtok_r (NULL, ":", &saveptr); if(verbose) D (debug_file, "Authorization token: %s", s_token); if (s_token && otp_id && strcmp (otp_id, s_token) == 0) { if(verbose) D (debug_file, "Match user/token as %s/%s", username, otp_id); fclose(opwfile); return AUTH_FOUND; } } while (s_token != NULL); } } fclose (opwfile); return retval; }
169,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::MarkAsForeignEntry( int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { AppCacheHost* host = GetHost(host_id); if (!host) return false; host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from); 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::MarkAsForeignEntry( int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { AppCacheHost* host = GetHost(host_id); if (!host) return false; return host->MarkAsForeignEntry(document_url, cache_document_was_loaded_from); }
171,735
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh16(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } }
174,018
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; } Commit Message: CWE ID: CWE-354
int csum_len_for_type(int cst) { switch (cst) { case CSUM_NONE: return 1; case CSUM_MD4_ARCHAIC: return 2; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: return MD4_DIGEST_LEN; case CSUM_MD5: return MD5_DIGEST_LEN; } return 0; }
164,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); usleep(250000); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ usleep(250000); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void a2dp_open_ctrl_path(struct a2dp_stream_common *common) { int i; /* retry logic to catch any timing variations on control channel */ for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { /* connect control channel if not already connected */ if ((common->ctrl_fd = skt_connect(A2DP_CTRL_PATH, common->buffer_sz)) > 0) { /* success, now check if stack is ready */ if (check_a2dp_ready(common) == 0) break; ERROR("error : a2dp not ready, wait 250 ms and retry"); TEMP_FAILURE_RETRY(usleep(250000)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; } /* ctrl channel not ready, wait a bit */ TEMP_FAILURE_RETRY(usleep(250000)); } }
173,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mount *child, *p; struct hlist_node *n; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); umount_tree(child, UMOUNT_SYNC); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: return err; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400
static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mnt_namespace *ns = dest_mnt->mnt_ns; struct mount *child, *p; struct hlist_node *n; int err; /* Is there space to add these mounts to the mount namespace? */ if (!parent_path) { err = count_mounts(ns, source_mnt); if (err) goto out; } if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); child->mnt_parent->mnt_ns->pending_mounts = 0; umount_tree(child, UMOUNT_SYNC); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: ns->pending_mounts = 0; return err; }
167,007
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNameComplex++; #endif /* * Handler for more complex cases */ GROW; c = CUR_CHAR(l); if ((ctxt->options & XML_PARSE_OLD10) == 0) { /* * Use the new checks of production [4] [4a] amd [5] of the * Update 5 of XML-1.0 */ if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_') || (c == ':') || ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF))))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */ (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || /* !start */ (c == '_') || (c == ':') || (c == '-') || (c == '.') || (c == 0xB7) || /* !start */ ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x300) && (c <= 0x36F)) || /* !start */ ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x203F) && (c <= 0x2040)) || /* !start */ ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF)) )) { if (count++ > 100) { count = 0; GROW; } len += l; NEXTL(l); c = CUR_CHAR(l); } } else { if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!IS_LETTER(c) && (c != '_') && (c != ':'))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ ((IS_LETTER(c)) || (IS_DIGIT(c)) || (c == '.') || (c == '-') || (c == '_') || (c == ':') || (IS_COMBINING(c)) || (IS_EXTENDER(c)))) { if (count++ > 100) { count = 0; GROW; } len += l; NEXTL(l); c = CUR_CHAR(l); } } if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r')) return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len)); return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseNameComplex(xmlParserCtxtPtr ctxt) { int len = 0, l; int c; int count = 0; #ifdef DEBUG nbParseNameComplex++; #endif /* * Handler for more complex cases */ GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); c = CUR_CHAR(l); if ((ctxt->options & XML_PARSE_OLD10) == 0) { /* * Use the new checks of production [4] [4a] amd [5] of the * Update 5 of XML-1.0 */ if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!(((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || (c == '_') || (c == ':') || ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF))))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* accelerators */ (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) || /* !start */ (c == '_') || (c == ':') || (c == '-') || (c == '.') || (c == 0xB7) || /* !start */ ((c >= 0xC0) && (c <= 0xD6)) || ((c >= 0xD8) && (c <= 0xF6)) || ((c >= 0xF8) && (c <= 0x2FF)) || ((c >= 0x300) && (c <= 0x36F)) || /* !start */ ((c >= 0x370) && (c <= 0x37D)) || ((c >= 0x37F) && (c <= 0x1FFF)) || ((c >= 0x200C) && (c <= 0x200D)) || ((c >= 0x203F) && (c <= 0x2040)) || /* !start */ ((c >= 0x2070) && (c <= 0x218F)) || ((c >= 0x2C00) && (c <= 0x2FEF)) || ((c >= 0x3001) && (c <= 0xD7FF)) || ((c >= 0xF900) && (c <= 0xFDCF)) || ((c >= 0xFDF0) && (c <= 0xFFFD)) || ((c >= 0x10000) && (c <= 0xEFFFF)) )) { if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); } } else { if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */ (!IS_LETTER(c) && (c != '_') && (c != ':'))) { return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */ ((IS_LETTER(c)) || (IS_DIGIT(c)) || (c == '.') || (c == '-') || (c == '_') || (c == ':') || (IS_COMBINING(c)) || (IS_EXTENDER(c)))) { if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); } len += l; NEXTL(l); c = CUR_CHAR(l); } } if ((*ctxt->input->cur == '\n') && (ctxt->input->cur[-1] == '\r')) return(xmlDictLookup(ctxt->dict, ctxt->input->cur - (len + 1), len)); return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len)); }
171,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { const int shmkey = shmget(IPC_PRIVATE, size, 0666); if (shmkey == -1) { DLOG(ERROR) << "Failed to create SysV shared memory region" << " errno:" << errno; return NULL; } void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); shmctl(shmkey, IPC_RMID, 0); if (address == kInvalidAddress) return NULL; TransportDIB* dib = new TransportDIB; dib->key_.shmkey = shmkey; dib->address_ = address; dib->size_ = size; return dib; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { const int shmkey = shmget(IPC_PRIVATE, size, 0600); if (shmkey == -1) { DLOG(ERROR) << "Failed to create SysV shared memory region" << " errno:" << errno; return NULL; } else { VLOG(1) << "Created SysV shared memory region " << shmkey; } void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); shmctl(shmkey, IPC_RMID, 0); if (address == kInvalidAddress) return NULL; TransportDIB* dib = new TransportDIB; dib->key_.shmkey = shmkey; dib->address_ = address; dib->size_ = size; return dib; }
171,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DecrementUntilZero(int* count) { (*count)--; if (!(*count)) base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
static void DecrementUntilZero(int* count) { { base::RunLoop run_loop; cloud_print_proxy->GetCloudPrintProxyInfo( base::BindOnce([](base::OnceClosure done, bool, const std::string&, const std::string&) { std::move(done).Run(); }, run_loop.QuitClosure())); run_loop.Run(); } }
172,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, count) { PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(zend_hash_num_elements(&phar_obj->arc.archive->manifest)); }
165,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pid_ns_release_proc(struct pid_namespace *ns) { mntput(ns->proc_mnt); } Commit Message: procfs: fix a vfsmount longterm reference leak kern_mount() doesn't pair with plain mntput()... Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-119
void pid_ns_release_proc(struct pid_namespace *ns) { kern_unmount(ns->proc_mnt); }
165,614
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserSelectionScreen::UpdateAndReturnUserListForWebUI() { std::unique_ptr<base::ListValue> users_list = std::make_unique<base::ListValue>(); const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (user_manager::UserList::const_iterator it = users_to_send_.begin(); it != users_to_send_.end(); ++it) { const AccountId& account_id = (*it)->GetAccountId(); bool is_owner = (account_id == owner); const bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(*it) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; auto user_dict = std::make_unique<base::DictionaryValue>(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserDictionary(*it, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, user_dict.get()); user_dict->SetBoolean(kKeyCanRemove, CanRemoveUser(*it)); users_list->Append(std::move(user_dict)); } return users_list; } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
UserSelectionScreen::UpdateAndReturnUserListForWebUI() { std::unique_ptr<base::ListValue> users_list = std::make_unique<base::ListValue>(); const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (const user_manager::User* user : users_to_send_) { const AccountId& account_id = user->GetAccountId(); bool is_owner = (account_id == owner); const bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(user) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; auto user_dict = std::make_unique<base::DictionaryValue>(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserDictionary(user, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, user_dict.get()); user_dict->SetBoolean(kKeyCanRemove, CanRemoveUser(user)); users_list->Append(std::move(user_dict)); } return users_list; }
172,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: long long Block::GetTimeCode(const Cluster* pCluster) const { if (pCluster == 0) return m_timecode; const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; //unscaled timecode units } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Block::GetTimeCode(const Cluster* pCluster) const const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; // unscaled timecode units }
174,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length ) { static const size_t kMinPSIRSize = 12; // 4+2+1+1+4 this->DeleteExistingInfo(); this->fileParsed = true; if ( length == 0 ) return; XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets. XMP_Int64 fileEnd = psirOrigin + length; char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad. while ( fileRef->Offset() < fileEnd ) { if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource. XMP_Int64 thisRsrcPos = fileRef->Offset(); XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef ); XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef ); XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string. XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2! if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource. nameBuffer[0] = nameLen; fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen. XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef ); XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total. if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource. XMP_Int64 thisDataPos = fileRef->Offset(); continue; } InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased ); InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id ); if ( rsrcPos == this->imgRsrcs.end() ) { rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) ); } else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) { rsrcPos->second = newInfo; } else { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } InternalRsrcInfo* rsrcPtr = &rsrcPos->second; rsrcPtr->origOffset = (XMP_Uns32)thisDataPos; if ( nameLen > 0 ) { rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen ); if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above. } if ( ! IsMetadataImgRsrc ( id ) ) { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check. if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal ); } Commit Message: CWE ID: CWE-125
void PSIR_FileWriter::ParseFileResources ( XMP_IO* fileRef, XMP_Uns32 length ) { static const size_t kMinPSIRSize = 12; // 4+2+1+1+4 this->DeleteExistingInfo(); this->fileParsed = true; if ( length == 0 ) return; XMP_Int64 psirOrigin = fileRef->Offset(); // Need this to determine the resource data offsets. XMP_Int64 fileEnd = psirOrigin + length; char nameBuffer [260]; // The name is a PString, at 1+255+1 including length and pad. while ( fileRef->Offset() < fileEnd ) { if ( ! XIO::CheckFileSpace ( fileRef, kMinPSIRSize ) ) break; // Bad image resource. XMP_Int64 thisRsrcPos = fileRef->Offset(); XMP_Uns32 type = XIO::ReadUns32_BE ( fileRef ); XMP_Uns16 id = XIO::ReadUns16_BE ( fileRef ); XMP_Uns8 nameLen = XIO::ReadUns8 ( fileRef ); // ! The length for the Pascal string. XMP_Uns16 paddedLen = (nameLen + 2) & 0xFFFE; // ! Round up to an even total. Yes, +2! if ( ! XIO::CheckFileSpace ( fileRef, paddedLen+4 ) ) break; // Bad image resource. nameBuffer[0] = nameLen; fileRef->ReadAll ( &nameBuffer[1], paddedLen-1 ); // Include the pad byte, present for zero nameLen. XMP_Uns32 dataLen = XIO::ReadUns32_BE ( fileRef ); XMP_Uns32 dataTotal = ((dataLen + 1) & 0xFFFFFFFEUL); // Round up to an even total. // See bug https://bugs.freedesktop.org/show_bug.cgi?id=105204 // If dataLen is 0xffffffff, then dataTotal might be 0 // and therefor make the CheckFileSpace test pass. if (dataTotal < dataLen) { break; } if ( ! XIO::CheckFileSpace ( fileRef, dataTotal ) ) break; // Bad image resource. XMP_Int64 thisDataPos = fileRef->Offset(); continue; } InternalRsrcInfo newInfo ( id, dataLen, kIsFileBased ); InternalRsrcMap::iterator rsrcPos = this->imgRsrcs.find ( id ); if ( rsrcPos == this->imgRsrcs.end() ) { rsrcPos = this->imgRsrcs.insert ( rsrcPos, InternalRsrcMap::value_type ( id, newInfo ) ); } else if ( (rsrcPos->second.dataLen == 0) && (newInfo.dataLen != 0) ) { rsrcPos->second = newInfo; } else { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } InternalRsrcInfo* rsrcPtr = &rsrcPos->second; rsrcPtr->origOffset = (XMP_Uns32)thisDataPos; if ( nameLen > 0 ) { rsrcPtr->rsrcName = (XMP_Uns8*) malloc ( paddedLen ); if ( rsrcPtr->rsrcName == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); memcpy ( (void*)rsrcPtr->rsrcName, nameBuffer, paddedLen ); // AUDIT: Safe, allocated enough bytes above. } if ( ! IsMetadataImgRsrc ( id ) ) { fileRef->Seek ( nextRsrcPos, kXMP_SeekFromStart ); continue; } rsrcPtr->dataPtr = malloc ( dataTotal ); // ! Allocate after the IsMetadataImgRsrc check. if ( rsrcPtr->dataPtr == 0 ) XMP_Throw ( "Out of memory", kXMPErr_NoMemory ); fileRef->ReadAll ( (void*)rsrcPtr->dataPtr, dataTotal ); }
164,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ','; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; } Commit Message: CWE ID: CWE-119
parse_instruction( struct translate_ctx *ctx, boolean has_label ) { uint i; uint saturate = 0; const struct tgsi_opcode_info *info; struct tgsi_full_instruction inst; const char *cur; uint advance; inst = tgsi_default_full_instruction(); /* Parse predicate. */ eat_opt_white( &ctx->cur ); if (*ctx->cur == '(') { uint file; int index; uint swizzle[4]; boolean parsed_swizzle; inst.Instruction.Predicate = 1; ctx->cur++; if (*ctx->cur == '!') { ctx->cur++; inst.Predicate.Negate = 1; } if (!parse_register_1d( ctx, &file, &index )) return FALSE; if (parse_optional_swizzle( ctx, swizzle, &parsed_swizzle, 4 )) { if (parsed_swizzle) { inst.Predicate.SwizzleX = swizzle[0]; inst.Predicate.SwizzleY = swizzle[1]; inst.Predicate.SwizzleZ = swizzle[2]; inst.Predicate.SwizzleW = swizzle[3]; } } if (*ctx->cur != ')') { report_error( ctx, "Expected `)'" ); return FALSE; } ctx->cur++; } /* Parse instruction name. */ eat_opt_white( &ctx->cur ); for (i = 0; i < TGSI_OPCODE_LAST; i++) { cur = ctx->cur; info = tgsi_get_opcode_info( i ); if (match_inst(&cur, &saturate, info)) { if (info->num_dst + info->num_src + info->is_tex == 0) { ctx->cur = cur; break; } else if (*cur == '\0' || eat_white( &cur )) { ctx->cur = cur; break; } } } if (i == TGSI_OPCODE_LAST) { if (has_label) report_error( ctx, "Unknown opcode" ); else report_error( ctx, "Expected `DCL', `IMM' or a label" ); return FALSE; } inst.Instruction.Opcode = i; inst.Instruction.Saturate = saturate; inst.Instruction.NumDstRegs = info->num_dst; inst.Instruction.NumSrcRegs = info->num_src; if (i >= TGSI_OPCODE_SAMPLE && i <= TGSI_OPCODE_GATHER4) { /* * These are not considered tex opcodes here (no additional * target argument) however we're required to set the Texture * bit so we can set the number of tex offsets. */ inst.Instruction.Texture = 1; inst.Texture.Texture = TGSI_TEXTURE_UNKNOWN; } /* Parse instruction operands. */ for (i = 0; i < info->num_dst + info->num_src + info->is_tex; i++) { if (i > 0) { eat_opt_white( &ctx->cur ); if (*ctx->cur != ',') { report_error( ctx, "Expected `,'" ); return FALSE; } ctx->cur++; eat_opt_white( &ctx->cur ); } if (i < info->num_dst) { if (!parse_dst_operand( ctx, &inst.Dst[i] )) return FALSE; } else if (i < info->num_dst + info->num_src) { if (!parse_src_operand( ctx, &inst.Src[i - info->num_dst] )) return FALSE; } else { uint j; for (j = 0; j < TGSI_TEXTURE_COUNT; j++) { if (str_match_nocase_whole( &ctx->cur, tgsi_texture_names[j] )) { inst.Instruction.Texture = 1; inst.Texture.Texture = j; break; } } if (j == TGSI_TEXTURE_COUNT) { report_error( ctx, "Expected texture target" ); return FALSE; } } } cur = ctx->cur; eat_opt_white( &cur ); for (i = 0; inst.Instruction.Texture && *cur == ',' && i < TGSI_FULL_MAX_TEX_OFFSETS; i++) { cur++; eat_opt_white( &cur ); ctx->cur = cur; if (!parse_texoffset_operand( ctx, &inst.TexOffsets[i] )) return FALSE; cur = ctx->cur; eat_opt_white( &cur ); } inst.Texture.NumOffsets = i; cur = ctx->cur; eat_opt_white( &cur ); if (info->is_branch && *cur == ':') { uint target; cur++; eat_opt_white( &cur ); if (!parse_uint( &cur, &target )) { report_error( ctx, "Expected a label" ); return FALSE; } inst.Instruction.Label = 1; inst.Label.Label = target; ctx->cur = cur; } advance = tgsi_build_full_instruction( &inst, ctx->tokens_cur, ctx->header, (uint) (ctx->tokens_end - ctx->tokens_cur) ); if (advance == 0) return FALSE; ctx->tokens_cur += advance; return TRUE; }
164,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheGroup::RemoveCache(AppCache* cache) { DCHECK(cache->associated_hosts().empty()); if (cache == newest_complete_cache_) { CancelUpdate(); AppCache* tmp_cache = newest_complete_cache_; newest_complete_cache_ = nullptr; tmp_cache->set_owning_group(nullptr); // may cause this group to be deleted } else { scoped_refptr<AppCacheGroup> protect(this); Caches::iterator it = std::find(old_caches_.begin(), old_caches_.end(), cache); if (it != old_caches_.end()) { AppCache* tmp_cache = *it; old_caches_.erase(it); tmp_cache->set_owning_group(nullptr); // may cause group to be released } if (!is_obsolete() && old_caches_.empty() && !newly_deletable_response_ids_.empty()) { storage_->DeleteResponses(manifest_url_, newly_deletable_response_ids_); newly_deletable_response_ids_.clear(); } } } Commit Message: Refcount AppCacheGroup correctly. Bug: 888926 Change-Id: Iab0d82d272e2f24a5e91180d64bc8e2aa8a8238d Reviewed-on: https://chromium-review.googlesource.com/1246827 Reviewed-by: Marijn Kruisselbrink <[email protected]> Reviewed-by: Joshua Bell <[email protected]> Commit-Queue: Chris Palmer <[email protected]> Cr-Commit-Position: refs/heads/master@{#594475} CWE ID: CWE-20
void AppCacheGroup::RemoveCache(AppCache* cache) { DCHECK(cache->associated_hosts().empty()); if (cache == newest_complete_cache_) { AppCache* tmp_cache = newest_complete_cache_; newest_complete_cache_ = nullptr; CancelUpdate(); tmp_cache->set_owning_group(nullptr); // may cause this group to be deleted } else { scoped_refptr<AppCacheGroup> protect(this); Caches::iterator it = std::find(old_caches_.begin(), old_caches_.end(), cache); if (it != old_caches_.end()) { AppCache* tmp_cache = *it; old_caches_.erase(it); tmp_cache->set_owning_group(nullptr); // may cause group to be released } if (!is_obsolete() && old_caches_.empty() && !newly_deletable_response_ids_.empty()) { storage_->DeleteResponses(manifest_url_, newly_deletable_response_ids_); newly_deletable_response_ids_.clear(); } } }
172,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: bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } const PPB_NaCl_Private* ppb_nacl = GetNaclInterface(); if (ppb_nacl->StartPpapiProxy(pp_instance())) { using_ipc_proxy_ = true; CHECK(init_done_cb.pp_completion_callback().func != NULL); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon, started ipc proxy.\n")); pp::Module::Get()->core()->CallOnMainThread(0, init_done_cb, PP_OK); } return true; } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool Plugin::LoadNaClModuleCommon(nacl::DescWrapper* wrapper, NaClSubprocess* subprocess, const Manifest* manifest, bool should_report_uma, ErrorInfo* error_info, pp::CompletionCallback init_done_cb, pp::CompletionCallback crash_cb) { ServiceRuntime* new_service_runtime = new ServiceRuntime(this, manifest, should_report_uma, init_done_cb, crash_cb); subprocess->set_service_runtime(new_service_runtime); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime=%p)\n", static_cast<void*>(new_service_runtime))); if (NULL == new_service_runtime) { error_info->SetReport(ERROR_SEL_LDR_INIT, "sel_ldr init failure " + subprocess->description()); return false; } bool service_runtime_started = new_service_runtime->Start(wrapper, error_info, manifest_base_url()); PLUGIN_PRINTF(("Plugin::LoadNaClModuleCommon (service_runtime_started=%d)\n", service_runtime_started)); if (!service_runtime_started) { return false; } return true; }
170,742
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { tTcpIpPacketParsingResult res = _res; ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); res.xxpStatus = ppresXxpIncomplete; res.TcpUdp = ppresIsUDP; res.XxpIpHeaderSize = udpDataStart; if (len >= udpDataStart) { UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); USHORT datagramLength = swap_short(pUdpHeader->udp_length); res.xxpStatus = ppresXxpKnown; DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength)); } return res; } Commit Message: NetKVM: BZ#1169718: More rigoruous testing of incoming packet Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
ProcessUDPHeader(tTcpIpPacketParsingResult _res, PVOID pIpHeader, ULONG len, USHORT ipHeaderSize) { tTcpIpPacketParsingResult res = _res; ULONG udpDataStart = ipHeaderSize + sizeof(UDPHeader); res.TcpUdp = ppresIsUDP; res.XxpIpHeaderSize = udpDataStart; if (len >= udpDataStart) { UDPHeader *pUdpHeader = (UDPHeader *)RtlOffsetToPointer(pIpHeader, ipHeaderSize); USHORT datagramLength = swap_short(pUdpHeader->udp_length); res.xxpStatus = ppresXxpKnown; res.xxpFull = TRUE; DPrintf(2, ("udp: len %d, datagramLength %d\n", len, datagramLength)); } else { res.xxpFull = FALSE; res.xxpStatus = ppresXxpIncomplete; } return res; }
168,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WallpaperManager::SetDefaultWallpaperPath( const base::FilePath& default_small_wallpaper_file, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, const base::FilePath& default_large_wallpaper_file, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) { default_small_wallpaper_file_ = default_small_wallpaper_file; default_large_wallpaper_file_ = default_large_wallpaper_file; ash::WallpaperController* controller = ash::Shell::Get()->wallpaper_controller(); const bool need_update_screen = default_wallpaper_image_.get() && controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(), false /* compare_layouts */, wallpaper::WALLPAPER_LAYOUT_CENTER); default_wallpaper_image_.reset(); if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) { if (small_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*small_wallpaper_image)); default_wallpaper_image_->set_file_path(default_small_wallpaper_file); } } else { if (large_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*large_wallpaper_image)); default_wallpaper_image_->set_file_path(default_large_wallpaper_file); } } if (need_update_screen) DoSetDefaultWallpaper(EmptyAccountId(), MovableOnDestroyCallbackHolder()); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200
void WallpaperManager::SetDefaultWallpaperPath( const base::FilePath& default_small_wallpaper_file, std::unique_ptr<gfx::ImageSkia> small_wallpaper_image, const base::FilePath& default_large_wallpaper_file, std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) { default_small_wallpaper_file_ = default_small_wallpaper_file; default_large_wallpaper_file_ = default_large_wallpaper_file; ash::WallpaperController* controller = ash::Shell::Get()->wallpaper_controller(); const bool need_update_screen = default_wallpaper_image_.get() && controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(), false /* compare_layouts */, wallpaper::WALLPAPER_LAYOUT_CENTER); default_wallpaper_image_.reset(); if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) { if (small_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*small_wallpaper_image)); default_wallpaper_image_->set_file_path(default_small_wallpaper_file); } } else { if (large_wallpaper_image) { default_wallpaper_image_.reset( new user_manager::UserImage(*large_wallpaper_image)); default_wallpaper_image_->set_file_path(default_large_wallpaper_file); } } DoSetDefaultWallpaper(EmptyAccountId(), need_update_screen, MovableOnDestroyCallbackHolder()); }
171,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; } Commit Message: quote imap strings more carefully Co-authored-by: JerikoOne <[email protected]> CWE ID: CWE-77
enum ImapAuthRes imap_auth_login(struct ImapData *idata, const char *method) { char q_user[SHORT_STRING], q_pass[SHORT_STRING]; char buf[STRING]; int rc; if (mutt_bit_isset(idata->capabilities, LOGINDISABLED)) { mutt_message(_("LOGIN disabled on this server.")); return IMAP_AUTH_UNAVAIL; } if (mutt_account_getuser(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; mutt_message(_("Logging in...")); imap_quote_string(q_user, sizeof(q_user), idata->conn->account.user, false); imap_quote_string(q_pass, sizeof(q_pass), idata->conn->account.pass, false); /* don't print the password unless we're at the ungodly debugging level * of 5 or higher */ if (DebugLevel < IMAP_LOG_PASS) mutt_debug(2, "Sending LOGIN command for %s...\n", idata->conn->account.user); snprintf(buf, sizeof(buf), "LOGIN %s %s", q_user, q_pass); rc = imap_exec(idata, buf, IMAP_CMD_FAIL_OK | IMAP_CMD_PASS); if (!rc) { mutt_clear_error(); /* clear "Logging in...". fixes #3524 */ return IMAP_AUTH_SUCCESS; } mutt_error(_("Login failed.")); return IMAP_AUTH_FAILURE; }
169,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BinaryUploadService::IsAuthorized(AuthorizationCallback callback) { if (!timer_.IsRunning()) { timer_.Start(FROM_HERE, base::TimeDelta::FromHours(24), this, &BinaryUploadService::ResetAuthorizationData); } if (!can_upload_data_.has_value()) { if (!pending_validate_data_upload_request_) { std::string dm_token = GetDMToken(); if (dm_token.empty()) { std::move(callback).Run(false); return; } pending_validate_data_upload_request_ = true; auto request = std::make_unique<ValidateDataUploadRequest>(base::BindOnce( &BinaryUploadService::ValidateDataUploadRequestCallback, weakptr_factory_.GetWeakPtr())); request->set_dm_token(dm_token); UploadForDeepScanning(std::move(request)); } authorization_callbacks_.push_back(std::move(callback)); return; } std::move(callback).Run(can_upload_data_.value()); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <[email protected]> Reviewed-by: Tien Mai <[email protected]> Reviewed-by: Daniel Rubery <[email protected]> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
void BinaryUploadService::IsAuthorized(AuthorizationCallback callback) { if (!timer_.IsRunning()) { timer_.Start(FROM_HERE, base::TimeDelta::FromHours(24), this, &BinaryUploadService::ResetAuthorizationData); } if (!can_upload_data_.has_value()) { if (!pending_validate_data_upload_request_) { auto dm_token = GetDMToken(); if (!dm_token.is_valid()) { std::move(callback).Run(false); return; } pending_validate_data_upload_request_ = true; auto request = std::make_unique<ValidateDataUploadRequest>(base::BindOnce( &BinaryUploadService::ValidateDataUploadRequestCallback, weakptr_factory_.GetWeakPtr())); request->set_dm_token(dm_token.value()); UploadForDeepScanning(std::move(request)); } authorization_callbacks_.push_back(std::move(callback)); return; } std::move(callback).Run(can_upload_data_.value()); }
172,355
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pch_write_line (lin line, FILE *file) { bool after_newline = p_line[line][p_len[line] - 1] == '\n'; if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file)) write_fatal (); return after_newline; } Commit Message: CWE ID: CWE-119
pch_write_line (lin line, FILE *file) { bool after_newline = (p_len[line] > 0) && (p_line[line][p_len[line] - 1] == '\n'); if (! fwrite (p_line[line], sizeof (*p_line[line]), p_len[line], file)) write_fatal (); return after_newline; }
165,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t nfs4_proc_get_acl(struct inode *inode, void *buf, size_t buflen) { struct nfs_server *server = NFS_SERVER(inode); int ret; if (!nfs4_server_supports_acls(server)) return -EOPNOTSUPP; ret = nfs_revalidate_inode(server, inode); if (ret < 0) return ret; if (NFS_I(inode)->cache_validity & NFS_INO_INVALID_ACL) nfs_zap_acl_cache(inode); ret = nfs4_read_cached_acl(inode, buf, buflen); if (ret != -ENOENT) return ret; return nfs4_get_acl_uncached(inode, buf, buflen); } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189
static ssize_t nfs4_proc_get_acl(struct inode *inode, void *buf, size_t buflen) { struct nfs_server *server = NFS_SERVER(inode); int ret; if (!nfs4_server_supports_acls(server)) return -EOPNOTSUPP; ret = nfs_revalidate_inode(server, inode); if (ret < 0) return ret; if (NFS_I(inode)->cache_validity & NFS_INO_INVALID_ACL) nfs_zap_acl_cache(inode); ret = nfs4_read_cached_acl(inode, buf, buflen); if (ret != -ENOENT) /* -ENOENT is returned if there is no ACL or if there is an ACL * but no cached acl data, just the acl length */ return ret; return nfs4_get_acl_uncached(inode, buf, buflen); }
165,718
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 unix_inflight(struct file *fp) { struct sock *s = unix_get_socket(fp); spin_lock(&unix_gc_lock); if (s) { struct unix_sock *u = unix_sk(s); if (atomic_long_inc_return(&u->inflight) == 1) { BUG_ON(!list_empty(&u->link)); list_add_tail(&u->link, &gc_inflight_list); } else { BUG_ON(list_empty(&u->link)); } unix_tot_inflight++; } fp->f_cred->user->unix_inflight++; spin_unlock(&unix_gc_lock); } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
void unix_inflight(struct file *fp) void unix_inflight(struct user_struct *user, struct file *fp) { struct sock *s = unix_get_socket(fp); spin_lock(&unix_gc_lock); if (s) { struct unix_sock *u = unix_sk(s); if (atomic_long_inc_return(&u->inflight) == 1) { BUG_ON(!list_empty(&u->link)); list_add_tail(&u->link, &gc_inflight_list); } else { BUG_ON(list_empty(&u->link)); } unix_tot_inflight++; } user->unix_inflight++; spin_unlock(&unix_gc_lock); }
167,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hashtable_do_del(hashtable_t *hashtable, const char *key, size_t hash) { pair_t *pair; bucket_t *bucket; size_t index; index = hash % num_buckets(hashtable); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return -1; if(&pair->list == bucket->first && &pair->list == bucket->last) bucket->first = bucket->last = &hashtable->list; else if(&pair->list == bucket->first) bucket->first = pair->list.next; else if(&pair->list == bucket->last) bucket->last = pair->list.prev; list_remove(&pair->list); json_decref(pair->value); jsonp_free(pair); hashtable->size--; return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
static int hashtable_do_del(hashtable_t *hashtable, const char *key, size_t hash) { pair_t *pair; bucket_t *bucket; size_t index; index = hash & hashmask(hashtable->order); bucket = &hashtable->buckets[index]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return -1; if(&pair->list == bucket->first && &pair->list == bucket->last) bucket->first = bucket->last = &hashtable->list; else if(&pair->list == bucket->first) bucket->first = pair->list.next; else if(&pair->list == bucket->last) bucket->last = pair->list.prev; list_remove(&pair->list); json_decref(pair->value); jsonp_free(pair); hashtable->size--; return 0; }
166,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_acomp racomp; strlcpy(racomp.type, "acomp", sizeof(racomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP, sizeof(struct crypto_report_acomp), &racomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } Commit Message: crypto: user - fix leaking uninitialized memory to userspace All bytes of the NETLINK_CRYPTO report structures must be initialized, since they are copied to userspace. The change from strncpy() to strlcpy() broke this. As a minimal fix, change it back. Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion") Cc: <[email protected]> # v4.12+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID:
static int crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_acomp racomp; strncpy(racomp.type, "acomp", sizeof(racomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP, sizeof(struct crypto_report_acomp), &racomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; }
168,963
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GestureProviderAura::OnTouchEvent(const TouchEvent& event) { last_touch_event_flags_ = event.flags(); bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; } Commit Message: Pass ui::LatencyInfo correct with unified gesture detector on Aura. BUG=379812 TEST=GestureRecognizerTest.LatencyPassedFromTouchEvent Review URL: https://codereview.chromium.org/309823002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@274602 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool GestureProviderAura::OnTouchEvent(const TouchEvent& event) { bool pointer_id_is_active = false; for (size_t i = 0; i < pointer_state_.GetPointerCount(); ++i) { if (event.touch_id() != pointer_state_.GetPointerId(i)) continue; pointer_id_is_active = true; break; } if (event.type() == ET_TOUCH_PRESSED && pointer_id_is_active) { return false; } else if (event.type() != ET_TOUCH_PRESSED && !pointer_id_is_active) { return false; } last_touch_event_flags_ = event.flags(); last_touch_event_latency_info_ = *event.latency(); pointer_state_.OnTouch(event); bool result = filtered_gesture_provider_.OnTouchEvent(pointer_state_); pointer_state_.CleanupRemovedTouchPoints(event); return result; }
171,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: bool Cues::DoneParsing() const { const long long stop = m_start + m_size; return (m_pos >= stop); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool Cues::DoneParsing() const
174,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, SplashClipResult clipRes) { SplashPipe pipe; Guchar *p; int w, h, x, y; w = src->getWidth(); h = src->getHeight(); if (vectorAntialias && clipRes != splashClipAllInside) { pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); drawAAPixelInit(); p = src->getDataPtr(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { pipe.shape = *p++; pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); p = src->getDataPtr(); } else { pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); p = src->getDataPtr(); if (clipRes == splashClipAllInside) { for (y = 0; y < h; ++y) { pipeSetXY(&pipe, xDest, yDest + y); (this->*pipe.run)(&pipe); } else { pipeIncX(&pipe); } ++p; } } updateModX(xDest); updateModX(xDest + w - 1); updateModY(yDest); updateModY(yDest + h - 1); } else { for (y = 0; y < h; ++y) { pipeSetXY(&pipe, xDest, yDest + y); for (x = 0; x < w; ++x) { if (*p && state->clip->test(xDest + x, yDest + y)) { pipe.shape = *p; (this->*pipe.run)(&pipe); updateModX(xDest + x); updateModY(yDest + y); } else { pipeIncX(&pipe); } ++p; } } } } } Commit Message: CWE ID:
void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, SplashClipResult clipRes) { SplashPipe pipe; Guchar *p; int w, h, x, y; w = src->getWidth(); h = src->getHeight(); p = src->getDataPtr(); if (p == NULL) { error(errInternal, -1, "src->getDataPtr() is NULL in Splash::blitMask"); return; } if (vectorAntialias && clipRes != splashClipAllInside) { pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); drawAAPixelInit(); for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { pipe.shape = *p++; pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); p = src->getDataPtr(); } else { pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); if (clipRes == splashClipAllInside) { for (y = 0; y < h; ++y) { pipeSetXY(&pipe, xDest, yDest + y); (this->*pipe.run)(&pipe); } else { pipeIncX(&pipe); } ++p; } } updateModX(xDest); updateModX(xDest + w - 1); updateModY(yDest); updateModY(yDest + h - 1); } else { for (y = 0; y < h; ++y) { pipeSetXY(&pipe, xDest, yDest + y); for (x = 0; x < w; ++x) { if (*p && state->clip->test(xDest + x, yDest + y)) { pipe.shape = *p; (this->*pipe.run)(&pipe); updateModX(xDest + x); updateModY(yDest + y); } else { pipeIncX(&pipe); } ++p; } } } } }
164,732
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, 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(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to encode frame."); while ((pkt = vpx_codec_get_cx_data(ctx, &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(ctx, "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 *ctx, static int encode_frame(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, 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(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to encode frame."); while ((pkt = vpx_codec_get_cx_data(ctx, &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(ctx, "Failed to write compressed frame."); printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; } static vpx_fixed_buf_t pass0(vpx_image_t *raw, FILE *infile, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { vpx_codec_ctx_t codec; int frame_count = 0; vpx_fixed_buf_t stats = {NULL, 0}; if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Calculate frame statistics. while (vpx_img_read(raw, infile)) { ++frame_count; get_frame_stats(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats); } // Flush encoder. while (get_frame_stats(&codec, NULL, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, &stats)) {} printf("Pass 0 complete. Processed %d frames.\n", frame_count); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); return stats; } static void pass1(vpx_image_t *raw, FILE *infile, const char *outfile_name, const VpxInterface *encoder, const vpx_codec_enc_cfg_t *cfg) { VpxVideoInfo info = { encoder->fourcc, cfg->g_w, cfg->g_h, {cfg->g_timebase.num, cfg->g_timebase.den} }; VpxVideoWriter *writer = NULL; vpx_codec_ctx_t codec; int frame_count = 0; writer = vpx_video_writer_open(outfile_name, kContainerIVF, &info); if (!writer) die("Failed to open %s for writing", outfile_name); if (vpx_codec_enc_init(&codec, encoder->codec_interface(), cfg, 0)) die_codec(&codec, "Failed to initialize encoder"); // Encode frames. while (vpx_img_read(raw, infile)) { ++frame_count; encode_frame(&codec, raw, frame_count, 1, 0, VPX_DL_GOOD_QUALITY, writer); } // Flush encoder. while (encode_frame(&codec, NULL, -1, 1, 0, VPX_DL_GOOD_QUALITY, writer)) {} printf("\n"); if (vpx_codec_destroy(&codec)) die_codec(&codec, "Failed to destroy codec."); vpx_video_writer_close(writer); printf("Pass 1 complete. Processed %d frames.\n", frame_count); }
174,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SSH_PACKET_CALLBACK(ssh_packet_kexdh_init){ int rc; (void)type; (void)user; SSH_LOG(SSH_LOG_PACKET,"Received SSH_MSG_KEXDH_INIT"); if(session->dh_handshake_state != DH_STATE_INIT){ SSH_LOG(SSH_LOG_RARE,"Invalid state for SSH_MSG_KEXDH_INIT"); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_server_kexdh_init(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_server_ecdh_init(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_server_curve25519_init(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_kexdh_init"); rc = SSH_ERROR; } if (rc == SSH_ERROR) session->session_state = SSH_SESSION_STATE_ERROR; error: return SSH_PACKET_USED; } Commit Message: CWE ID:
SSH_PACKET_CALLBACK(ssh_packet_kexdh_init){ int rc = SSH_ERROR; (void)type; (void)user; SSH_LOG(SSH_LOG_PACKET,"Received SSH_MSG_KEXDH_INIT"); if(session->dh_handshake_state != DH_STATE_INIT){ SSH_LOG(SSH_LOG_RARE,"Invalid state for SSH_MSG_KEXDH_INIT"); goto error; } switch(session->next_crypto->kex_type){ case SSH_KEX_DH_GROUP1_SHA1: case SSH_KEX_DH_GROUP14_SHA1: rc=ssh_server_kexdh_init(session, packet); break; #ifdef HAVE_ECDH case SSH_KEX_ECDH_SHA2_NISTP256: rc = ssh_server_ecdh_init(session, packet); break; #endif #ifdef HAVE_CURVE25519 case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG: rc = ssh_server_curve25519_init(session, packet); break; #endif default: ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_kexdh_init"); rc = SSH_ERROR; } error: if (rc == SSH_ERROR) { session->session_state = SSH_SESSION_STATE_ERROR; } return SSH_PACKET_USED; }
165,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssd0323_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssd0323_state *s = (ssd0323_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->cmd_len = qemu_get_be32(f); s->cmd = qemu_get_be32(f); for (i = 0; i < 8; i++) s->cmd_data[i] = qemu_get_be32(f); s->row = qemu_get_be32(f); s->row_start = qemu_get_be32(f); s->row_end = qemu_get_be32(f); s->col = qemu_get_be32(f); s->col_start = qemu_get_be32(f); s->col_end = qemu_get_be32(f); s->redraw = qemu_get_be32(f); s->remap = qemu_get_be32(f); s->mode = qemu_get_be32(f); qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer)); ss->cs = qemu_get_be32(f); } Commit Message: CWE ID: CWE-119
static int ssd0323_load(QEMUFile *f, void *opaque, int version_id) { SSISlave *ss = SSI_SLAVE(opaque); ssd0323_state *s = (ssd0323_state *)opaque; int i; if (version_id != 1) return -EINVAL; s->cmd_len = qemu_get_be32(f); if (s->cmd_len < 0 || s->cmd_len > ARRAY_SIZE(s->cmd_data)) { return -EINVAL; } s->cmd = qemu_get_be32(f); for (i = 0; i < 8; i++) s->cmd_data[i] = qemu_get_be32(f); s->row = qemu_get_be32(f); if (s->row < 0 || s->row >= 80) { return -EINVAL; } s->row_start = qemu_get_be32(f); if (s->row_start < 0 || s->row_start >= 80) { return -EINVAL; } s->row_end = qemu_get_be32(f); if (s->row_end < 0 || s->row_end >= 80) { return -EINVAL; } s->col = qemu_get_be32(f); if (s->col < 0 || s->col >= 64) { return -EINVAL; } s->col_start = qemu_get_be32(f); if (s->col_start < 0 || s->col_start >= 64) { return -EINVAL; } s->col_end = qemu_get_be32(f); if (s->col_end < 0 || s->col_end >= 64) { return -EINVAL; } s->redraw = qemu_get_be32(f); s->remap = qemu_get_be32(f); s->mode = qemu_get_be32(f); if (s->mode != SSD0323_CMD && s->mode != SSD0323_DATA) { return -EINVAL; } qemu_get_buffer(f, s->framebuffer, sizeof(s->framebuffer)); ss->cs = qemu_get_be32(f); }
165,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
void libxsmm_sparse_csc_reader( libxsmm_generated_code* io_generated_code, const char* i_csc_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csc_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_column_idx_id = NULL; unsigned int l_i = 0; l_csc_file_handle = fopen( i_csc_file_in, "r" ); if ( l_csc_file_handle == NULL ) { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_INPUT ); return; } while (fgets(l_line, l_line_length, l_csc_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose( l_csc_file_handle ); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_LEN ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC data structure matching mtx file */ *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_column_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_column_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_column_idx_id == NULL ) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_ALLOC_DATA ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int) * (*o_element_count)); memset(*o_column_idx, 0, sizeof(unsigned int) * ((size_t)(*o_column_count) + 1)); memset(*o_values, 0, sizeof(double) * (*o_element_count)); memset(l_column_idx_id, 0, sizeof(unsigned int) * (*o_column_count)); /* init column idx */ for (l_i = 0; l_i <= *o_column_count; ++l_i) { (*o_column_idx)[l_i] = *o_element_count; } /* init */ (*o_column_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_DESC ); fclose( l_csc_file_handle ); /* close mtx file */ return; } /* now we read the actual content */ } else { unsigned int l_row = 0, l_column = 0; double l_value = 0; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; fclose(l_csc_file_handle); /* close mtx file */ LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_READ_ELEMS ); return; } /* adjust numbers to zero termination */ LIBXSMM_ASSERT(0 != l_row && 0 != l_column); l_row--; l_column--; /* add these values to row and value structure */ (*o_row_idx)[l_i] = l_row; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_column_idx_id[l_column] = 1; (*o_column_idx)[l_column+1] = l_i; } } } /* close mtx file */ fclose( l_csc_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { free(*o_row_idx); free(*o_column_idx); free(*o_values); free(l_column_idx_id); *o_row_idx = 0; *o_column_idx = 0; *o_values = 0; LIBXSMM_HANDLE_ERROR( io_generated_code, LIBXSMM_ERR_CSC_LEN ); return; } if ( l_column_idx_id != NULL ) { /* let's handle empty columns */ for ( l_i = 0; l_i < (*o_column_count); l_i++) { if ( l_column_idx_id[l_i] == 0 ) { (*o_column_idx)[l_i+1] = (*o_column_idx)[l_i]; } } /* free helper data structure */ free( l_column_idx_id ); } }
168,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Track::Info::Clear() { delete[] nameAsUTF8; nameAsUTF8 = NULL; delete[] language; language = NULL; delete[] codecId; codecId = NULL; delete[] codecPrivate; codecPrivate = NULL; codecPrivateSize = 0; delete[] codecNameAsUTF8; codecNameAsUTF8 = 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
void Track::Info::Clear() if (dst) // should be NULL already return -1; const char* const src = this->*str;
174,247
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsMLU* mlu; cmsUInt32Number Count, RecLen, NumOfWchar; cmsUInt32Number SizeOfHeader; cmsUInt32Number Len, Offset; cmsUInt32Number i; wchar_t* Block; cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (!_cmsReadUInt32Number(io, &RecLen)) return NULL; if (RecLen != 12) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported."); return NULL; } mlu = cmsMLUalloc(self ->ContextID, Count); if (mlu == NULL) return NULL; mlu ->UsedEntries = Count; SizeOfHeader = 12 * Count + sizeof(_cmsTagBase); LargestPosition = 0; for (i=0; i < Count; i++) { if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error; if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error; if (!_cmsReadUInt32Number(io, &Len)) goto Error; if (!_cmsReadUInt32Number(io, &Offset)) goto Error; if (Offset < (SizeOfHeader + 8)) goto Error; BeginOfThisString = Offset - SizeOfHeader - 8; mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number); mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number); EndOfThisString = BeginOfThisString + Len; if (EndOfThisString > LargestPosition) LargestPosition = EndOfThisString; } SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number); if (SizeOfTag == 0) { Block = NULL; NumOfWchar = 0; } else { Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag); if (Block == NULL) goto Error; NumOfWchar = SizeOfTag / sizeof(wchar_t); if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error; } mlu ->MemPool = Block; mlu ->PoolSize = SizeOfTag; mlu ->PoolUsed = SizeOfTag; *nItems = 1; return (void*) mlu; Error: if (mlu) cmsMLUfree(mlu); return NULL; } Commit Message: Added an extra check to MLU bounds Thanks to Ibrahim el-sayed for spotting the bug CWE ID: CWE-125
void *Type_MLU_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsUInt32Number* nItems, cmsUInt32Number SizeOfTag) { cmsMLU* mlu; cmsUInt32Number Count, RecLen, NumOfWchar; cmsUInt32Number SizeOfHeader; cmsUInt32Number Len, Offset; cmsUInt32Number i; wchar_t* Block; cmsUInt32Number BeginOfThisString, EndOfThisString, LargestPosition; *nItems = 0; if (!_cmsReadUInt32Number(io, &Count)) return NULL; if (!_cmsReadUInt32Number(io, &RecLen)) return NULL; if (RecLen != 12) { cmsSignalError(self->ContextID, cmsERROR_UNKNOWN_EXTENSION, "multiLocalizedUnicodeType of len != 12 is not supported."); return NULL; } mlu = cmsMLUalloc(self ->ContextID, Count); if (mlu == NULL) return NULL; mlu ->UsedEntries = Count; SizeOfHeader = 12 * Count + sizeof(_cmsTagBase); LargestPosition = 0; for (i=0; i < Count; i++) { if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Language)) goto Error; if (!_cmsReadUInt16Number(io, &mlu ->Entries[i].Country)) goto Error; if (!_cmsReadUInt32Number(io, &Len)) goto Error; if (!_cmsReadUInt32Number(io, &Offset)) goto Error; if (Offset < (SizeOfHeader + 8)) goto Error; if ((Offset + Len) > SizeOfTag + 8) goto Error; BeginOfThisString = Offset - SizeOfHeader - 8; mlu ->Entries[i].Len = (Len * sizeof(wchar_t)) / sizeof(cmsUInt16Number); mlu ->Entries[i].StrW = (BeginOfThisString * sizeof(wchar_t)) / sizeof(cmsUInt16Number); EndOfThisString = BeginOfThisString + Len; if (EndOfThisString > LargestPosition) LargestPosition = EndOfThisString; } SizeOfTag = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number); if (SizeOfTag == 0) { Block = NULL; NumOfWchar = 0; } else { Block = (wchar_t*) _cmsMalloc(self ->ContextID, SizeOfTag); if (Block == NULL) goto Error; NumOfWchar = SizeOfTag / sizeof(wchar_t); if (!_cmsReadWCharArray(io, NumOfWchar, Block)) goto Error; } mlu ->MemPool = Block; mlu ->PoolSize = SizeOfTag; mlu ->PoolUsed = SizeOfTag; *nItems = 1; return (void*) mlu; Error: if (mlu) cmsMLUfree(mlu); return NULL; }
168,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_arch_vcpu_init(struct kvm_vcpu *vcpu) { struct page *page; struct kvm *kvm; int r; BUG_ON(vcpu->kvm == NULL); kvm = vcpu->kvm; vcpu->arch.emulate_ctxt.ops = &emulate_ops; if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu)) vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; else vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED; page = alloc_page(GFP_KERNEL | __GFP_ZERO); if (!page) { r = -ENOMEM; goto fail; } vcpu->arch.pio_data = page_address(page); kvm_set_tsc_khz(vcpu, max_tsc_khz); r = kvm_mmu_create(vcpu); if (r < 0) goto fail_free_pio_data; if (irqchip_in_kernel(kvm)) { r = kvm_create_lapic(vcpu); if (r < 0) goto fail_mmu_destroy; } else static_key_slow_inc(&kvm_no_apic_vcpu); vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4, GFP_KERNEL); if (!vcpu->arch.mce_banks) { r = -ENOMEM; goto fail_free_lapic; } vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS; if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) goto fail_free_mce_banks; r = fx_init(vcpu); if (r) goto fail_free_wbinvd_dirty_mask; vcpu->arch.ia32_tsc_adjust_msr = 0x0; kvm_async_pf_hash_reset(vcpu); kvm_pmu_init(vcpu); return 0; fail_free_wbinvd_dirty_mask: free_cpumask_var(vcpu->arch.wbinvd_dirty_mask); fail_free_mce_banks: kfree(vcpu->arch.mce_banks); fail_free_lapic: kvm_free_lapic(vcpu); fail_mmu_destroy: kvm_mmu_destroy(vcpu); fail_free_pio_data: free_page((unsigned long)vcpu->arch.pio_data); fail: return r; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu) { struct page *page; struct kvm *kvm; int r; BUG_ON(vcpu->kvm == NULL); kvm = vcpu->kvm; vcpu->arch.emulate_ctxt.ops = &emulate_ops; if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu)) vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; else vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED; page = alloc_page(GFP_KERNEL | __GFP_ZERO); if (!page) { r = -ENOMEM; goto fail; } vcpu->arch.pio_data = page_address(page); kvm_set_tsc_khz(vcpu, max_tsc_khz); r = kvm_mmu_create(vcpu); if (r < 0) goto fail_free_pio_data; if (irqchip_in_kernel(kvm)) { r = kvm_create_lapic(vcpu); if (r < 0) goto fail_mmu_destroy; } else static_key_slow_inc(&kvm_no_apic_vcpu); vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4, GFP_KERNEL); if (!vcpu->arch.mce_banks) { r = -ENOMEM; goto fail_free_lapic; } vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS; if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) goto fail_free_mce_banks; r = fx_init(vcpu); if (r) goto fail_free_wbinvd_dirty_mask; vcpu->arch.ia32_tsc_adjust_msr = 0x0; vcpu->arch.pv_time_enabled = false; kvm_async_pf_hash_reset(vcpu); kvm_pmu_init(vcpu); return 0; fail_free_wbinvd_dirty_mask: free_cpumask_var(vcpu->arch.wbinvd_dirty_mask); fail_free_mce_banks: kfree(vcpu->arch.mce_banks); fail_free_lapic: kvm_free_lapic(vcpu); fail_mmu_destroy: kvm_mmu_destroy(vcpu); fail_free_pio_data: free_page((unsigned long)vcpu->arch.pio_data); fail: return r; }
166,115
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; } Commit Message: CWE ID: CWE-200
static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) { PCIDevice *pci_dev = PCI_DEVICE(s); PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); struct mfi_ctrl_info info; size_t dcmd_size = sizeof(info); BusChild *kid; int num_pd_disks = 0; memset(&info, 0x0, dcmd_size); if (cmd->iov_size < dcmd_size) { trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, dcmd_size); return MFI_STAT_INVALID_PARAMETER; } info.pci.vendor = cpu_to_le16(pci_class->vendor_id); info.pci.device = cpu_to_le16(pci_class->device_id); info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); /* * For some reason the firmware supports * only up to 8 device ports. * Despite supporting a far larger number * of devices for the physical devices. * So just display the first 8 devices * in the device port list, independent * of how many logical devices are actually * present. */ info.host.type = MFI_INFO_HOST_PCIE; info.device.type = MFI_INFO_DEV_SAS3G; info.device.port_count = 8; QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { SCSIDevice *sdev = SCSI_DEVICE(kid->child); uint16_t pd_id; if (num_pd_disks < 8) { pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); info.device.port_addr[num_pd_disks] = cpu_to_le64(megasas_get_sata_addr(pd_id)); } num_pd_disks++; } memcpy(info.product_name, base_class->product_name, 24); snprintf(info.serial_number, 32, "%s", s->hba_serial); snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version()); memcpy(info.image_component[0].name, "APP", 3); snprintf(info.image_component[0].version, 10, "%s-QEMU", base_class->product_version); memcpy(info.image_component[0].build_date, "Apr 1 2014", 11); memcpy(info.image_component[0].build_time, "12:34:56", 8); info.image_component_count = 1; if (pci_dev->has_rom) { uint8_t biosver[32]; uint8_t *ptr; ptr = memory_region_get_ram_ptr(&pci_dev->rom); memcpy(biosver, ptr + 0x41, 31); biosver[31] = 0; memcpy(info.image_component[1].name, "BIOS", 4); memcpy(info.image_component[1].version, biosver, strlen((const char *)biosver)); } info.current_fw_time = cpu_to_le32(megasas_fw_time()); info.max_arms = 32; info.max_spans = 8; info.max_arrays = MEGASAS_MAX_ARRAYS; info.max_lds = MFI_MAX_LD; info.max_cmds = cpu_to_le16(s->fw_cmds); info.max_sg_elements = cpu_to_le16(s->fw_sge); info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); if (!megasas_is_jbod(s)) info.lds_present = cpu_to_le16(num_pd_disks); info.pd_present = cpu_to_le16(num_pd_disks); info.pd_disks_present = cpu_to_le16(num_pd_disks); info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | MFI_INFO_HW_MEM | MFI_INFO_HW_FLASH); info.memory_size = cpu_to_le16(512); info.nvram_size = cpu_to_le16(32); info.flash_size = cpu_to_le16(16); info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | MFI_INFO_AOPS_SELF_DIAGNOSTIC | MFI_INFO_AOPS_MIXED_ARRAY); info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | MFI_INFO_LDOPS_ACCESS_POLICY | MFI_INFO_LDOPS_IO_POLICY | MFI_INFO_LDOPS_WRITE_POLICY | MFI_INFO_LDOPS_READ_POLICY); info.max_strips_per_io = cpu_to_le16(s->fw_sge); info.stripe_sz_ops.min = 3; info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); info.properties.pred_fail_poll_interval = cpu_to_le16(300); info.properties.intr_throttle_cnt = cpu_to_le16(16); info.properties.intr_throttle_timeout = cpu_to_le16(50); info.properties.rebuild_rate = 30; info.properties.patrol_read_rate = 30; info.properties.bgi_rate = 30; info.properties.cc_rate = 30; info.properties.recon_rate = 30; info.properties.cache_flush_interval = 4; info.properties.spinup_drv_cnt = 2; info.properties.spinup_delay = 6; info.properties.ecc_bucket_size = 15; info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); info.properties.expose_encl_devices = 1; info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | MFI_INFO_PDOPS_FORCE_OFFLINE); info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | MFI_INFO_PDMIX_SATA | MFI_INFO_PDMIX_LD); cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); return MFI_STAT_OK; }
165,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: EBMLHeader::EBMLHeader() : m_docType(NULL) { Init(); } 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
EBMLHeader::EBMLHeader() :
174,269
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); } Commit Message: Fixed possible foveon buffer overrun (Secunia SA750000) CWE ID: CWE-119
void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[1024], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); #ifdef LIBRAW_LIBRARY_BUILD if(wide>32767 || high > 32767 || wide*high > 20000000) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); }
168,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void *host_from_stream_offset(QEMUFile *f, ram_addr_t offset, int flags) { static RAMBlock *block = NULL; char id[256]; uint8_t len; if (flags & RAM_SAVE_FLAG_CONTINUE) { if (!block) { error_report("Ack, bad migration stream!"); return NULL; } return memory_region_get_ram_ptr(block->mr) + offset; } len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; QTAILQ_FOREACH(block, &ram_list.blocks, next) { if (!strncmp(id, block->idstr, sizeof(id))) return memory_region_get_ram_ptr(block->mr) + offset; } error_report("Can't find block %s!", id); } Commit Message: CWE ID: CWE-20
static inline void *host_from_stream_offset(QEMUFile *f, ram_addr_t offset, int flags) { static RAMBlock *block = NULL; char id[256]; uint8_t len; if (flags & RAM_SAVE_FLAG_CONTINUE) { if (!block || block->length <= offset) { error_report("Ack, bad migration stream!"); return NULL; } return memory_region_get_ram_ptr(block->mr) + offset; } len = qemu_get_byte(f); qemu_get_buffer(f, (uint8_t *)id, len); id[len] = 0; QTAILQ_FOREACH(block, &ram_list.blocks, next) { if (!strncmp(id, block->idstr, sizeof(id)) && block->length > offset) { return memory_region_get_ram_ptr(block->mr) + offset; } } error_report("Can't find block %s!", id); }
164,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: horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } }
166,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Browser::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE); SessionService* session_service = SessionServiceFactory::GetForProfile(profile_); if (session_service) session_service->TabClosing(old_contents->web_contents()); TabInsertedAt(new_contents->web_contents(), index, (index == active_index())); int entry_count = new_contents->web_contents()->GetController().GetEntryCount(); if (entry_count > 0) { new_contents->web_contents()->GetController().NotifyEntryChanged( new_contents->web_contents()->GetController().GetEntryAtIndex( entry_count - 1), entry_count - 1); } if (session_service) { session_service->TabRestored(new_contents, tab_strip_model_->IsTabPinned(index)); } content::DevToolsManager::GetInstance()->ContentsReplaced( old_contents->web_contents(), new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void Browser::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedAtImpl(old_contents->web_contents(), index, DETACH_TYPE_REPLACE); SessionService* session_service = SessionServiceFactory::GetForProfile(profile_); if (session_service) session_service->TabClosing(old_contents->web_contents()); TabInsertedAt(new_contents->web_contents(), index, (index == active_index())); int entry_count = new_contents->web_contents()->GetController().GetEntryCount(); if (entry_count > 0) { new_contents->web_contents()->GetController().NotifyEntryChanged( new_contents->web_contents()->GetController().GetEntryAtIndex( entry_count - 1), entry_count - 1); } if (session_service) { session_service->TabRestored(new_contents, tab_strip_model_->IsTabPinned(index)); } content::DevToolsManager::GetInstance()->ContentsReplaced( old_contents->web_contents(), new_contents->web_contents()); }
171,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ssize_t f_hidg_write(struct file *file, const char __user *buffer, size_t count, loff_t *offp) { struct f_hidg *hidg = file->private_data; struct usb_request *req; unsigned long flags; ssize_t status = -ENOMEM; if (!access_ok(buffer, count)) return -EFAULT; spin_lock_irqsave(&hidg->write_spinlock, flags); #define WRITE_COND (!hidg->write_pending) try_again: /* write queue */ while (!WRITE_COND) { spin_unlock_irqrestore(&hidg->write_spinlock, flags); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible_exclusive( hidg->write_queue, WRITE_COND)) return -ERESTARTSYS; spin_lock_irqsave(&hidg->write_spinlock, flags); } hidg->write_pending = 1; req = hidg->req; count = min_t(unsigned, count, hidg->report_length); spin_unlock_irqrestore(&hidg->write_spinlock, flags); status = copy_from_user(req->buf, buffer, count); if (status != 0) { ERROR(hidg->func.config->cdev, "copy_from_user error\n"); status = -EINVAL; goto release_write_pending; } spin_lock_irqsave(&hidg->write_spinlock, flags); /* when our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, req); /* * TODO * Should we fail with error here? */ goto try_again; } req->status = 0; req->zero = 0; req->length = count; req->complete = f_hidg_req_complete; req->context = hidg; status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC); if (status < 0) { ERROR(hidg->func.config->cdev, "usb_ep_queue error on int endpoint %zd\n", status); goto release_write_pending_unlocked; } else { status = count; } spin_unlock_irqrestore(&hidg->write_spinlock, flags); return status; release_write_pending: spin_lock_irqsave(&hidg->write_spinlock, flags); release_write_pending_unlocked: hidg->write_pending = 0; spin_unlock_irqrestore(&hidg->write_spinlock, flags); wake_up(&hidg->write_queue); return status; } Commit Message: USB: gadget: f_hid: fix deadlock in f_hidg_write() In f_hidg_write() the write_spinlock is acquired before calling usb_ep_queue() which causes a deadlock when dummy_hcd is being used. This is because dummy_queue() callbacks into f_hidg_req_complete() which tries to acquire the same spinlock. This is (part of) the backtrace when the deadlock occurs: 0xffffffffc06b1410 in f_hidg_req_complete 0xffffffffc06a590a in usb_gadget_giveback_request 0xffffffffc06cfff2 in dummy_queue 0xffffffffc06a4b96 in usb_ep_queue 0xffffffffc06b1eb6 in f_hidg_write 0xffffffff8127730b in __vfs_write 0xffffffff812774d1 in vfs_write 0xffffffff81277725 in SYSC_write Fix this by releasing the write_spinlock before calling usb_ep_queue() Reviewed-by: James Bottomley <[email protected]> Tested-by: James Bottomley <[email protected]> Cc: [email protected] # 4.11+ Fixes: 749494b6bdbb ("usb: gadget: f_hid: fix: Move IN request allocation to set_alt()") Signed-off-by: Radoslav Gerganov <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> CWE ID: CWE-189
static ssize_t f_hidg_write(struct file *file, const char __user *buffer, size_t count, loff_t *offp) { struct f_hidg *hidg = file->private_data; struct usb_request *req; unsigned long flags; ssize_t status = -ENOMEM; if (!access_ok(buffer, count)) return -EFAULT; spin_lock_irqsave(&hidg->write_spinlock, flags); #define WRITE_COND (!hidg->write_pending) try_again: /* write queue */ while (!WRITE_COND) { spin_unlock_irqrestore(&hidg->write_spinlock, flags); if (file->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible_exclusive( hidg->write_queue, WRITE_COND)) return -ERESTARTSYS; spin_lock_irqsave(&hidg->write_spinlock, flags); } hidg->write_pending = 1; req = hidg->req; count = min_t(unsigned, count, hidg->report_length); spin_unlock_irqrestore(&hidg->write_spinlock, flags); status = copy_from_user(req->buf, buffer, count); if (status != 0) { ERROR(hidg->func.config->cdev, "copy_from_user error\n"); status = -EINVAL; goto release_write_pending; } spin_lock_irqsave(&hidg->write_spinlock, flags); /* when our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, req); /* * TODO * Should we fail with error here? */ goto try_again; } req->status = 0; req->zero = 0; req->length = count; req->complete = f_hidg_req_complete; req->context = hidg; spin_unlock_irqrestore(&hidg->write_spinlock, flags); status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC); if (status < 0) { ERROR(hidg->func.config->cdev, "usb_ep_queue error on int endpoint %zd\n", status); goto release_write_pending; } else { status = count; } return status; release_write_pending: spin_lock_irqsave(&hidg->write_spinlock, flags); hidg->write_pending = 0; spin_unlock_irqrestore(&hidg->write_spinlock, flags); wake_up(&hidg->write_queue); return status; }
170,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); } 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 RunInvTxfm(const int16_t *out, uint8_t *dst, int stride) { void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride); }
174,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; xmlNodePtr paramNode, oldInsert, fake; int oldBase; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; struct objChain { struct objChain *next; xmlXPathObjectPtr obj; }; struct objChain *savedObjChain = NULL, *savedObj; /* * retrieve func:function template */ data = (exsltFuncData *) xsltGetExtData (tctxt, EXSLT_FUNCTIONS_NAMESPACE); oldResult = data->result; data->result = NULL; func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs, ctxt->context->functionURI, ctxt->context->function); /* * params handling */ if (nargs > func->nargs) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: called with too many arguments\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_INVALID_ARITY; return; } if (func->content != NULL) { paramNode = func->content->prev; } else paramNode = NULL; if ((paramNode == NULL) && (func->nargs != 0)) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionFunction: nargs != 0 and " "param == NULL\n"); return; } if (tctxt->funcLevel > MAX_FUNC_RECURSION) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: detected a recursion\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_MEMORY_ERROR; return; } tctxt->funcLevel++; /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until * the last moment. After version 1.1.17 of the libxslt, the logic * of other parts of the library was changed, and the evaluation of * XPath expressions within parameters now takes place as soon as the * parameter is parsed/evaluated (xsltParseStylesheetCallerParam). * This means that the parameters need to be evaluated in lexical * order (since a variable is "in scope" as soon as it is declared). * However, on entry to this routine, the values (from the caller) are * in reverse order (held on the XPath context variable stack). To * accomplish what is required, I have added code to pop the XPath * objects off of the stack at the beginning and save them, then use * them (in the reverse order) as the params are evaluated. This * requires an xmlMalloc/xmlFree for each param set by the caller, * which is not very nice. There is probably a much better solution * (like change other code to delay the evaluation). */ /* * In order to give the function params and variables a new 'scope' * we change varsBase in the context. */ oldBase = tctxt->varsBase; tctxt->varsBase = tctxt->varsNr; /* If there are any parameters */ if (paramNode != NULL) { /* Fetch the stored argument values from the caller */ for (i = 0; i < nargs; i++) { savedObj = xmlMalloc(sizeof(struct objChain)); savedObj->next = savedObjChain; savedObj->obj = valuePop(ctxt); savedObjChain = savedObj; } /* * Prepare to process params in reverse order. First, go to * the beginning of the param chain. */ for (i = 1; i <= func->nargs; i++) { if (paramNode->prev == NULL) break; paramNode = paramNode->prev; } /* * i has total # params found, nargs is number which are present * as arguments from the caller * Calculate the number of un-set parameters */ notSet = func->nargs - nargs; for (; i > 0; i--) { param = xsltParseStylesheetCallerParam (tctxt, paramNode); if (i > notSet) { /* if parameter value set */ param->computed = 1; if (param->value != NULL) xmlXPathFreeObject(param->value); savedObj = savedObjChain; /* get next val from chain */ param->value = savedObj->obj; savedObjChain = savedObjChain->next; xmlFree(savedObj); } xsltLocalVariablePush(tctxt, param, -1); param->next = params; params = param; paramNode = paramNode->next; } } /* * actual processing */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; tctxt->insert = fake; xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt), func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; tctxt->varsBase = oldBase; /* restore original scope */ if (params != NULL) xsltFreeStackElemList(params); if (data->error != 0) goto error; if (data->result != NULL) { ret = data->result; } else ret = xmlXPathNewCString(""); data->result = oldResult; /* * It is an error if the instantiation of the template results in * the generation of result nodes. */ if (fake->children != NULL) { #ifdef LIBXML_DEBUG_ENABLED xmlDebugDumpNode (stderr, fake, 1); #endif xsltGenericError(xsltGenericErrorContext, "{%s}%s: cannot write to result tree while " "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); goto error; } xmlFreeNode(fake); valuePush(ctxt, ret); error: /* * IMPORTANT: This enables previously tree fragments marked as * being results of a function, to be garbage-collected after * the calling process exits. */ xsltExtensionInstructionResultFinalize(tctxt); tctxt->funcLevel--; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; xmlNodePtr paramNode, oldInsert, fake; int oldBase; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; struct objChain { struct objChain *next; xmlXPathObjectPtr obj; }; struct objChain *savedObjChain = NULL, *savedObj; /* * retrieve func:function template */ data = (exsltFuncData *) xsltGetExtData (tctxt, EXSLT_FUNCTIONS_NAMESPACE); oldResult = data->result; data->result = NULL; func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs, ctxt->context->functionURI, ctxt->context->function); if (func == NULL) { /* Should never happen */ xsltGenericError(xsltGenericErrorContext, "{%s}%s: not found\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_UNKNOWN_FUNC_ERROR; return; } /* * params handling */ if (nargs > func->nargs) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: called with too many arguments\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_INVALID_ARITY; return; } if (func->content != NULL) { paramNode = func->content->prev; } else paramNode = NULL; if ((paramNode == NULL) && (func->nargs != 0)) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionFunction: nargs != 0 and " "param == NULL\n"); return; } if (tctxt->funcLevel > MAX_FUNC_RECURSION) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: detected a recursion\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_MEMORY_ERROR; return; } tctxt->funcLevel++; /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until * the last moment. After version 1.1.17 of the libxslt, the logic * of other parts of the library was changed, and the evaluation of * XPath expressions within parameters now takes place as soon as the * parameter is parsed/evaluated (xsltParseStylesheetCallerParam). * This means that the parameters need to be evaluated in lexical * order (since a variable is "in scope" as soon as it is declared). * However, on entry to this routine, the values (from the caller) are * in reverse order (held on the XPath context variable stack). To * accomplish what is required, I have added code to pop the XPath * objects off of the stack at the beginning and save them, then use * them (in the reverse order) as the params are evaluated. This * requires an xmlMalloc/xmlFree for each param set by the caller, * which is not very nice. There is probably a much better solution * (like change other code to delay the evaluation). */ /* * In order to give the function params and variables a new 'scope' * we change varsBase in the context. */ oldBase = tctxt->varsBase; tctxt->varsBase = tctxt->varsNr; /* If there are any parameters */ if (paramNode != NULL) { /* Fetch the stored argument values from the caller */ for (i = 0; i < nargs; i++) { savedObj = xmlMalloc(sizeof(struct objChain)); savedObj->next = savedObjChain; savedObj->obj = valuePop(ctxt); savedObjChain = savedObj; } /* * Prepare to process params in reverse order. First, go to * the beginning of the param chain. */ for (i = 1; i <= func->nargs; i++) { if (paramNode->prev == NULL) break; paramNode = paramNode->prev; } /* * i has total # params found, nargs is number which are present * as arguments from the caller * Calculate the number of un-set parameters */ notSet = func->nargs - nargs; for (; i > 0; i--) { param = xsltParseStylesheetCallerParam (tctxt, paramNode); if (i > notSet) { /* if parameter value set */ param->computed = 1; if (param->value != NULL) xmlXPathFreeObject(param->value); savedObj = savedObjChain; /* get next val from chain */ param->value = savedObj->obj; savedObjChain = savedObjChain->next; xmlFree(savedObj); } xsltLocalVariablePush(tctxt, param, -1); param->next = params; params = param; paramNode = paramNode->next; } } /* * actual processing */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; tctxt->insert = fake; xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt), func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; tctxt->varsBase = oldBase; /* restore original scope */ if (params != NULL) xsltFreeStackElemList(params); if (data->error != 0) goto error; if (data->result != NULL) { ret = data->result; } else ret = xmlXPathNewCString(""); data->result = oldResult; /* * It is an error if the instantiation of the template results in * the generation of result nodes. */ if (fake->children != NULL) { #ifdef LIBXML_DEBUG_ENABLED xmlDebugDumpNode (stderr, fake, 1); #endif xsltGenericError(xsltGenericErrorContext, "{%s}%s: cannot write to result tree while " "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); goto error; } xmlFreeNode(fake); valuePush(ctxt, ret); error: /* * IMPORTANT: This enables previously tree fragments marked as * being results of a function, to be garbage-collected after * the calling process exits. */ xsltExtensionInstructionResultFinalize(tctxt); tctxt->funcLevel--; }
173,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } }
167,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: static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED) return -ENOENT; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
static int timer_start(Unit *u) { Timer *t = TIMER(u); TimerValue *v; assert(t); assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED); if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED) return -ENOENT; t->last_trigger = DUAL_TIMESTAMP_NULL; /* Reenable all timers that depend on unit activation time */ LIST_FOREACH(value, v, t->values) if (v->base == TIMER_ACTIVE) v->disabled = false; if (t->stamp_path) { struct stat st; if (stat(t->stamp_path, &st) >= 0) t->last_trigger.realtime = timespec_load(&st.st_atim); else if (errno == ENOENT) /* The timer has never run before, * make sure a stamp file exists. */ touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID); } t->result = TIMER_SUCCESS; timer_enter_waiting(t, true); return 1; }
170,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } Commit Message: Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42). CWE ID: CWE-476
static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* auth_user may be missing */ if (!user) { slog_error(client, "Password packet before auth packet?"); return false; } /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; }
170,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); } Commit Message: sctp: validate chunk len before actually using it Andrey Konovalov reported that KASAN detected that SCTP was using a slab beyond the boundaries. It was caused because when handling out of the blue packets in function sctp_sf_ootb() it was checking the chunk len only after already processing the first chunk, validating only for the 2nd and subsequent ones. The fix is to just move the check upwards so it's also validated for the 1st chunk. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Reviewed-by: Xin Long <[email protected]> Acked-by: Neil Horman <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
sctp_disposition_t sctp_sf_ootb(struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sk_buff *skb = chunk->skb; sctp_chunkhdr_t *ch; sctp_errhdr_t *err; __u8 *ch_end; int ootb_shut_ack = 0; int ootb_cookie_ack = 0; SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); ch = (sctp_chunkhdr_t *) chunk->chunk_hdr; do { /* Report violation if the chunk is less then minimal */ if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Report violation if chunk len overflows */ ch_end = ((__u8 *)ch) + SCTP_PAD4(ntohs(ch->length)); if (ch_end > skb_tail_pointer(skb)) return sctp_sf_violation_chunklen(net, ep, asoc, type, arg, commands); /* Now that we know we at least have a chunk header, * do things that are type appropriate. */ if (SCTP_CID_SHUTDOWN_ACK == ch->type) ootb_shut_ack = 1; /* RFC 2960, Section 3.3.7 * Moreover, under any circumstances, an endpoint that * receives an ABORT MUST NOT respond to that ABORT by * sending an ABORT of its own. */ if (SCTP_CID_ABORT == ch->type) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); /* RFC 8.4, 7) If the packet contains a "Stale cookie" ERROR * or a COOKIE ACK the SCTP Packet should be silently * discarded. */ if (SCTP_CID_COOKIE_ACK == ch->type) ootb_cookie_ack = 1; if (SCTP_CID_ERROR == ch->type) { sctp_walk_errors(err, ch) { if (SCTP_ERROR_STALE_COOKIE == err->cause) { ootb_cookie_ack = 1; break; } } } ch = (sctp_chunkhdr_t *) ch_end; } while (ch_end < skb_tail_pointer(skb)); if (ootb_shut_ack) return sctp_sf_shut_8_4_5(net, ep, asoc, type, arg, commands); else if (ootb_cookie_ack) return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); else return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); }
166,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::MessageLoopProxy* ProxyChannelDelegate::GetIPCMessageLoop() { return RenderThread::Get()->GetIOMessageLoopProxy().get(); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
base::MessageLoopProxy* ProxyChannelDelegate::GetIPCMessageLoop() {
170,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; } 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 char* Track::GetNameAsUTF8() const
174,343
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaStreamImpl::~MediaStreamImpl() { DCHECK(!peer_connection_handler_); if (dependency_factory_.get()) dependency_factory_->ReleasePeerConnectionFactory(); if (network_manager_) { if (chrome_worker_thread_.IsRunning()) { chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &MediaStreamImpl::DeleteIpcNetworkManager, base::Unretained(this))); } else { NOTREACHED() << "Worker thread not running."; } } } Commit Message: Explicitly stopping thread in MediaStreamImpl dtor to avoid any racing issues. This may solve the below bugs. BUG=112408,111202 TEST=content_unittests Review URL: https://chromiumcodereview.appspot.com/9307058 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120222 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
MediaStreamImpl::~MediaStreamImpl() { DCHECK(!peer_connection_handler_); if (dependency_factory_.get()) dependency_factory_->ReleasePeerConnectionFactory(); if (network_manager_) { if (chrome_worker_thread_.IsRunning()) { chrome_worker_thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &MediaStreamImpl::DeleteIpcNetworkManager, base::Unretained(this))); // Stopping the thread will wait until all tasks have been // processed before returning. We wait for the above task to finish before // letting the destructor continue to avoid any potential race issues. chrome_worker_thread_.Stop(); } else { NOTREACHED() << "Worker thread not running."; } } }
170,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str, *padding, *alignment, *ret; int str_l, padding_l; if ((nargs < 2) || (nargs > 3)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 3) alignment = xmlXPathPopString(ctxt); else alignment = NULL; padding = xmlXPathPopString(ctxt); str = xmlXPathPopString(ctxt); str_l = xmlUTF8Strlen (str); padding_l = xmlUTF8Strlen (padding); if (str_l == padding_l) { xmlXPathReturnString (ctxt, str); xmlFree(padding); xmlFree(alignment); return; } if (str_l > padding_l) { ret = xmlUTF8Strndup (str, padding_l); } else { if (xmlStrEqual(alignment, (const xmlChar *) "right")) { ret = xmlUTF8Strndup (padding, padding_l - str_l); ret = xmlStrcat (ret, str); } else if (xmlStrEqual(alignment, (const xmlChar *) "center")) { int left = (padding_l - str_l) / 2; int right_start; ret = xmlUTF8Strndup (padding, left); ret = xmlStrcat (ret, str); right_start = xmlUTF8Strsize (padding, left + str_l); ret = xmlStrcat (ret, padding + right_start); } else { int str_s; str_s = xmlStrlen (str); ret = xmlStrdup (str); ret = xmlStrcat (ret, padding + str_s); } } xmlXPathReturnString (ctxt, ret); xmlFree(str); xmlFree(padding); xmlFree(alignment); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str, *padding, *alignment, *ret; int str_l, padding_l; if ((nargs < 2) || (nargs > 3)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 3) alignment = xmlXPathPopString(ctxt); else alignment = NULL; padding = xmlXPathPopString(ctxt); str = xmlXPathPopString(ctxt); str_l = xmlUTF8Strlen (str); padding_l = xmlUTF8Strlen (padding); if (str_l == padding_l) { xmlXPathReturnString (ctxt, str); xmlFree(padding); xmlFree(alignment); return; } if (str_l > padding_l) { ret = xmlUTF8Strndup (str, padding_l); } else { if (xmlStrEqual(alignment, (const xmlChar *) "right")) { ret = xmlUTF8Strndup (padding, padding_l - str_l); ret = xmlStrcat (ret, str); } else if (xmlStrEqual(alignment, (const xmlChar *) "center")) { int left = (padding_l - str_l) / 2; int right_start; ret = xmlUTF8Strndup (padding, left); ret = xmlStrcat (ret, str); right_start = xmlUTF8Strsize (padding, left + str_l); ret = xmlStrcat (ret, padding + right_start); } else { int str_s; str_s = xmlUTF8Strsize(padding, str_l); ret = xmlStrdup (str); ret = xmlStrcat (ret, padding + str_s); } } xmlXPathReturnString (ctxt, ret); xmlFree(str); xmlFree(padding); xmlFree(alignment); }
173,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sp<IMediaPlayerService>& MediaMetadataRetriever::getService() { Mutex::Autolock lock(sServiceLock); if (sService == 0) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16("media.player")); if (binder != 0) { break; } ALOGW("MediaPlayerService not published, waiting..."); usleep(500000); // 0.5 s } while (true); if (sDeathNotifier == NULL) { sDeathNotifier = new DeathNotifier(); } binder->linkToDeath(sDeathNotifier); sService = interface_cast<IMediaPlayerService>(binder); } ALOGE_IF(sService == 0, "no MediaPlayerService!?"); return sService; } Commit Message: Get service by value instead of reference to prevent a cleared service binder from being used. Bug: 26040840 Change-Id: Ifb5483c55b172d3553deb80dbe27f2204b86ecdb CWE ID: CWE-119
const sp<IMediaPlayerService>& MediaMetadataRetriever::getService() const sp<IMediaPlayerService> MediaMetadataRetriever::getService() { Mutex::Autolock lock(sServiceLock); if (sService == 0) { sp<IServiceManager> sm = defaultServiceManager(); sp<IBinder> binder; do { binder = sm->getService(String16("media.player")); if (binder != 0) { break; } ALOGW("MediaPlayerService not published, waiting..."); usleep(500000); // 0.5 s } while (true); if (sDeathNotifier == NULL) { sDeathNotifier = new DeathNotifier(); } binder->linkToDeath(sDeathNotifier); sService = interface_cast<IMediaPlayerService>(binder); } ALOGE_IF(sService == 0, "no MediaPlayerService!?"); return sService; }
173,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: PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */ { const char *endptr = val + vallen; zval *session_vars; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); ALLOC_INIT_ZVAL(session_vars); if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) { var_push_dtor(&var_hash, &session_vars); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PS(http_session_vars)) { zval_ptr_dtor(&PS(http_session_vars)); } if (Z_TYPE_P(session_vars) == IS_NULL) { array_init(session_vars); } PS(http_session_vars) = session_vars; ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1); return SUCCESS; } /* }}} */ Commit Message: CWE ID: CWE-416
PS_SERIALIZER_DECODE_FUNC(php_serialize) /* {{{ */ { const char *endptr = val + vallen; zval *session_vars; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); ALLOC_INIT_ZVAL(session_vars); if (php_var_unserialize(&session_vars, &val, endptr, &var_hash TSRMLS_CC)) { var_push_dtor(&var_hash, &session_vars); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (PS(http_session_vars)) { zval_ptr_dtor(&PS(http_session_vars)); } if (Z_TYPE_P(session_vars) == IS_NULL) { array_init(session_vars); } PS(http_session_vars) = session_vars; ZEND_SET_GLOBAL_VAR_WITH_LENGTH("_SESSION", sizeof("_SESSION"), PS(http_session_vars), Z_REFCOUNT_P(PS(http_session_vars)) + 1, 1); return SUCCESS; } /* }}} */
164,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool_t xdr_nullstring(XDR *xdrs, char **objp) { u_int size; if (xdrs->x_op == XDR_ENCODE) { if (*objp == NULL) size = 0; else size = strlen(*objp) + 1; } if (! xdr_u_int(xdrs, &size)) { return FALSE; } switch (xdrs->x_op) { case XDR_DECODE: if (size == 0) { *objp = NULL; return TRUE; } else if (*objp == NULL) { *objp = (char *) mem_alloc(size); if (*objp == NULL) { errno = ENOMEM; return FALSE; } } return (xdr_opaque(xdrs, *objp, size)); case XDR_ENCODE: if (size != 0) return (xdr_opaque(xdrs, *objp, size)); return TRUE; case XDR_FREE: if (*objp != NULL) mem_free(*objp, size); *objp = NULL; return TRUE; } return FALSE; } Commit Message: Verify decoded kadmin C strings [CVE-2015-8629] In xdr_nullstring(), check that the decoded string is terminated with a zero byte and does not contain any internal zero bytes. CVE-2015-8629: In all versions of MIT krb5, an authenticated attacker can cause kadmind to read beyond the end of allocated memory by sending a string without a terminating zero byte. Information leakage may be possible for an attacker with permission to modify the database. CVSSv2 Vector: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C ticket: 8341 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
bool_t xdr_nullstring(XDR *xdrs, char **objp) { u_int size; if (xdrs->x_op == XDR_ENCODE) { if (*objp == NULL) size = 0; else size = strlen(*objp) + 1; } if (! xdr_u_int(xdrs, &size)) { return FALSE; } switch (xdrs->x_op) { case XDR_DECODE: if (size == 0) { *objp = NULL; return TRUE; } else if (*objp == NULL) { *objp = (char *) mem_alloc(size); if (*objp == NULL) { errno = ENOMEM; return FALSE; } } if (!xdr_opaque(xdrs, *objp, size)) return FALSE; /* Check that the unmarshalled bytes are a C string. */ if ((*objp)[size - 1] != '\0') return FALSE; if (memchr(*objp, '\0', size - 1) != NULL) return FALSE; return TRUE; case XDR_ENCODE: if (size != 0) return (xdr_opaque(xdrs, *objp, size)); return TRUE; case XDR_FREE: if (*objp != NULL) mem_free(*objp, size); *objp = NULL; return TRUE; } return FALSE; }
167,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old; struct mount *new; int copy_flags; BUG_ON(!ns); if (likely(!(flags & CLONE_NEWNS))) { get_mnt_ns(ns); return ns; } old = ns->root; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE; if (user_ns != ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; list_add_tail(&new_ns->list, &new->mnt_list); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (new_fs) { if (&p->mnt == new_fs->root.mnt) { new_fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == new_fs->pwd.mnt) { new_fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); if (!q) break; while (p->mnt.mnt_root != q->mnt.mnt_root) p = next_mnt(p, old); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400
struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old; struct mount *new; int copy_flags; BUG_ON(!ns); if (likely(!(flags & CLONE_NEWNS))) { get_mnt_ns(ns); return ns; } old = ns->root; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE; if (user_ns != ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; list_add_tail(&new_ns->list, &new->mnt_list); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; new_ns->mounts++; if (new_fs) { if (&p->mnt == new_fs->root.mnt) { new_fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == new_fs->pwd.mnt) { new_fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); if (!q) break; while (p->mnt.mnt_root != q->mnt.mnt_root) p = next_mnt(p, old); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; }
167,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_rec_arrays (MyObject *obj, GPtrArray *in, GPtrArray **ret, GError **error) { char **strs; GArray *ints; guint v_UINT; if (in->len != 2) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid array len"); return FALSE; } strs = g_ptr_array_index (in, 0); if (!*strs || strcmp (*strs, "foo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "bar")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 0"); return FALSE; } strs = g_ptr_array_index (in, 1); if (!*strs || strcmp (*strs, "baz")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 0"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "whee")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 1"); return FALSE; } strs++; if (!*strs || strcmp (*strs, "moo")) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string 2"); return FALSE; } strs++; if (*strs) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "invalid string array len in pos 1"); return FALSE; } *ret = g_ptr_array_new (); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 10; g_array_append_val (ints, v_UINT); v_UINT = 42; g_array_append_val (ints, v_UINT); v_UINT = 27; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); ints = g_array_new (TRUE, TRUE, sizeof (guint)); v_UINT = 30; g_array_append_val (ints, v_UINT); g_ptr_array_add (*ret, ints); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_rec_arrays (MyObject *obj, GPtrArray *in, GPtrArray **ret, GError **error)
165,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from >= to) { eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to); return -1; } ut8 *buf = calloc (to - from, 1); if (!buf || !min) { return -1; } r_buf_read_at (bf->buf, from, buf, to - from); while (needle < to) { rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if ((to - needle) > 5) { bool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4]; if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = " abtnvfr e " " " " " " \\"[r]; } else { break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start -from> 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start -from> 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } bs->paddr = bs->vaddr = str_start; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); } else { print_string (bs, bf); r_bin_string_free (bs); } } } free (buf); return count; } Commit Message: Fix #9902 - Fix oobread in RBin.string_scan_range CWE ID: CWE-125
static int string_scan_range(RList *list, RBinFile *bf, int min, const ut64 from, const ut64 to, int type) { ut8 tmp[R_STRING_SCAN_BUFFER_SIZE]; ut64 str_start, needle = from; int count = 0, i, rc, runes; int str_type = R_STRING_TYPE_DETECT; if (type == -1) { type = R_STRING_TYPE_DETECT; } if (from >= to) { eprintf ("Invalid range to find strings 0x%llx .. 0x%llx\n", from, to); return -1; } int len = to - from; ut8 *buf = calloc (len, 1); if (!buf || !min) { return -1; } r_buf_read_at (bf->buf, from, buf, len); while (needle < to) { rc = r_utf8_decode (buf + needle - from, to - needle, NULL); if (!rc) { needle++; continue; } if (type == R_STRING_TYPE_DETECT) { char *w = (char *)buf + needle + rc - from; if ((to - needle) > 5 + rc) { bool is_wide32 = (needle + rc + 2 < to) && (!w[0] && !w[1] && !w[2] && w[3] && !w[4]); if (is_wide32) { str_type = R_STRING_TYPE_WIDE32; } else { bool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2]; str_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII; } } else { str_type = R_STRING_TYPE_ASCII; } } else { str_type = type; } runes = 0; str_start = needle; /* Eat a whole C string */ for (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) { RRune r = {0}; if (str_type == R_STRING_TYPE_WIDE32) { rc = r_utf32le_decode (buf + needle - from, to - needle, &r); if (rc) { rc = 4; } } else if (str_type == R_STRING_TYPE_WIDE) { rc = r_utf16le_decode (buf + needle - from, to - needle, &r); if (rc == 1) { rc = 2; } } else { rc = r_utf8_decode (buf + needle - from, to - needle, &r); if (rc > 1) { str_type = R_STRING_TYPE_UTF8; } } /* Invalid sequence detected */ if (!rc) { needle++; break; } needle += rc; if (r_isprint (r) && r != '\\') { if (str_type == R_STRING_TYPE_WIDE32) { if (r == 0xff) { r = 0; } } rc = r_utf8_encode (&tmp[i], r); runes++; /* Print the escape code */ } else if (r && r < 0x100 && strchr ("\b\v\f\n\r\t\a\033\\", (char)r)) { if ((i + 32) < sizeof (tmp) && r < 93) { tmp[i + 0] = '\\'; tmp[i + 1] = " abtnvfr e " " " " " " \\"[r]; } else { break; } rc = 2; runes++; } else { /* \0 marks the end of C-strings */ break; } } tmp[i++] = '\0'; if (runes >= min) { if (str_type == R_STRING_TYPE_ASCII) { int j; for (j = 0; j < i; j++) { char ch = tmp[j]; if (ch != '\n' && ch != '\r' && ch != '\t') { if (!IS_PRINTABLE (tmp[j])) { continue; } } } } RBinString *bs = R_NEW0 (RBinString); if (!bs) { break; } bs->type = str_type; bs->length = runes; bs->size = needle - str_start; bs->ordinal = count++; switch (str_type) { case R_STRING_TYPE_WIDE: if (str_start -from> 1) { const ut8 *p = buf + str_start - 2 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 2; // \xff\xfe } } break; case R_STRING_TYPE_WIDE32: if (str_start -from> 3) { const ut8 *p = buf + str_start - 4 - from; if (p[0] == 0xff && p[1] == 0xfe) { str_start -= 4; // \xff\xfe\x00\x00 } } break; } bs->paddr = bs->vaddr = str_start; bs->string = r_str_ndup ((const char *)tmp, i); if (list) { r_list_append (list, bs); } else { print_string (bs, bf); r_bin_string_free (bs); } } } free (buf); return count; }
169,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false), audio_thread_(new AudioDeviceThread()) { CHECK(ipc_); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
AudioOutputDevice::AudioOutputDevice( AudioOutputIPC* ipc, const scoped_refptr<base::MessageLoopProxy>& io_loop) : ScopedLoopObserver(io_loop), input_channels_(0), callback_(NULL), ipc_(ipc), stream_id_(0), play_on_start_(true), is_started_(false) { CHECK(ipc_); }
170,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f = NULL; int w, h, prec; int i, numcomps, max; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ opj_image_t * image = NULL; int adjustS, ushift, dshift, force8; char endian1, endian2, sign; char signtmp[32]; char temp[32]; int bigendian; opj_image_comp_t *comp = NULL; numcomps = 1; color_space = OPJ_CLRSPC_GRAY; memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); max = 0; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !\n", filename); return NULL; } fseek(f, 0, SEEK_SET); if (fscanf(f, "PG%[ \t]%c%c%[ \t+-]%d%[ \t]%d%[ \t]%d", temp, &endian1, &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { fclose(f); fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n"); return NULL; } i = 0; sign = '+'; while (signtmp[i] != '\0') { if (signtmp[i] == '-') { sign = '-'; } i++; } fgetc(f); if (endian1 == 'M' && endian2 == 'L') { bigendian = 1; } else if (endian2 == 'M' && endian1 == 'L') { bigendian = 0; } else { fclose(f); fprintf(stderr, "Bad pgx header, please check input file\n"); return NULL; } /* initialize image component */ cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1; cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1; if (sign == '-') { cmptparm.sgnd = 1; } else { cmptparm.sgnd = 0; } if (prec < 8) { force8 = 1; ushift = 8 - prec; dshift = prec - ushift; if (cmptparm.sgnd) { adjustS = (1 << (prec - 1)); } else { adjustS = 0; } cmptparm.sgnd = 0; prec = 8; } else { ushift = dshift = force8 = adjustS = 0; } cmptparm.prec = (OPJ_UINT32)prec; cmptparm.bpp = (OPJ_UINT32)prec; cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = cmptparm.x0; image->y0 = cmptparm.x0; image->x1 = cmptparm.w; image->y1 = cmptparm.h; /* set image data */ comp = &image->comps[0]; for (i = 0; i < w * h; i++) { int v; if (force8) { v = readuchar(f) + adjustS; v = (v << ushift) + (v >> dshift); comp->data[i] = (unsigned char)v; if (v > max) { max = v; } continue; } if (comp->prec == 8) { if (!comp->sgnd) { v = readuchar(f); } else { v = (char) readuchar(f); } } else if (comp->prec <= 16) { if (!comp->sgnd) { v = readushort(f, bigendian); } else { v = (short) readushort(f, bigendian); } } else { if (!comp->sgnd) { v = (int)readuint(f, bigendian); } else { v = (int) readuint(f, bigendian); } } if (v > max) { max = v; } comp->data[i] = v; } fclose(f); comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; return image; } Commit Message: pgxtoimage(): fix write stack buffer overflow (#997) CWE ID: CWE-787
opj_image_t* pgxtoimage(const char *filename, opj_cparameters_t *parameters) { FILE *f = NULL; int w, h, prec; int i, numcomps, max; OPJ_COLOR_SPACE color_space; opj_image_cmptparm_t cmptparm; /* maximum of 1 component */ opj_image_t * image = NULL; int adjustS, ushift, dshift, force8; char endian1, endian2, sign; char signtmp[32]; char temp[32]; int bigendian; opj_image_comp_t *comp = NULL; numcomps = 1; color_space = OPJ_CLRSPC_GRAY; memset(&cmptparm, 0, sizeof(opj_image_cmptparm_t)); max = 0; f = fopen(filename, "rb"); if (!f) { fprintf(stderr, "Failed to open %s for reading !\n", filename); return NULL; } fseek(f, 0, SEEK_SET); if (fscanf(f, "PG%31[ \t]%c%c%31[ \t+-]%d%31[ \t]%d%31[ \t]%d", temp, &endian1, &endian2, signtmp, &prec, temp, &w, temp, &h) != 9) { fclose(f); fprintf(stderr, "ERROR: Failed to read the right number of element from the fscanf() function!\n"); return NULL; } i = 0; sign = '+'; while (signtmp[i] != '\0') { if (signtmp[i] == '-') { sign = '-'; } i++; } fgetc(f); if (endian1 == 'M' && endian2 == 'L') { bigendian = 1; } else if (endian2 == 'M' && endian1 == 'L') { bigendian = 0; } else { fclose(f); fprintf(stderr, "Bad pgx header, please check input file\n"); return NULL; } /* initialize image component */ cmptparm.x0 = (OPJ_UINT32)parameters->image_offset_x0; cmptparm.y0 = (OPJ_UINT32)parameters->image_offset_y0; cmptparm.w = !cmptparm.x0 ? (OPJ_UINT32)((w - 1) * parameters->subsampling_dx + 1) : cmptparm.x0 + (OPJ_UINT32)(w - 1) * (OPJ_UINT32)parameters->subsampling_dx + 1; cmptparm.h = !cmptparm.y0 ? (OPJ_UINT32)((h - 1) * parameters->subsampling_dy + 1) : cmptparm.y0 + (OPJ_UINT32)(h - 1) * (OPJ_UINT32)parameters->subsampling_dy + 1; if (sign == '-') { cmptparm.sgnd = 1; } else { cmptparm.sgnd = 0; } if (prec < 8) { force8 = 1; ushift = 8 - prec; dshift = prec - ushift; if (cmptparm.sgnd) { adjustS = (1 << (prec - 1)); } else { adjustS = 0; } cmptparm.sgnd = 0; prec = 8; } else { ushift = dshift = force8 = adjustS = 0; } cmptparm.prec = (OPJ_UINT32)prec; cmptparm.bpp = (OPJ_UINT32)prec; cmptparm.dx = (OPJ_UINT32)parameters->subsampling_dx; cmptparm.dy = (OPJ_UINT32)parameters->subsampling_dy; /* create the image */ image = opj_image_create((OPJ_UINT32)numcomps, &cmptparm, color_space); if (!image) { fclose(f); return NULL; } /* set image offset and reference grid */ image->x0 = cmptparm.x0; image->y0 = cmptparm.x0; image->x1 = cmptparm.w; image->y1 = cmptparm.h; /* set image data */ comp = &image->comps[0]; for (i = 0; i < w * h; i++) { int v; if (force8) { v = readuchar(f) + adjustS; v = (v << ushift) + (v >> dshift); comp->data[i] = (unsigned char)v; if (v > max) { max = v; } continue; } if (comp->prec == 8) { if (!comp->sgnd) { v = readuchar(f); } else { v = (char) readuchar(f); } } else if (comp->prec <= 16) { if (!comp->sgnd) { v = readushort(f, bigendian); } else { v = (short) readushort(f, bigendian); } } else { if (!comp->sgnd) { v = (int)readuint(f, bigendian); } else { v = (int) readuint(f, bigendian); } } if (v > max) { max = v; } comp->data[i] = v; } fclose(f); comp->bpp = (OPJ_UINT32)int_floorlog2(max) + 1; return image; }
167,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ExtensionTtsPlatformImplChromeOs::Speak( const std::string& utterance, const std::string& locale, const std::string& gender, double rate, double pitch, double volume) { chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get(); if (!cros_library->EnsureLoaded()) { set_error(kCrosLibraryNotLoadedError); return false; } std::string options; if (!locale.empty()) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale, locale, &options); } if (!gender.empty()) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyGender, gender, &options); } if (rate >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate, DoubleToString(rate * 5), &options); } if (pitch >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch, DoubleToString(pitch * 2), &options); } if (volume >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume, DoubleToString(volume * 5), &options); } if (!options.empty()) { cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties( options.c_str()); } return cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str()); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool ExtensionTtsPlatformImplChromeOs::Speak( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { chromeos::CrosLibrary* cros_library = chromeos::CrosLibrary::Get(); if (!cros_library->EnsureLoaded()) { set_error(kCrosLibraryNotLoadedError); return false; } utterance_id_ = utterance_id; utterance_length_ = utterance.size(); std::string options; if (!lang.empty()) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyLocale, lang, &options); } if (params.rate >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyRate, DoubleToString(1.5 + params.rate * 2.5), &options); } if (params.pitch >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyPitch, DoubleToString(params.pitch), &options); } if (params.volume >= 0.0) { AppendSpeakOption( chromeos::SpeechSynthesisLibrary::kSpeechPropertyVolume, DoubleToString(params.volume * 5), &options); } if (!options.empty()) { cros_library->GetSpeechSynthesisLibrary()->SetSpeakProperties( options.c_str()); } bool result = cros_library->GetSpeechSynthesisLibrary()->Speak(utterance.c_str()); if (result) { ExtensionTtsController* controller = ExtensionTtsController::GetInstance(); controller->OnTtsEvent(utterance_id_, TTS_EVENT_START, 0, std::string()); PollUntilSpeechFinishes(utterance_id_); } return result; }
170,399
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_ = 8; fwd_txfm_ref = fdct8x8_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); pitch_ = 8; fwd_txfm_ref = fdct8x8_ref; bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,562
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
167,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sgi_clock_get(clockid_t clockid, struct timespec *tp) { u64 nsec; nsec = rtc_time() * sgi_clock_period + sgi_clock_offset.tv_nsec; tp->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &tp->tv_nsec) + sgi_clock_offset.tv_sec; return 0; }; Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
static int sgi_clock_get(clockid_t clockid, struct timespec *tp) { u64 nsec; nsec = rtc_time() * sgi_clock_period + sgi_clock_offset.tv_nsec; *tp = ns_to_timespec(nsec); tp->tv_sec += sgi_clock_offset.tv_sec; return 0; };
165,749
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); db_tracker_->HandleSqliteError(origin_identifier, database_name, error); } Commit Message: WebDatabase: check path traversal in origin_identifier BUG=172264 Review URL: https://chromiumcodereview.appspot.com/12212091 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22
void DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) { RecordAction(UserMetricsAction("BadMessageTerminate_DBMF")); BadMessageReceived(); return; } db_tracker_->HandleSqliteError(origin_identifier, database_name, error); }
171,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } Commit Message: Sanitize 'move_pages()' permission checks The 'move_paghes()' system call was introduced long long ago with the same permission checks as for sending a signal (except using CAP_SYS_NICE instead of CAP_SYS_KILL for the overriding capability). That turns out to not be a great choice - while the system call really only moves physical page allocations around (and you need other capabilities to do a lot of it), you can check the return value to map out some the virtual address choices and defeat ASLR of a binary that still shares your uid. So change the access checks to the more common 'ptrace_may_access()' model instead. This tightens the access checks for the uid, and also effectively changes the CAP_SYS_NICE check to CAP_SYS_PTRACE, but it's unlikely that anybody really _uses_ this legacy system call any more (we hav ebetter NUMA placement models these days), so I expect nobody to notice. Famous last words. Reported-by: Otto Ebeling <[email protected]> Acked-by: Eric W. Biederman <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. Use the regular "ptrace_may_access()" checks. */ if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; }
167,770
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: u32 h264bsdInit(storage_t *pStorage, u32 noOutputReordering) { /* Variables */ u32 size; /* Code */ ASSERT(pStorage); h264bsdInitStorage(pStorage); /* allocate mbLayer to be next multiple of 64 to enable use of * specific NEON optimized "memset" for clearing the structure */ size = (sizeof(macroblockLayer_t) + 63) & ~0x3F; pStorage->mbLayer = (macroblockLayer_t*)H264SwDecMalloc(size); if (!pStorage->mbLayer) return HANTRO_NOK; if (noOutputReordering) pStorage->noReordering = HANTRO_TRUE; return HANTRO_OK; } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
u32 h264bsdInit(storage_t *pStorage, u32 noOutputReordering) { /* Variables */ u32 size; /* Code */ ASSERT(pStorage); h264bsdInitStorage(pStorage); /* allocate mbLayer to be next multiple of 64 to enable use of * specific NEON optimized "memset" for clearing the structure */ size = (sizeof(macroblockLayer_t) + 63) & ~0x3F; pStorage->mbLayer = (macroblockLayer_t*)H264SwDecMalloc(size, 1); if (!pStorage->mbLayer) return HANTRO_NOK; if (noOutputReordering) pStorage->noReordering = HANTRO_TRUE; return HANTRO_OK; }
173,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || 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; } uint32_t numSyncSamples = U32_AT(&header[4]); if (numSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = (uint64_t)numSyncSamples * sizeof(uint32_t); if (allocSize > kMaxTotalSize) { ALOGE("Sync sample table size too large."); return ERROR_OUT_OF_RANGE; } mTotalSize += allocSize; if (mTotalSize > kMaxTotalSize) { ALOGE("Sync sample table size would make sample table too large.\n" " Requested sync sample table size = %llu\n" " Eventual sample table size >= %llu\n" " Allowed sample table size = %llu\n", (unsigned long long)allocSize, (unsigned long long)mTotalSize, (unsigned long long)kMaxTotalSize); return ERROR_OUT_OF_RANGE; } mSyncSamples = new (std::nothrow) uint32_t[numSyncSamples]; if (!mSyncSamples) { ALOGE("Cannot allocate sync sample table with %llu entries.", (unsigned long long)numSyncSamples); return ERROR_OUT_OF_RANGE; } if (mDataSource->readAt(data_offset + 8, mSyncSamples, (size_t)allocSize) != (ssize_t)allocSize) { delete mSyncSamples; mSyncSamples = NULL; return ERROR_IO; } for (size_t i = 0; i < numSyncSamples; ++i) { if (mSyncSamples[i] == 0) { ALOGE("b/32423862, unexpected zero value in stss"); continue; } mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } mSyncSampleOffset = data_offset; mNumSyncSamples = numSyncSamples; return OK; } Commit Message: Fix 'potential memory leak' compiler warning. This CL fixes the following compiler warning: frameworks/av/media/libstagefright/SampleTable.cpp:569:9: warning: Memory allocated by 'new[]' should be deallocated by 'delete[]', not 'delete'. Bug: 33137046 Test: Compiled with change; no warning generated. Change-Id: I29abd90e02bf482fa840d1f7206ebbdacf7dfa37 (cherry picked from commit 158c197b668ad684f92829db6a31bee3aec794ba) (cherry picked from commit 37c428cd521351837fccb6864f509f996820b234) CWE ID: CWE-772
status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || 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; } uint32_t numSyncSamples = U32_AT(&header[4]); if (numSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = (uint64_t)numSyncSamples * sizeof(uint32_t); if (allocSize > kMaxTotalSize) { ALOGE("Sync sample table size too large."); return ERROR_OUT_OF_RANGE; } mTotalSize += allocSize; if (mTotalSize > kMaxTotalSize) { ALOGE("Sync sample table size would make sample table too large.\n" " Requested sync sample table size = %llu\n" " Eventual sample table size >= %llu\n" " Allowed sample table size = %llu\n", (unsigned long long)allocSize, (unsigned long long)mTotalSize, (unsigned long long)kMaxTotalSize); return ERROR_OUT_OF_RANGE; } mSyncSamples = new (std::nothrow) uint32_t[numSyncSamples]; if (!mSyncSamples) { ALOGE("Cannot allocate sync sample table with %llu entries.", (unsigned long long)numSyncSamples); return ERROR_OUT_OF_RANGE; } if (mDataSource->readAt(data_offset + 8, mSyncSamples, (size_t)allocSize) != (ssize_t)allocSize) { delete[] mSyncSamples; mSyncSamples = NULL; return ERROR_IO; } for (size_t i = 0; i < numSyncSamples; ++i) { if (mSyncSamples[i] == 0) { ALOGE("b/32423862, unexpected zero value in stss"); continue; } mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } mSyncSampleOffset = data_offset; mNumSyncSamples = numSyncSamples; return OK; }
173,992
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir, const FilePath& text) { FilePath old_cur_directory; if (!base_dir.empty()) { file_util::GetCurrentDirectory(&old_cur_directory); file_util::SetCurrentDirectory(base_dir); } FilePath::StringType trimmed; PrepareStringForFileOps(text, &trimmed); bool is_file = true; FilePath full_path; if (!ValidPathForFile(trimmed, &full_path)) { #if defined(OS_WIN) std::wstring unescaped = UTF8ToWide(UnescapeURLComponent( WideToUTF8(trimmed), UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS)); #elif defined(OS_POSIX) std::string unescaped = UnescapeURLComponent( trimmed, UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS); #endif if (!ValidPathForFile(unescaped, &full_path)) is_file = false; } if (!base_dir.empty()) file_util::SetCurrentDirectory(old_cur_directory); if (is_file) { GURL file_url = net::FilePathToFileURL(full_path); if (file_url.is_valid()) return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(), net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL, NULL, NULL))); } #if defined(OS_WIN) std::string text_utf8 = WideToUTF8(text.value()); #elif defined(OS_POSIX) std::string text_utf8 = text.value(); #endif return FixupURL(text_utf8, std::string()); } Commit Message: Be a little more careful whether something is an URL or a file path. BUG=72492 Review URL: http://codereview.chromium.org/7572046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
GURL URLFixerUpper::FixupRelativeFile(const FilePath& base_dir, const FilePath& text) { FilePath old_cur_directory; if (!base_dir.empty()) { file_util::GetCurrentDirectory(&old_cur_directory); file_util::SetCurrentDirectory(base_dir); } FilePath::StringType trimmed; PrepareStringForFileOps(text, &trimmed); bool is_file = true; // Avoid recognizing definite non-file URLs as file paths. GURL gurl(trimmed); if (gurl.is_valid() && gurl.IsStandard()) is_file = false; FilePath full_path; if (is_file && !ValidPathForFile(trimmed, &full_path)) { #if defined(OS_WIN) std::wstring unescaped = UTF8ToWide(UnescapeURLComponent( WideToUTF8(trimmed), UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS)); #elif defined(OS_POSIX) std::string unescaped = UnescapeURLComponent( trimmed, UnescapeRule::SPACES | UnescapeRule::URL_SPECIAL_CHARS); #endif if (!ValidPathForFile(unescaped, &full_path)) is_file = false; } if (!base_dir.empty()) file_util::SetCurrentDirectory(old_cur_directory); if (is_file) { GURL file_url = net::FilePathToFileURL(full_path); if (file_url.is_valid()) return GURL(UTF16ToUTF8(net::FormatUrl(file_url, std::string(), net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL, NULL, NULL))); } #if defined(OS_WIN) std::string text_utf8 = WideToUTF8(text.value()); #elif defined(OS_POSIX) std::string text_utf8 = text.value(); #endif return FixupURL(text_utf8, std::string()); }
170,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { if (paintingDisabled()) return; if (numPoints <= 1) return; notImplemented(); }
170,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) * 4 >= std::numeric_limits<int32>::max()) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); } Commit Message: Security fix: integer overflow on checking image size Test is left in another CL (codereview.chromiu,.org/11274036) to avoid conflict there. Hope it's fine. BUG=160926 Review URL: https://chromiumcodereview.appspot.com/11410081 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167882 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-190
bool PPB_ImageData_Impl::Init(PP_ImageDataFormat format, int width, int height, bool init_to_zero) { if (!IsImageDataFormatSupported(format)) return false; // Only support this one format for now. if (width <= 0 || height <= 0) return false; if (static_cast<int64>(width) * static_cast<int64>(height) >= std::numeric_limits<int32>::max() / 4) return false; // Prevent overflow of signed 32-bit ints. format_ = format; width_ = width; height_ = height; return backend_->Init(this, format, width, height, init_to_zero); }
170,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 keyring_describe(const struct key *keyring, struct seq_file *m) { if (keyring->description) seq_puts(m, keyring->description); else seq_puts(m, "[anon]"); if (key_is_instantiated(keyring)) { if (keyring->keys.nr_leaves_on_tree != 0) seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); else seq_puts(m, ": empty"); } } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static void keyring_describe(const struct key *keyring, struct seq_file *m) { if (keyring->description) seq_puts(m, keyring->description); else seq_puts(m, "[anon]"); if (key_is_positive(keyring)) { if (keyring->keys.nr_leaves_on_tree != 0) seq_printf(m, ": %lu", keyring->keys.nr_leaves_on_tree); else seq_puts(m, ": empty"); } }
167,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); } Commit Message: All: Merge some file writing extension checks CWE ID: CWE-269
void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } if (!COM_CompareExtension(filename, ".cfg")) { Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); }
170,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: tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( "tt_face_load_kern:" " kerning table is too small - ignored\n" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( "tt_face_load_kern:" " could not extract kerning table\n" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; } Commit Message: CWE ID: CWE-125
tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( "tt_face_load_kern:" " kerning table is too small - ignored\n" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( "tt_face_load_kern:" " could not extract kerning table\n" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 + 8 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & ~8 ) != 0x0001 || p + 8 > p_limit ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; }
164,865
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <[email protected]> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <[email protected]> CWE ID: CWE-20
static inline int mk_vhost_fdt_close(struct session_request *sr) { int id; unsigned int hash; struct vhost_fdt_hash_table *ht = NULL; struct vhost_fdt_hash_chain *hc; if (config->fdt == MK_FALSE) { return close(sr->fd_file); } id = sr->vhost_fdt_id; hash = sr->vhost_fdt_hash; ht = mk_vhost_fdt_table_lookup(id, sr->host_conf); if (mk_unlikely(!ht)) { return close(sr->fd_file); } /* We got the hash table, now look around the chains array */ hc = mk_vhost_fdt_chain_lookup(hash, ht); if (hc) { /* Increment the readers and check if we should close */ hc->readers--; if (hc->readers == 0) { hc->fd = -1; hc->hash = 0; ht->av_slots++; return close(sr->fd_file); } else { return 0; } } return close(sr->fd_file); }
166,278
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebPageSerializerImpl::openTagToString(Element* element, SerializeDomParam* param) { bool needSkip; StringBuilder result; result.append(preActionBeforeSerializeOpenTag(element, param, &needSkip)); if (needSkip) return; result.append('<'); result.append(element->nodeName().lower()); AttributeCollection attributes = element->attributes(); AttributeCollection::iterator end = attributes.end(); for (AttributeCollection::iterator it = attributes.begin(); it != end; ++it) { result.append(' '); result.append(it->name().toString()); result.appendLiteral("=\""); if (!it->value().isEmpty()) { const String& attrValue = it->value(); const QualifiedName& attrName = it->name(); if (element->hasLegalLinkAttribute(attrName)) { if (attrValue.startsWith("javascript:", TextCaseInsensitive)) { result.append(attrValue); } else { WebLocalFrameImpl* subFrame = WebLocalFrameImpl::fromFrameOwnerElement(element); String completeURL = subFrame ? subFrame->frame()->document()->url() : param->document->completeURL(attrValue); if (m_localLinks.contains(completeURL)) { if (!param->directoryName.isEmpty()) { result.appendLiteral("./"); result.append(param->directoryName); result.append('/'); } result.append(m_localLinks.get(completeURL)); } else { result.append(completeURL); } } } else { if (param->isHTMLDocument) result.append(m_htmlEntities.convertEntitiesInString(attrValue)); else result.append(m_xmlEntities.convertEntitiesInString(attrValue)); } } result.append('\"'); } String addedContents = postActionAfterSerializeOpenTag(element, param); if (element->hasChildren() || param->haveAddedContentsBeforeEnd) result.append('>'); result.append(addedContents); saveHTMLContentToBuffer(result.toString(), param); } Commit Message: Make WebPageSerializerImpl to escape URL attribute values in result. This patch makes |WebPageSerializerImpl| to escape URL attribute values rather than directly output URL attribute values into result. BUG=542054 TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.URLAttributeValues Review URL: https://codereview.chromium.org/1398453005 Cr-Commit-Position: refs/heads/master@{#353712} CWE ID: CWE-20
void WebPageSerializerImpl::openTagToString(Element* element, SerializeDomParam* param) { bool needSkip; StringBuilder result; result.append(preActionBeforeSerializeOpenTag(element, param, &needSkip)); if (needSkip) return; result.append('<'); result.append(element->nodeName().lower()); AttributeCollection attributes = element->attributes(); AttributeCollection::iterator end = attributes.end(); for (AttributeCollection::iterator it = attributes.begin(); it != end; ++it) { result.append(' '); result.append(it->name().toString()); result.appendLiteral("=\""); if (!it->value().isEmpty()) { const String& attrValue = it->value(); const QualifiedName& attrName = it->name(); if (element->hasLegalLinkAttribute(attrName)) { if (attrValue.startsWith("javascript:", TextCaseInsensitive)) { result.append(m_htmlEntities.convertEntitiesInString(attrValue)); } else { WebLocalFrameImpl* subFrame = WebLocalFrameImpl::fromFrameOwnerElement(element); String completeURL = subFrame ? subFrame->frame()->document()->url() : param->document->completeURL(attrValue); if (m_localLinks.contains(completeURL)) { if (!param->directoryName.isEmpty()) { result.appendLiteral("./"); result.append(param->directoryName); result.append('/'); } result.append(m_htmlEntities.convertEntitiesInString(m_localLinks.get(completeURL))); } else { result.append(m_htmlEntities.convertEntitiesInString(completeURL)); } } } else { if (param->isHTMLDocument) result.append(m_htmlEntities.convertEntitiesInString(attrValue)); else result.append(m_xmlEntities.convertEntitiesInString(attrValue)); } } result.append('\"'); } String addedContents = postActionAfterSerializeOpenTag(element, param); if (element->hasChildren() || param->haveAddedContentsBeforeEnd) result.append('>'); result.append(addedContents); saveHTMLContentToBuffer(result.toString(), param); }
171,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __init big_key_crypto_init(void) { int ret = -EINVAL; /* init RNG */ big_key_rng = crypto_alloc_rng(big_key_rng_name, 0, 0); if (IS_ERR(big_key_rng)) { big_key_rng = NULL; return -EFAULT; } /* seed RNG */ ret = crypto_rng_reset(big_key_rng, NULL, crypto_rng_seedsize(big_key_rng)); if (ret) goto error; /* init block cipher */ big_key_skcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(big_key_skcipher)) { big_key_skcipher = NULL; ret = -EFAULT; goto error; } return 0; error: crypto_free_rng(big_key_rng); big_key_rng = NULL; return ret; } Commit Message: KEYS: Sort out big_key initialisation big_key has two separate initialisation functions, one that registers the key type and one that registers the crypto. If the key type fails to register, there's no problem if the crypto registers successfully because there's no way to reach the crypto except through the key type. However, if the key type registers successfully but the crypto does not, big_key_rng and big_key_blkcipher may end up set to NULL - but the code neither checks for this nor unregisters the big key key type. Furthermore, since the key type is registered before the crypto, it is theoretically possible for the kernel to try adding a big_key before the crypto is set up, leading to the same effect. Fix this by merging big_key_crypto_init() and big_key_init() and calling the resulting function late. If they're going to be encrypted, we shouldn't be creating big_keys before we have the facilities to do the encryption available. The key type registration is also moved after the crypto initialisation. The fix also includes message printing on failure. If the big_key type isn't correctly set up, simply doing: dd if=/dev/zero bs=4096 count=1 | keyctl padd big_key a @s ought to cause an oops. Fixes: 13100a72f40f5748a04017e0ab3df4cf27c809ef ('Security: Keys: Big keys stored encrypted') Signed-off-by: David Howells <[email protected]> cc: Peter Hlavaty <[email protected]> cc: Kirill Marinushkin <[email protected]> cc: Artem Savkov <[email protected]> cc: [email protected] Signed-off-by: James Morris <[email protected]> CWE ID: CWE-476
static int __init big_key_crypto_init(void) struct crypto_skcipher *cipher; struct crypto_rng *rng; int ret; rng = crypto_alloc_rng(big_key_rng_name, 0, 0); if (IS_ERR(rng)) { pr_err("Can't alloc rng: %ld\n", PTR_ERR(rng)); return PTR_ERR(rng); } big_key_rng = rng; /* seed RNG */ ret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng)); if (ret) { pr_err("Can't reset rng: %d\n", ret); goto error_rng; } /* init block cipher */ cipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC); if (IS_ERR(cipher)) { ret = PTR_ERR(cipher); pr_err("Can't alloc crypto: %d\n", ret); goto error_rng; } big_key_skcipher = cipher; ret = register_key_type(&key_type_big_key); if (ret < 0) { pr_err("Can't register type: %d\n", ret); goto error_cipher; } return 0; error_cipher: crypto_free_skcipher(big_key_skcipher); error_rng: crypto_free_rng(big_key_rng); return ret; }
166,893
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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()->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::MemoryHandler())); 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(false /* browser_only */))); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); 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] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { bool RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (session->restricted() && !IsFrameHostAllowedForRestrictedSessions()) return false; 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::MemoryHandler())); 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(false /* browser_only */))); session->AddHandler(base::WrapUnique(new protocol::TracingHandler( protocol::TracingHandler::Renderer, frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0, GetIOContext()))); 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 } return true; }
173,248
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bmp_validate(jas_stream_t *in) { int n; int i; uchar buf[2]; assert(JAS_STREAM_MAXPUTBACK >= 2); /* Read the first two characters that constitute the signature. */ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { return -1; } /* Put the characters read back onto the stream. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough characters? */ if (n < 2) { return -1; } /* Is the signature correct for the BMP format? */ if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) { return 0; } return -1; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
int bmp_validate(jas_stream_t *in) { int n; int i; jas_uchar buf[2]; assert(JAS_STREAM_MAXPUTBACK >= 2); /* Read the first two characters that constitute the signature. */ if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { return -1; } /* Put the characters read back onto the stream. */ for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } /* Did we read enough characters? */ if (n < 2) { return -1; } /* Is the signature correct for the BMP format? */ if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) { return 0; } return -1; }
168,714