instruction
stringclasses
1 value
input
stringlengths
90
9.3k
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: MediaGalleriesCustomBindings::MediaGalleriesCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetMediaFileSystemObject", base::Bind(&MediaGalleriesCustomBindings::GetMediaFileSystemObject, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
MediaGalleriesCustomBindings::MediaGalleriesCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetMediaFileSystemObject", "mediaGalleries", base::Bind(&MediaGalleriesCustomBindings::GetMediaFileSystemObject, base::Unretained(this))); }
173,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController* ExtensionTtsController::GetInstance() { return Singleton<ExtensionTtsController>::get(); } 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
ExtensionTtsController* ExtensionTtsController::GetInstance() {
170,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sanity_check_raw_super(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; unsigned int blocksize; if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) { f2fs_msg(sb, KERN_INFO, "Magic Mismatch, valid(0x%x) - read(0x%x)", F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic)); return 1; } /* Currently, support only 4KB page cache size */ if (F2FS_BLKSIZE != PAGE_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid page_cache_size (%lu), supports only 4KB\n", PAGE_SIZE); return 1; } /* Currently, support only 4KB block size */ blocksize = 1 << le32_to_cpu(raw_super->log_blocksize); if (blocksize != F2FS_BLKSIZE) { f2fs_msg(sb, KERN_INFO, "Invalid blocksize (%u), supports only 4KB\n", blocksize); return 1; } /* check log blocks per segment */ if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) { f2fs_msg(sb, KERN_INFO, "Invalid log blocks per segment (%u)\n", le32_to_cpu(raw_super->log_blocks_per_seg)); return 1; } /* Currently, support 512/1024/2048/4096 bytes sector size */ if (le32_to_cpu(raw_super->log_sectorsize) > F2FS_MAX_LOG_SECTOR_SIZE || le32_to_cpu(raw_super->log_sectorsize) < F2FS_MIN_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)", le32_to_cpu(raw_super->log_sectorsize)); return 1; } if (le32_to_cpu(raw_super->log_sectors_per_block) + le32_to_cpu(raw_super->log_sectorsize) != F2FS_MAX_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block(%u) log sectorsize(%u)", le32_to_cpu(raw_super->log_sectors_per_block), le32_to_cpu(raw_super->log_sectorsize)); return 1; } /* check reserved ino info */ if (le32_to_cpu(raw_super->node_ino) != 1 || le32_to_cpu(raw_super->meta_ino) != 2 || le32_to_cpu(raw_super->root_ino) != 3) { f2fs_msg(sb, KERN_INFO, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)", le32_to_cpu(raw_super->node_ino), le32_to_cpu(raw_super->meta_ino), le32_to_cpu(raw_super->root_ino)); return 1; } /* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */ if (sanity_check_area_boundary(sbi, bh)) return 1; return 0; } Commit Message: f2fs: sanity check segment count F2FS uses 4 bytes to represent block address. As a result, supported size of disk is 16 TB and it equals to 16 * 1024 * 1024 / 2 segments. Signed-off-by: Jin Qian <jinqian@google.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID:
static int sanity_check_raw_super(struct f2fs_sb_info *sbi, struct buffer_head *bh) { struct f2fs_super_block *raw_super = (struct f2fs_super_block *) (bh->b_data + F2FS_SUPER_OFFSET); struct super_block *sb = sbi->sb; unsigned int blocksize; if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) { f2fs_msg(sb, KERN_INFO, "Magic Mismatch, valid(0x%x) - read(0x%x)", F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic)); return 1; } /* Currently, support only 4KB page cache size */ if (F2FS_BLKSIZE != PAGE_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid page_cache_size (%lu), supports only 4KB\n", PAGE_SIZE); return 1; } /* Currently, support only 4KB block size */ blocksize = 1 << le32_to_cpu(raw_super->log_blocksize); if (blocksize != F2FS_BLKSIZE) { f2fs_msg(sb, KERN_INFO, "Invalid blocksize (%u), supports only 4KB\n", blocksize); return 1; } /* check log blocks per segment */ if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) { f2fs_msg(sb, KERN_INFO, "Invalid log blocks per segment (%u)\n", le32_to_cpu(raw_super->log_blocks_per_seg)); return 1; } /* Currently, support 512/1024/2048/4096 bytes sector size */ if (le32_to_cpu(raw_super->log_sectorsize) > F2FS_MAX_LOG_SECTOR_SIZE || le32_to_cpu(raw_super->log_sectorsize) < F2FS_MIN_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)", le32_to_cpu(raw_super->log_sectorsize)); return 1; } if (le32_to_cpu(raw_super->log_sectors_per_block) + le32_to_cpu(raw_super->log_sectorsize) != F2FS_MAX_LOG_SECTOR_SIZE) { f2fs_msg(sb, KERN_INFO, "Invalid log sectors per block(%u) log sectorsize(%u)", le32_to_cpu(raw_super->log_sectors_per_block), le32_to_cpu(raw_super->log_sectorsize)); return 1; } /* check reserved ino info */ if (le32_to_cpu(raw_super->node_ino) != 1 || le32_to_cpu(raw_super->meta_ino) != 2 || le32_to_cpu(raw_super->root_ino) != 3) { f2fs_msg(sb, KERN_INFO, "Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)", le32_to_cpu(raw_super->node_ino), le32_to_cpu(raw_super->meta_ino), le32_to_cpu(raw_super->root_ino)); return 1; } if (le32_to_cpu(raw_super->segment_count) > F2FS_MAX_SEGMENT) { f2fs_msg(sb, KERN_INFO, "Invalid segment count (%u)", le32_to_cpu(raw_super->segment_count)); return 1; } /* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */ if (sanity_check_area_boundary(sbi, bh)) return 1; return 0; }
168,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); }
167,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(snmp, __construct) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1, *a2; int a1_len, a2_len; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; long version = SNMP_DEFAULT_VERSION; int argc = ZEND_NUM_ARGS(); zend_error_handling error_handling; snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); switch(version) { case SNMP_VERSION_1: case SNMP_VERSION_2c: case SNMP_VERSION_3: break; default: zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC); return; } /* handle re-open of snmp session */ if (snmp_object->session) { netsnmp_session_free(&(snmp_object->session)); } if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) { return; } snmp_object->max_oids = 0; snmp_object->valueretrieval = SNMP_G(valueretrieval); snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); snmp_object->oid_increasing_check = TRUE; snmp_object->exceptions_enabled = 0; } Commit Message: CWE ID: CWE-416
PHP_METHOD(snmp, __construct) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1, *a2; int a1_len, a2_len; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; long version = SNMP_DEFAULT_VERSION; int argc = ZEND_NUM_ARGS(); zend_error_handling error_handling; snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); zend_replace_error_handling(EH_THROW, NULL, &error_handling TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "lss|ll", &version, &a1, &a1_len, &a2, &a2_len, &timeout, &retries) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } zend_restore_error_handling(&error_handling TSRMLS_CC); switch(version) { case SNMP_VERSION_1: case SNMP_VERSION_2c: case SNMP_VERSION_3: break; default: zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Unknown SNMP protocol version", 0 TSRMLS_CC); return; } /* handle re-open of snmp session */ if (snmp_object->session) { netsnmp_session_free(&(snmp_object->session)); } if (netsnmp_session_init(&(snmp_object->session), version, a1, a2, timeout, retries TSRMLS_CC)) { return; } snmp_object->max_oids = 0; snmp_object->valueretrieval = SNMP_G(valueretrieval); snmp_object->enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); snmp_object->oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); snmp_object->quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); snmp_object->oid_increasing_check = TRUE; snmp_object->exceptions_enabled = 0; }
164,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT(" << GLES2Util::GetStringQueryTarget(target) << ", " << id << ")"); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!capabilities_.sync_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return; } break; case GL_SAMPLES_PASSED_ARB: if (!capabilities_.occlusion_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!capabilities_.occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return; } break; case GL_TIME_ELAPSED_EXT: if (!capabilities_.timer_queries) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (capabilities_.major_version >= 3) break; FALLTHROUGH; default: SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return; } if (query_tracker_->GetCurrentQuery(target)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return; } if (id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return; } if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id"); return; } switch (target) { case GL_TIME_ELAPSED_EXT: if (!query_tracker_->SetDisjointSync(this)) { SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT", "buffer allocation failed"); return; } break; default: break; } if (query_tracker_->BeginQuery(id, target, this)) CheckGLError(); if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) { AllocateShadowCopiesForReadback(); } } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Reviewed-by: Geoff Lang <geofflang@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416
void GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { GPU_CLIENT_SINGLE_THREAD_CHECK(); GPU_CLIENT_LOG("[" << GetLogPrefix() << "] BeginQueryEXT(" << GLES2Util::GetStringQueryTarget(target) << ", " << id << ")"); switch (target) { case GL_COMMANDS_ISSUED_CHROMIUM: case GL_LATENCY_QUERY_CHROMIUM: case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: case GL_GET_ERROR_QUERY_CHROMIUM: case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: break; case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: case GL_COMMANDS_COMPLETED_CHROMIUM: if (!capabilities_.sync_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for commands completed queries"); return; } break; case GL_SAMPLES_PASSED_ARB: if (!capabilities_.occlusion_query) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for occlusion queries"); return; } break; case GL_ANY_SAMPLES_PASSED: case GL_ANY_SAMPLES_PASSED_CONSERVATIVE: if (!capabilities_.occlusion_query_boolean) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for boolean occlusion queries"); return; } break; case GL_TIME_ELAPSED_EXT: if (!capabilities_.timer_queries) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "not enabled for timing queries"); return; } break; case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: if (capabilities_.major_version >= 3) break; FALLTHROUGH; default: SetGLError(GL_INVALID_ENUM, "glBeginQueryEXT", "unknown query target"); return; } if (query_tracker_->GetCurrentQuery(target)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "query already in progress"); return; } if (id == 0) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "id is 0"); return; } if (!GetIdAllocator(IdNamespaces::kQueries)->InUse(id)) { SetGLError(GL_INVALID_OPERATION, "glBeginQueryEXT", "invalid id"); return; } switch (target) { case GL_TIME_ELAPSED_EXT: if (!query_tracker_->SetDisjointSync(this)) { SetGLError(GL_OUT_OF_MEMORY, "glBeginQueryEXT", "buffer allocation failed"); return; } break; default: break; } if (query_tracker_->BeginQuery(id, target, this)) CheckGLError(); if (target == GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM) { AllocateShadowCopiesForReadback(); } }
172,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; int ulen; if (!replay_esn || !rp) return 0; up = nla_data(rp); ulen = xfrm_replay_state_esn_len(up); if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen) return -EINVAL; if (up->replay_window > up->bmp_len * sizeof(__u32) * 8) return -EINVAL; return 0; } Commit Message: xfrm_user: validate XFRM_MSG_NEWAE incoming ESN size harder Kees Cook has pointed out that xfrm_replay_state_esn_len() is subject to wrapping issues. To ensure we are correctly ensuring that the two ESN structures are the same size compare both the overall size as reported by xfrm_replay_state_esn_len() and the internal length are the same. CVE-2017-7184 Signed-off-by: Andy Whitcroft <apw@canonical.com> Acked-by: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; int ulen; if (!replay_esn || !rp) return 0; up = nla_data(rp); ulen = xfrm_replay_state_esn_len(up); /* Check the overall length and the internal bitmap length to avoid * potential overflow. */ if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen || replay_esn->bmp_len != up->bmp_len) return -EINVAL; if (up->replay_window > up->bmp_len * sizeof(__u32) * 8) return -EINVAL; return 0; }
168,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; } Commit Message: avformat/asfdec: Fix DoS in asf_build_simple_index() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-399
static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (avio_feof(s->pb)) { ret = AVERROR_INVALIDDATA; goto end; } if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: avio_seek(s->pb, current_pos, SEEK_SET); return ret; }
167,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void btsnoop_write(const void *data, size_t length) { if (logfile_fd != INVALID_FD) write(logfile_fd, data, length); btsnoop_net_write(data, length); } 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 btsnoop_write(const void *data, size_t length) { if (logfile_fd != INVALID_FD) TEMP_FAILURE_RETRY(write(logfile_fd, data, length)); btsnoop_net_write(data, length); }
173,472
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cues::PreloadCuePoint( long& cue_points_size, long long pos) const { assert(m_count == 0); if (m_preload_count >= cue_points_size) { const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size; CuePoint** const qq = new CuePoint*[n]; CuePoint** q = qq; //beginning of target CuePoint** p = m_cue_points; //beginning of source CuePoint** const pp = p + m_preload_count; //end of source while (p != pp) *q++ = *p++; delete[] m_cue_points; m_cue_points = qq; cue_points_size = n; } CuePoint* const pCP = new CuePoint(m_preload_count, pos); m_cue_points[m_preload_count++] = pCP; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Cues::PreloadCuePoint( continue; } assert(m_preload_count > 0); CuePoint* const pCP = m_cue_points[m_count]; assert(pCP); assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) return false; pCP->Load(pReader); ++m_count; --m_preload_count; m_pos += size; // consume payload assert(m_pos <= stop); return true; // yes, we loaded a cue point } // return (m_pos < stop); return false; // no, we did not load a cue point }
174,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ecryptfs_privileged_open(struct file **lower_file, struct dentry *lower_dentry, struct vfsmount *lower_mnt, const struct cred *cred) { struct ecryptfs_open_req req; int flags = O_LARGEFILE; int rc = 0; init_completion(&req.done); req.lower_file = lower_file; req.path.dentry = lower_dentry; req.path.mnt = lower_mnt; /* Corresponding dput() and mntput() are done when the * lower file is fput() when all eCryptfs files for the inode are * released. */ flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR; (*lower_file) = dentry_open(&req.path, flags, cred); if (!IS_ERR(*lower_file)) goto out; if ((flags & O_ACCMODE) == O_RDONLY) { rc = PTR_ERR((*lower_file)); goto out; } mutex_lock(&ecryptfs_kthread_ctl.mux); if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) { rc = -EIO; mutex_unlock(&ecryptfs_kthread_ctl.mux); printk(KERN_ERR "%s: We are in the middle of shutting down; " "aborting privileged request to open lower file\n", __func__); goto out; } list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list); mutex_unlock(&ecryptfs_kthread_ctl.mux); wake_up(&ecryptfs_kthread_ctl.wait); wait_for_completion(&req.done); if (IS_ERR(*lower_file)) rc = PTR_ERR(*lower_file); out: return rc; } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <jannh@google.com>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top CWE ID: CWE-119
int ecryptfs_privileged_open(struct file **lower_file, struct dentry *lower_dentry, struct vfsmount *lower_mnt, const struct cred *cred) { struct ecryptfs_open_req req; int flags = O_LARGEFILE; int rc = 0; init_completion(&req.done); req.lower_file = lower_file; req.path.dentry = lower_dentry; req.path.mnt = lower_mnt; /* Corresponding dput() and mntput() are done when the * lower file is fput() when all eCryptfs files for the inode are * released. */ flags |= IS_RDONLY(d_inode(lower_dentry)) ? O_RDONLY : O_RDWR; (*lower_file) = dentry_open(&req.path, flags, cred); if (!IS_ERR(*lower_file)) goto have_file; if ((flags & O_ACCMODE) == O_RDONLY) { rc = PTR_ERR((*lower_file)); goto out; } mutex_lock(&ecryptfs_kthread_ctl.mux); if (ecryptfs_kthread_ctl.flags & ECRYPTFS_KTHREAD_ZOMBIE) { rc = -EIO; mutex_unlock(&ecryptfs_kthread_ctl.mux); printk(KERN_ERR "%s: We are in the middle of shutting down; " "aborting privileged request to open lower file\n", __func__); goto out; } list_add_tail(&req.kthread_ctl_list, &ecryptfs_kthread_ctl.req_list); mutex_unlock(&ecryptfs_kthread_ctl.mux); wake_up(&ecryptfs_kthread_ctl.wait); wait_for_completion(&req.done); if (IS_ERR(*lower_file)) { rc = PTR_ERR(*lower_file); goto out; } have_file: if ((*lower_file)->f_op->mmap == NULL) { fput(*lower_file); *lower_file = NULL; rc = -EMEDIUMTYPE; } out: return rc; }
167,443
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; } Commit Message: Change ECDSA signing to use blinding. CWE ID: CWE-200
static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; }
169,194
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseDocTypeDecl : no DOCTYPE name !\n"); } ctxt->intSubName = name; SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = xmlParseExternalID(ctxt, &ExternalID, 1); if ((URI != NULL) || (ExternalID != NULL)) { ctxt->hasExternalSubset = 1; } ctxt->extSubURI = URI; ctxt->extSubSystem = ExternalID; SKIP_BLANKS; /* * Create and update the internal subset. */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); /* * Is there any internal subset declarations ? * they are handled separately in xmlParseInternalSubset() */ if (RAW == '[') return; /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; } 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
xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { const xmlChar *name = NULL; xmlChar *ExternalID = NULL; xmlChar *URI = NULL; /* * We know that '<!DOCTYPE' has been detected. */ SKIP(9); SKIP_BLANKS; /* * Parse the DOCTYPE name. */ name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseDocTypeDecl : no DOCTYPE name !\n"); } ctxt->intSubName = name; SKIP_BLANKS; /* * Check for SystemID and ExternalID */ URI = xmlParseExternalID(ctxt, &ExternalID, 1); if ((URI != NULL) || (ExternalID != NULL)) { ctxt->hasExternalSubset = 1; } ctxt->extSubURI = URI; ctxt->extSubSystem = ExternalID; SKIP_BLANKS; /* * Create and update the internal subset. */ if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); if (ctxt->instate == XML_PARSER_EOF) return; /* * Is there any internal subset declarations ? * they are handled separately in xmlParseInternalSubset() */ if (RAW == '[') return; /* * We should be at the end of the DOCTYPE declaration. */ if (RAW != '>') { xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL); } NEXT; }
171,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InitChromeDriverLogging(const CommandLine& command_line) { bool success = InitLogging( FILE_PATH_LITERAL("chromedriver.log"), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::LOCK_LOG_FILE, logging::DELETE_OLD_LOG_FILE, logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); if (!success) { PLOG(ERROR) << "Unable to initialize logging"; } logging::SetLogItems(false, // enable_process_id false, // enable_thread_id true, // enable_timestamp false); // enable_tickcount if (command_line.HasSwitch(switches::kLoggingLevel)) { std::string log_level = command_line.GetSwitchValueASCII( switches::kLoggingLevel); int level = 0; if (base::StringToInt(log_level, &level)) { logging::SetMinLogLevel(level); } else { LOG(WARNING) << "Bad log level: " << log_level; } } } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void InitChromeDriverLogging(const CommandLine& command_line) {
170,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GestureProviderAura::OnGestureEvent( const GestureEventData& gesture) { GestureEventDetails details = gesture.details; if (gesture.type == ET_GESTURE_TAP) { int tap_count = 1; if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture)) tap_count = 1 + (previous_tap_->details.tap_count() % 3); details.set_tap_count(tap_count); if (!previous_tap_) previous_tap_.reset(new GestureEventData(gesture)); else *previous_tap_ = gesture; previous_tap_->details = details; } else if (gesture.type == ET_GESTURE_TAP_CANCEL) { previous_tap_.reset(); } scoped_ptr<ui::GestureEvent> event( new ui::GestureEvent(gesture.type, gesture.x, gesture.y, last_touch_event_flags_, gesture.time - base::TimeTicks(), details, 1 << gesture.motion_event_id)); if (!handling_event_) { client_->OnGestureEvent(event.get()); } else { pending_gestures_.push_back(event.release()); } } 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:
void GestureProviderAura::OnGestureEvent( const GestureEventData& gesture) { GestureEventDetails details = gesture.details; if (gesture.type == ET_GESTURE_TAP) { int tap_count = 1; if (previous_tap_ && IsConsideredDoubleTap(*previous_tap_, gesture)) tap_count = 1 + (previous_tap_->details.tap_count() % 3); details.set_tap_count(tap_count); if (!previous_tap_) previous_tap_.reset(new GestureEventData(gesture)); else *previous_tap_ = gesture; previous_tap_->details = details; } else if (gesture.type == ET_GESTURE_TAP_CANCEL) { previous_tap_.reset(); } scoped_ptr<ui::GestureEvent> event( new ui::GestureEvent(gesture.type, gesture.x, gesture.y, last_touch_event_flags_, gesture.time - base::TimeTicks(), details, 1 << gesture.motion_event_id)); ui::LatencyInfo* gesture_latency = event->latency(); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_UI_COMPONENT); gesture_latency->CopyLatencyFrom( last_touch_event_latency_info_, ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT); if (!handling_event_) { client_->OnGestureEvent(event.get()); } else { pending_gestures_.push_back(event.release()); } }
171,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } Commit Message: Fix write heap buffer overflow in opj_mqc_byteout(). Discovered by Ke Liu of Tencent's Xuanwu LAB (#835) CWE ID: CWE-119
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }
168,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateTrue( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_True; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateTrue( void )
167,280
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address) { /* VPD - all zeros */ return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00, "s256"); } Commit Message: CWE ID: CWE-20
size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address) { /* VPD - all zeros */ return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00, "*s256"); }
164,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } if (texture_id_in_layer_) { ImageTransportFactoryAndroid::GetInstance()->DeleteTexture( texture_id_in_layer_); } }
171,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto) { switch (proto) { case DECODE_TUNNEL_PPP: return DecodePPP(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV4: return DecodeIPV4(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV6: return DecodeIPV6(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_VLAN: return DecodeVLAN(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ETHERNET: return DecodeEthernet(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ERSPAN: return DecodeERSPAN(tv, dtv, p, pkt, len, pq); default: SCLogInfo("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto); break; } return TM_ECODE_OK; } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
int DecodeTunnel(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint32_t len, PacketQueue *pq, enum DecodeTunnelProto proto) { switch (proto) { case DECODE_TUNNEL_PPP: return DecodePPP(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV4: return DecodeIPV4(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_IPV6: case DECODE_TUNNEL_IPV6_TEREDO: return DecodeIPV6(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_VLAN: return DecodeVLAN(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ETHERNET: return DecodeEthernet(tv, dtv, p, pkt, len, pq); case DECODE_TUNNEL_ERSPAN: return DecodeERSPAN(tv, dtv, p, pkt, len, pq); default: SCLogDebug("FIXME: DecodeTunnel: protocol %" PRIu32 " not supported.", proto); break; } return TM_ECODE_OK; }
169,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void toggle_os_keylockstates(int fd, int changedlockstates) { BTIF_TRACE_EVENT("%s: fd = %d, changedlockstates = 0x%x", __FUNCTION__, fd, changedlockstates); UINT8 hidreport[9]; int reportIndex; memset(hidreport,0,9); hidreport[0]=1; reportIndex=4; if (changedlockstates & BTIF_HH_KEYSTATE_MASK_CAPSLOCK) { BTIF_TRACE_DEBUG("%s Setting CAPSLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_CAPSLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_NUMLOCK) { BTIF_TRACE_DEBUG("%s Setting NUMLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_NUMLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_SCROLLLOCK) { BTIF_TRACE_DEBUG("%s Setting SCROLLLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8) HID_REPORT_SCROLLLOCK; } BTIF_TRACE_DEBUG("Writing hidreport #1 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); usleep(200000); memset(hidreport,0,9); hidreport[0]=1; BTIF_TRACE_DEBUG("Writing hidreport #2 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x ", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); } 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 toggle_os_keylockstates(int fd, int changedlockstates) { BTIF_TRACE_EVENT("%s: fd = %d, changedlockstates = 0x%x", __FUNCTION__, fd, changedlockstates); UINT8 hidreport[9]; int reportIndex; memset(hidreport,0,9); hidreport[0]=1; reportIndex=4; if (changedlockstates & BTIF_HH_KEYSTATE_MASK_CAPSLOCK) { BTIF_TRACE_DEBUG("%s Setting CAPSLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_CAPSLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_NUMLOCK) { BTIF_TRACE_DEBUG("%s Setting NUMLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8)HID_REPORT_NUMLOCK; } if (changedlockstates & BTIF_HH_KEYSTATE_MASK_SCROLLLOCK) { BTIF_TRACE_DEBUG("%s Setting SCROLLLOCK", __FUNCTION__); hidreport[reportIndex++] = (UINT8) HID_REPORT_SCROLLLOCK; } BTIF_TRACE_DEBUG("Writing hidreport #1 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); TEMP_FAILURE_RETRY(usleep(200000)); memset(hidreport,0,9); hidreport[0]=1; BTIF_TRACE_DEBUG("Writing hidreport #2 to os: "\ "%s: %x %x %x", __FUNCTION__, hidreport[0], hidreport[1], hidreport[2]); BTIF_TRACE_DEBUG("%s: %x %x %x", __FUNCTION__, hidreport[3], hidreport[4], hidreport[5]); BTIF_TRACE_DEBUG("%s: %x %x %x ", __FUNCTION__, hidreport[6], hidreport[7], hidreport[8]); bta_hh_co_write(fd , hidreport, sizeof(hidreport)); }
173,438
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *fin, *fout; FILE *fpin, *fpout; uint8_t *inbuf, *outbuf; uint8_t *inbuf_u, *outbuf_u; uint8_t *inbuf_v, *outbuf_v; int f, frames; int width, height, target_width, target_height; if (argc < 5) { printf("Incorrect parameters:\n"); usage(argv[0]); return 1; } fin = argv[1]; fout = argv[4]; if (!parse_dim(argv[2], &width, &height)) { printf("Incorrect parameters: %s\n", argv[2]); usage(argv[0]); return 1; } if (!parse_dim(argv[3], &target_width, &target_height)) { printf("Incorrect parameters: %s\n", argv[3]); usage(argv[0]); return 1; } fpin = fopen(fin, "rb"); if (fpin == NULL) { printf("Can't open file %s to read\n", fin); usage(argv[0]); return 1; } fpout = fopen(fout, "wb"); if (fpout == NULL) { printf("Can't open file %s to write\n", fout); usage(argv[0]); return 1; } if (argc >= 6) frames = atoi(argv[5]); else frames = INT_MAX; printf("Input size: %dx%d\n", width, height); printf("Target size: %dx%d, Frames: ", target_width, target_height); if (frames == INT_MAX) printf("All\n"); else printf("%d\n", frames); inbuf = (uint8_t*)malloc(width * height * 3 / 2); outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2); inbuf_u = inbuf + width * height; inbuf_v = inbuf_u + width * height / 4; outbuf_u = outbuf + target_width * target_height; outbuf_v = outbuf_u + target_width * target_height / 4; f = 0; while (f < frames) { if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1) break; vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2, height, width, outbuf, target_width, outbuf_u, outbuf_v, target_width / 2, target_height, target_width); fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout); f++; } printf("%d frames processed\n", f); fclose(fpin); fclose(fpout); free(inbuf); free(outbuf); return 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int main(int argc, char *argv[]) { char *fin, *fout; FILE *fpin, *fpout; uint8_t *inbuf, *outbuf; uint8_t *inbuf_u, *outbuf_u; uint8_t *inbuf_v, *outbuf_v; int f, frames; int width, height, target_width, target_height; exec_name = argv[0]; if (argc < 5) { printf("Incorrect parameters:\n"); usage(); return 1; } fin = argv[1]; fout = argv[4]; if (!parse_dim(argv[2], &width, &height)) { printf("Incorrect parameters: %s\n", argv[2]); usage(); return 1; } if (!parse_dim(argv[3], &target_width, &target_height)) { printf("Incorrect parameters: %s\n", argv[3]); usage(); return 1; } fpin = fopen(fin, "rb"); if (fpin == NULL) { printf("Can't open file %s to read\n", fin); usage(); return 1; } fpout = fopen(fout, "wb"); if (fpout == NULL) { printf("Can't open file %s to write\n", fout); usage(); return 1; } if (argc >= 6) frames = atoi(argv[5]); else frames = INT_MAX; printf("Input size: %dx%d\n", width, height); printf("Target size: %dx%d, Frames: ", target_width, target_height); if (frames == INT_MAX) printf("All\n"); else printf("%d\n", frames); inbuf = (uint8_t*)malloc(width * height * 3 / 2); outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2); inbuf_u = inbuf + width * height; inbuf_v = inbuf_u + width * height / 4; outbuf_u = outbuf + target_width * target_height; outbuf_v = outbuf_u + target_width * target_height / 4; f = 0; while (f < frames) { if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1) break; vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2, height, width, outbuf, target_width, outbuf_u, outbuf_v, target_width / 2, target_height, target_width); fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout); f++; } printf("%d frames processed\n", f); fclose(fpin); fclose(fpout); free(inbuf); free(outbuf); return 0; }
174,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk))) || (write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; } Commit Message: issue #27, do not overwrite stack on corrupt RF64 file CWE ID: CWE-119
int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { int do_rf64 = 0, write_junk = 1, table_length = 0; ChunkHeader ds64hdr, datahdr, fmthdr; RiffChunkHeader riffhdr; DS64Chunk ds64_chunk; CS64Chunk cs64_chunk; JunkChunk junkchunk; WaveHeader wavhdr; uint32_t bcount; int64_t total_data_bytes, total_riff_bytes; int num_channels = WavpackGetNumChannels (wpc); int32_t channel_mask = WavpackGetChannelMask (wpc); int32_t sample_rate = WavpackGetSampleRate (wpc); int bytes_per_sample = WavpackGetBytesPerSample (wpc); int bits_per_sample = WavpackGetBitsPerSample (wpc); int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; int wavhdrsize = 16; if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { error_line ("can't create valid RIFF wav header for non-normalized floating data!"); return FALSE; } if (total_samples == -1) total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); total_data_bytes = total_samples * bytes_per_sample * num_channels; if (total_data_bytes > 0xff000000) { if (debug_logging_mode) error_line ("total_data_bytes = %lld, so rf64", total_data_bytes); write_junk = 0; do_rf64 = 1; } else if (debug_logging_mode) error_line ("total_data_bytes = %lld, so riff", total_data_bytes); CLEAR (wavhdr); wavhdr.FormatTag = format; wavhdr.NumChannels = num_channels; wavhdr.SampleRate = sample_rate; wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; wavhdr.BlockAlign = bytes_per_sample * num_channels; wavhdr.BitsPerSample = bits_per_sample; if (num_channels > 2 || channel_mask != 0x5 - num_channels) { wavhdrsize = sizeof (wavhdr); wavhdr.cbSize = 22; wavhdr.ValidBitsPerSample = bits_per_sample; wavhdr.SubFormat = format; wavhdr.ChannelMask = channel_mask; wavhdr.FormatTag = 0xfffe; wavhdr.BitsPerSample = bytes_per_sample * 8; wavhdr.GUID [4] = 0x10; wavhdr.GUID [6] = 0x80; wavhdr.GUID [9] = 0xaa; wavhdr.GUID [11] = 0x38; wavhdr.GUID [12] = 0x9b; wavhdr.GUID [13] = 0x71; } strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID)); strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType)); total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); total_riff_bytes += table_length * sizeof (CS64Chunk); if (write_junk) total_riff_bytes += sizeof (junkchunk); strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID)); strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID)); fmthdr.ckSize = wavhdrsize; if (write_junk) { CLEAR (junkchunk); strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID)); junkchunk.ckSize = sizeof (junkchunk) - 8; WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); } if (do_rf64) { strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID)); ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); CLEAR (ds64_chunk); ds64_chunk.riffSize64 = total_riff_bytes; ds64_chunk.dataSize64 = total_data_bytes; ds64_chunk.sampleCount64 = total_samples; ds64_chunk.tableLength = table_length; riffhdr.ckSize = (uint32_t) -1; datahdr.ckSize = (uint32_t) -1; WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); } else { riffhdr.ckSize = (uint32_t) total_riff_bytes; datahdr.ckSize = (uint32_t) total_data_bytes; } // this "table" is just a dummy placeholder for testing (normally not written) if (table_length) { strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID)); cs64_chunk.chunkSize64 = 12345678; WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); } WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } // again, this is normally not written except for testing while (table_length--) if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { error_line ("can't write .WAV data, disk probably full!"); return FALSE; } return TRUE; }
169,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned long long Chapters::Atom::GetUID() const { return m_uid; } 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
unsigned long long Chapters::Atom::GetUID() const const char* SegmentInfo::GetWritingAppAsUTF8() const { return m_pWritingAppAsUTF8; }
174,376
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain == 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; } Commit Message: Avoid potentially dangerous signed to unsigned conversion We make sure to never pass a negative `rlen` as size to memcpy(). See also <https://bugs.php.net/bug.php?id=73280>. Patch provided by Emmanuel Law. CWE ID: CWE-119
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain <= 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; }
168,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uhid_event(btif_hh_device_t *p_dev) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); if(!p_dev) { APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__) return -1; } ret = read(p_dev->fd, &ev, sizeof(ev)); if (ret == 0) { APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__, strerror(errno)); return -EFAULT; } else if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__, strerror(errno)); return -errno; } else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) { if (ret < (ssize_t)sizeof(ev)) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu", __FUNCTION__, ret, sizeof(ev.type)); return -EFAULT; } } switch (ev.type) { case UHID_START: APPL_TRACE_DEBUG("UHID_START from uhid-dev\n"); p_dev->ready_for_data = TRUE; break; case UHID_STOP: APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OPEN: APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OUTPUT: if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu", __FUNCTION__, ret, sizeof(ev.type) + sizeof(ev.u.output)); return -EFAULT; } APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d" ,ev.u.output.rtype, ev.u.output.size); if(ev.u.output.rtype == UHID_FEATURE_REPORT) btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT, ev.u.output.size, ev.u.output.data); else if(ev.u.output.rtype == UHID_OUTPUT_REPORT) btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT, ev.u.output.size, ev.u.output.data); else btif_hh_setreport(p_dev, BTHH_INPUT_REPORT, ev.u.output.size, ev.u.output.data); break; case UHID_OUTPUT_EV: APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n"); break; case UHID_FEATURE: APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n"); break; case UHID_FEATURE_ANSWER: APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n"); break; default: APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type); } return 0; } 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 int uhid_event(btif_hh_device_t *p_dev) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); if(!p_dev) { APPL_TRACE_ERROR("%s: Device not found",__FUNCTION__) return -1; } ret = TEMP_FAILURE_RETRY(read(p_dev->fd, &ev, sizeof(ev))); if (ret == 0) { APPL_TRACE_ERROR("%s: Read HUP on uhid-cdev %s", __FUNCTION__, strerror(errno)); return -EFAULT; } else if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot read uhid-cdev: %s", __FUNCTION__, strerror(errno)); return -errno; } else if ((ev.type == UHID_OUTPUT) || (ev.type==UHID_OUTPUT_EV)) { if (ret < (ssize_t)sizeof(ev)) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %ld != %lu", __FUNCTION__, ret, sizeof(ev.type)); return -EFAULT; } } switch (ev.type) { case UHID_START: APPL_TRACE_DEBUG("UHID_START from uhid-dev\n"); p_dev->ready_for_data = TRUE; break; case UHID_STOP: APPL_TRACE_DEBUG("UHID_STOP from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OPEN: APPL_TRACE_DEBUG("UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: APPL_TRACE_DEBUG("UHID_CLOSE from uhid-dev\n"); p_dev->ready_for_data = FALSE; break; case UHID_OUTPUT: if (ret < (ssize_t)(sizeof(ev.type) + sizeof(ev.u.output))) { APPL_TRACE_ERROR("%s: Invalid size read from uhid-dev: %zd < %zu", __FUNCTION__, ret, sizeof(ev.type) + sizeof(ev.u.output)); return -EFAULT; } APPL_TRACE_DEBUG("UHID_OUTPUT: Report type = %d, report_size = %d" ,ev.u.output.rtype, ev.u.output.size); if(ev.u.output.rtype == UHID_FEATURE_REPORT) btif_hh_setreport(p_dev, BTHH_FEATURE_REPORT, ev.u.output.size, ev.u.output.data); else if(ev.u.output.rtype == UHID_OUTPUT_REPORT) btif_hh_setreport(p_dev, BTHH_OUTPUT_REPORT, ev.u.output.size, ev.u.output.data); else btif_hh_setreport(p_dev, BTHH_INPUT_REPORT, ev.u.output.size, ev.u.output.data); break; case UHID_OUTPUT_EV: APPL_TRACE_DEBUG("UHID_OUTPUT_EV from uhid-dev\n"); break; case UHID_FEATURE: APPL_TRACE_DEBUG("UHID_FEATURE from uhid-dev\n"); break; case UHID_FEATURE_ANSWER: APPL_TRACE_DEBUG("UHID_FEATURE_ANSWER from uhid-dev\n"); break; default: APPL_TRACE_DEBUG("Invalid event from uhid-dev: %u\n", ev.type); } return 0; }
173,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_size = size; return true; } 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 Chapters::Atom::ExpandDisplaysArray()
174,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HandleCompleteLogin(const base::ListValue* args) { #if defined(OS_CHROMEOS) oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui())); oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher( oauth2_delegate_.get(), profile_->GetRequestContext())); oauth2_token_fetcher_->StartExchangeFromCookies(); #elif !defined(OS_ANDROID) const base::DictionaryValue* dict = NULL; string16 email; string16 password; if (!args->GetDictionary(0, &dict) || !dict || !dict->GetString("email", &email) || !dict->GetString("password", &password)) { NOTREACHED(); return; } new OneClickSigninSyncStarter( profile_, NULL, "0" /* session_index 0 for the default user */, UTF16ToASCII(email), UTF16ToASCII(password), OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, true /* force_same_tab_navigation */, OneClickSigninSyncStarter::NO_CONFIRMATION); web_ui()->CallJavascriptFunction("inline.login.closeDialog"); #endif } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void HandleCompleteLogin(const base::ListValue* args) { #if defined(OS_CHROMEOS) oauth2_delegate_.reset(new InlineLoginUIOAuth2Delegate(web_ui())); oauth2_token_fetcher_.reset(new chromeos::OAuth2TokenFetcher( oauth2_delegate_.get(), profile_->GetRequestContext())); oauth2_token_fetcher_->StartExchangeFromCookies(); #elif !defined(OS_ANDROID) const base::DictionaryValue* dict = NULL; string16 email; string16 password; if (!args->GetDictionary(0, &dict) || !dict || !dict->GetString("email", &email) || !dict->GetString("password", &password)) { NOTREACHED(); return; } new OneClickSigninSyncStarter( profile_, NULL, "0" /* session_index 0 for the default user */, UTF16ToASCII(email), UTF16ToASCII(password), OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS, true /* force_same_tab_navigation */, OneClickSigninSyncStarter::NO_CONFIRMATION, SyncPromoUI::SOURCE_UNKNOWN); web_ui()->CallJavascriptFunction("inline.login.closeDialog"); #endif }
171,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: s4u_identify_user(krb5_context context, krb5_creds *in_creds, krb5_data *subject_cert, krb5_principal *canon_user) { krb5_error_code code; krb5_preauthtype ptypes[1] = { KRB5_PADATA_S4U_X509_USER }; krb5_creds creds; int use_master = 0; krb5_get_init_creds_opt *opts = NULL; krb5_principal_data client; krb5_s4u_userid userid; *canon_user = NULL; if (in_creds->client == NULL && subject_cert == NULL) { return EINVAL; } if (in_creds->client != NULL && in_creds->client->type != KRB5_NT_ENTERPRISE_PRINCIPAL) { int anonymous; anonymous = krb5_principal_compare(context, in_creds->client, krb5_anonymous_principal()); return krb5_copy_principal(context, anonymous ? in_creds->server : in_creds->client, canon_user); } memset(&creds, 0, sizeof(creds)); memset(&userid, 0, sizeof(userid)); if (subject_cert != NULL) userid.subject_cert = *subject_cert; code = krb5_get_init_creds_opt_alloc(context, &opts); if (code != 0) goto cleanup; krb5_get_init_creds_opt_set_tkt_life(opts, 15); krb5_get_init_creds_opt_set_renew_life(opts, 0); krb5_get_init_creds_opt_set_forwardable(opts, 0); krb5_get_init_creds_opt_set_proxiable(opts, 0); krb5_get_init_creds_opt_set_canonicalize(opts, 1); krb5_get_init_creds_opt_set_preauth_list(opts, ptypes, 1); if (in_creds->client != NULL) { client = *in_creds->client; client.realm = in_creds->server->realm; } else { client.magic = KV5M_PRINCIPAL; client.realm = in_creds->server->realm; /* should this be NULL, empty or a fixed string? XXX */ client.data = NULL; client.length = 0; client.type = KRB5_NT_ENTERPRISE_PRINCIPAL; } code = k5_get_init_creds(context, &creds, &client, NULL, NULL, 0, NULL, opts, krb5_get_as_key_noop, &userid, &use_master, NULL); if (code == 0 || code == KRB5_PREAUTH_FAILED) { *canon_user = userid.user; userid.user = NULL; code = 0; } cleanup: krb5_free_cred_contents(context, &creds); if (opts != NULL) krb5_get_init_creds_opt_free(context, opts); if (userid.user != NULL) krb5_free_principal(context, userid.user); return code; } Commit Message: Ignore password attributes for S4U2Self requests For consistency with Windows KDCs, allow protocol transition to work even if the password has expired or needs changing. Also, when looking up an enterprise principal with an AS request, treat ERR_KEY_EXP as confirmation that the client is present in the realm. [ghudson@mit.edu: added comment in kdc_process_s4u2self_req(); edited commit message] ticket: 8763 (new) tags: pullup target_version: 1.17 CWE ID: CWE-617
s4u_identify_user(krb5_context context, krb5_creds *in_creds, krb5_data *subject_cert, krb5_principal *canon_user) { krb5_error_code code; krb5_preauthtype ptypes[1] = { KRB5_PADATA_S4U_X509_USER }; krb5_creds creds; int use_master = 0; krb5_get_init_creds_opt *opts = NULL; krb5_principal_data client; krb5_s4u_userid userid; *canon_user = NULL; if (in_creds->client == NULL && subject_cert == NULL) { return EINVAL; } if (in_creds->client != NULL && in_creds->client->type != KRB5_NT_ENTERPRISE_PRINCIPAL) { int anonymous; anonymous = krb5_principal_compare(context, in_creds->client, krb5_anonymous_principal()); return krb5_copy_principal(context, anonymous ? in_creds->server : in_creds->client, canon_user); } memset(&creds, 0, sizeof(creds)); memset(&userid, 0, sizeof(userid)); if (subject_cert != NULL) userid.subject_cert = *subject_cert; code = krb5_get_init_creds_opt_alloc(context, &opts); if (code != 0) goto cleanup; krb5_get_init_creds_opt_set_tkt_life(opts, 15); krb5_get_init_creds_opt_set_renew_life(opts, 0); krb5_get_init_creds_opt_set_forwardable(opts, 0); krb5_get_init_creds_opt_set_proxiable(opts, 0); krb5_get_init_creds_opt_set_canonicalize(opts, 1); krb5_get_init_creds_opt_set_preauth_list(opts, ptypes, 1); if (in_creds->client != NULL) { client = *in_creds->client; client.realm = in_creds->server->realm; } else { client.magic = KV5M_PRINCIPAL; client.realm = in_creds->server->realm; /* should this be NULL, empty or a fixed string? XXX */ client.data = NULL; client.length = 0; client.type = KRB5_NT_ENTERPRISE_PRINCIPAL; } code = k5_get_init_creds(context, &creds, &client, NULL, NULL, 0, NULL, opts, krb5_get_as_key_noop, &userid, &use_master, NULL); if (!code || code == KRB5_PREAUTH_FAILED || code == KRB5KDC_ERR_KEY_EXP) { *canon_user = userid.user; userid.user = NULL; code = 0; } cleanup: krb5_free_cred_contents(context, &creds); if (opts != NULL) krb5_get_init_creds_opt_free(context, opts); if (userid.user != NULL) krb5_free_principal(context, userid.user); return code; }
168,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 init_ext2_fs(void) { int err = init_ext2_xattr(); if (err) return err; err = init_inodecache(); if (err) goto out1; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); out1: exit_ext2_xattr(); return err; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
static int __init init_ext2_fs(void) { int err; err = init_inodecache(); if (err) return err; err = register_filesystem(&ext2_fs_type); if (err) goto out; return 0; out: destroy_inodecache(); return err; }
169,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION( locale_get_keywords ) { UEnumeration* e = NULL; UErrorCode status = U_ZERO_ERROR; const char* kw_key = NULL; int32_t kw_key_len = 0; const char* loc_name = NULL; int loc_name_len = 0; /* ICU expects the buffer to be allocated before calling the function and so the buffer size has been explicitly specified ICU uloc.h #define ULOC_KEYWORD_AND_VALUES_CAPACITY 100 hence the kw_value buffer size is 100 */ char* kw_value = NULL; int32_t kw_value_len = 100; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "s", &loc_name, &loc_name_len ) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } if(loc_name_len == 0) { loc_name = intl_locale_get_default(TSRMLS_C); } /* Get the keywords */ e = uloc_openKeywords( loc_name, &status ); if( e != NULL ) { /* Traverse it, filling the return array. */ array_init( return_value ); while( ( kw_key = uenum_next( e, &kw_key_len, &status ) ) != NULL ){ kw_value = ecalloc( 1 , kw_value_len ); /* Get the keyword value for each keyword */ kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len , &status ); if (status == U_BUFFER_OVERFLOW_ERROR) { status = U_ZERO_ERROR; kw_value = erealloc( kw_value , kw_value_len+1); kw_value_len=uloc_getKeywordValue( loc_name,kw_key, kw_value, kw_value_len+1 , &status ); } else if(!U_FAILURE(status)) { kw_value = erealloc( kw_value , kw_value_len+1); } if (U_FAILURE(status)) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_get_keywords: Error encountered while getting the keyword value for the keyword", 0 TSRMLS_CC ); if( kw_value){ efree( kw_value ); } zval_dtor(return_value); RETURN_FALSE; } add_assoc_stringl( return_value, (char *)kw_key, kw_value , kw_value_len, 0); } /* end of while */ } /* end of if e!=NULL */ uenum_close( e ); }
167,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TargetHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { auto_attacher_.SetRenderFrameHost(frame_host); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void TargetHandler::SetRenderer(RenderProcessHost* process_host, void TargetHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { auto_attacher_.SetRenderFrameHost(frame_host); }
172,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) { struct user *dummy = NULL; addr_t offset; if (addr < (addr_t) &dummy->regs.acrs) { /* * psw and gprs are stored on the stack */ if (addr == (addr_t) &dummy->regs.psw.mask) { unsigned long mask = PSW_MASK_USER; mask |= is_ri_task(child) ? PSW_MASK_RI : 0; if ((data & ~mask) != PSW_USER_BITS) return -EINVAL; if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA)) return -EINVAL; } *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data; } else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.acrs; #ifdef CONFIG_64BIT /* * Very special case: old & broken 64 bit gdb writing * to acrs[15] with a 64 bit value. Ignore the lower * half of the value and write the upper 32 bit to * acrs[15]. Sick... */ if (addr == (addr_t) &dummy->regs.acrs[15]) child->thread.acrs[15] = (unsigned int) (data >> 32); else #endif *(addr_t *)((addr_t) &child->thread.acrs + offset) = data; } else if (addr == (addr_t) &dummy->regs.orig_gpr2) { /* * orig_gpr2 is stored on the kernel stack */ task_pt_regs(child)->orig_gpr2 = data; } else if (addr < (addr_t) &dummy->regs.fp_regs) { /* * prevent writes of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy->regs.fp_regs.fpc) if ((unsigned int) data != 0 || test_fp_ctl(data >> (BITS_PER_LONG - 32))) return -EINVAL; offset = addr - (addr_t) &dummy->regs.fp_regs; *(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data; } else if (addr < (addr_t) (&dummy->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy->regs.per_info; __poke_user_per(child, addr, data); } return 0; } Commit Message: s390/ptrace: fix PSW mask check The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect. The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace interface accepts all combinations for the address-space-control bits. To protect the kernel space the PSW mask check in ptrace needs to reject the address-space-control bit combination for home space. Fixes CVE-2014-3534 Cc: stable@vger.kernel.org Signed-off-by: Martin Schwidefsky <schwidefsky@de.ibm.com> CWE ID: CWE-264
static int __poke_user(struct task_struct *child, addr_t addr, addr_t data) { struct user *dummy = NULL; addr_t offset; if (addr < (addr_t) &dummy->regs.acrs) { /* * psw and gprs are stored on the stack */ if (addr == (addr_t) &dummy->regs.psw.mask) { unsigned long mask = PSW_MASK_USER; mask |= is_ri_task(child) ? PSW_MASK_RI : 0; if ((data ^ PSW_USER_BITS) & ~mask) /* Invalid psw mask. */ return -EINVAL; if ((data & PSW_MASK_ASC) == PSW_ASC_HOME) /* Invalid address-space-control bits */ return -EINVAL; if ((data & PSW_MASK_EA) && !(data & PSW_MASK_BA)) /* Invalid addressing mode bits */ return -EINVAL; } *(addr_t *)((addr_t) &task_pt_regs(child)->psw + addr) = data; } else if (addr < (addr_t) (&dummy->regs.orig_gpr2)) { /* * access registers are stored in the thread structure */ offset = addr - (addr_t) &dummy->regs.acrs; #ifdef CONFIG_64BIT /* * Very special case: old & broken 64 bit gdb writing * to acrs[15] with a 64 bit value. Ignore the lower * half of the value and write the upper 32 bit to * acrs[15]. Sick... */ if (addr == (addr_t) &dummy->regs.acrs[15]) child->thread.acrs[15] = (unsigned int) (data >> 32); else #endif *(addr_t *)((addr_t) &child->thread.acrs + offset) = data; } else if (addr == (addr_t) &dummy->regs.orig_gpr2) { /* * orig_gpr2 is stored on the kernel stack */ task_pt_regs(child)->orig_gpr2 = data; } else if (addr < (addr_t) &dummy->regs.fp_regs) { /* * prevent writes of padding hole between * orig_gpr2 and fp_regs on s390. */ return 0; } else if (addr < (addr_t) (&dummy->regs.fp_regs + 1)) { /* * floating point regs. are stored in the thread structure */ if (addr == (addr_t) &dummy->regs.fp_regs.fpc) if ((unsigned int) data != 0 || test_fp_ctl(data >> (BITS_PER_LONG - 32))) return -EINVAL; offset = addr - (addr_t) &dummy->regs.fp_regs; *(addr_t *)((addr_t) &child->thread.fp_regs + offset) = data; } else if (addr < (addr_t) (&dummy->regs.per_info + 1)) { /* * Handle access to the per_info structure. */ addr -= (addr_t) &dummy->regs.per_info; __poke_user_per(child, addr, data); } return 0; }
166,362
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderProcessImpl::RenderProcessImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_( FROM_HERE, base::TimeDelta::FromSeconds(5), this, &RenderProcessImpl::ClearTransportDIBCache)), transport_dib_next_sequence_number_(0) { in_process_plugins_ = InProcessPlugins(); for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) shared_mem_cache_[i] = NULL; #if defined(OS_WIN) if (GetModuleHandle(L"LPK.DLL") == NULL) { typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs); GdiInitializeLanguagePack gdi_init_lpk = reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress( GetModuleHandle(L"GDI32.DLL"), "GdiInitializeLanguagePack")); DCHECK(gdi_init_lpk); if (gdi_init_lpk) { gdi_init_lpk(0); } } #endif webkit_glue::SetJavaScriptFlags( "--debugger-auto-break" " --prof --prof-lazy"); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kJavaScriptFlags)) { webkit_glue::SetJavaScriptFlags( command_line.GetSwitchValueASCII(switches::kJavaScriptFlags)); } } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
RenderProcessImpl::RenderProcessImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_( FROM_HERE, base::TimeDelta::FromSeconds(5), this, &RenderProcessImpl::ClearTransportDIBCache)), transport_dib_next_sequence_number_(0), enabled_bindings_(0) { in_process_plugins_ = InProcessPlugins(); for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) shared_mem_cache_[i] = NULL; #if defined(OS_WIN) if (GetModuleHandle(L"LPK.DLL") == NULL) { typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs); GdiInitializeLanguagePack gdi_init_lpk = reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress( GetModuleHandle(L"GDI32.DLL"), "GdiInitializeLanguagePack")); DCHECK(gdi_init_lpk); if (gdi_init_lpk) { gdi_init_lpk(0); } } #endif webkit_glue::SetJavaScriptFlags( "--debugger-auto-break" " --prof --prof-lazy"); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kJavaScriptFlags)) { webkit_glue::SetJavaScriptFlags( command_line.GetSwitchValueASCII(switches::kJavaScriptFlags)); } }
171,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CuePoint::GetTimeCode() const { return m_timecode; } 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 CuePoint::GetTimeCode() const long long CuePoint::GetTime(const Segment* pSegment) const { assert(pSegment); assert(m_timecode >= 0); const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long time = scale * m_timecode; return time; }
174,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UnacceleratedStaticBitmapImage::MakeAccelerated( base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) { if (!context_wrapper) return nullptr; // Can happen if the context is lost. GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext(); if (!grcontext) return nullptr; // Can happen if the context is lost. sk_sp<SkImage> sk_image = paint_image_.GetSkImage(); sk_sp<SkImage> gpu_skimage = sk_image->makeTextureImage(grcontext, sk_image->colorSpace()); if (!gpu_skimage) return nullptr; return AcceleratedStaticBitmapImage::CreateFromSkImage( std::move(gpu_skimage), std::move(context_wrapper)); } 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 <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
UnacceleratedStaticBitmapImage::MakeAccelerated( base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_wrapper) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!context_wrapper) return nullptr; // Can happen if the context is lost. GrContext* grcontext = context_wrapper->ContextProvider()->GetGrContext(); if (!grcontext) return nullptr; // Can happen if the context is lost. sk_sp<SkImage> sk_image = paint_image_.GetSkImage(); sk_sp<SkImage> gpu_skimage = sk_image->makeTextureImage(grcontext, sk_image->colorSpace()); if (!gpu_skimage) return nullptr; return AcceleratedStaticBitmapImage::CreateFromSkImage( std::move(gpu_skimage), std::move(context_wrapper)); }
172,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter) { if (depth > kMaxMenuDepth) return NULL; ++depth; PP_Flash_Menu* menu = new PP_Flash_Menu; menu->items = NULL; if (!m->ReadUInt32(iter, &menu->count)) { FreeMenu(menu); return NULL; } if (menu->count == 0) return menu; menu->items = new PP_Flash_MenuItem[menu->count]; memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count); for (uint32_t i = 0; i < menu->count; ++i) { if (!ReadMenuItem(depth, m, iter, menu->items + i)) { FreeMenu(menu); return NULL; } } return menu; } Commit Message: IPC: defend against excessive number of submenu entries in PPAPI message. BUG=168710 Review URL: https://codereview.chromium.org/11794037 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175576 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
PP_Flash_Menu* ReadMenu(int depth, const IPC::Message* m, PickleIterator* iter) { if (depth > kMaxMenuDepth) return NULL; ++depth; PP_Flash_Menu* menu = new PP_Flash_Menu; menu->items = NULL; if (!m->ReadUInt32(iter, &menu->count)) { FreeMenu(menu); return NULL; } if (menu->count == 0) return menu; if (menu->count > kMaxMenuEntries) { FreeMenu(menu); return NULL; } menu->items = new PP_Flash_MenuItem[menu->count]; memset(menu->items, 0, sizeof(PP_Flash_MenuItem) * menu->count); for (uint32_t i = 0; i < menu->count; ++i) { if (!ReadMenuItem(depth, m, iter, menu->items + i)) { FreeMenu(menu); return NULL; } } return menu; }
171,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "TIME")) return; reply(nickFromMask(prefix), "TIME", QDateTime::currentDateTime().toString()); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") .arg(nickFromMask(prefix)).arg(param)); } } Commit Message: CWE ID: CWE-399
void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handleTime(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { reply = QDateTime::currentDateTime().toString(); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") .arg(nickFromMask(prefix)).arg(param)); } }
164,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
status_t MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; }
173,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); } Commit Message: [Android WebAPK] Send share target information in WebAPK updates This CL plumbs through share target information for WebAPK updates. Chromium detects Web Manifest updates (including Web Manifest share target updates) and requests an update. Currently, depending on whether the Web Manifest is for an intranet site, the updated WebAPK would either: - no longer be able handle share intents (even if the Web Manifest share target information was not deleted) - be created with the same share intent handlers as the current WebAPK (regardless of whether the Web Manifest share target information has changed). This CL plumbs through the share target information from WebApkUpdateDataFetcher#onDataAvailable() to WebApkUpdateManager::StoreWebApkUpdateRequestToFile() BUG=912945 Change-Id: Ie416570533abc848eeb23de8c197b44f2a1fd028 Reviewed-on: https://chromium-review.googlesource.com/c/1369709 Commit-Queue: Peter Kotwicz <pkotwicz@chromium.org> Reviewed-by: Dominick Ng <dominickn@chromium.org> Cr-Commit-Position: refs/heads/master@{#616429} CWE ID: CWE-200
static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_share_target_action, const JavaParamRef<jstring>& java_share_target_param_title, const JavaParamRef<jstring>& java_share_target_param_text, const JavaParamRef<jstring>& java_share_target_param_url, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); GURL share_target_action = GURL(ConvertJavaStringToUTF8(env, java_share_target_action)); if (!share_target_action.is_empty()) { info.share_target = ShareTarget(); info.share_target->action = share_target_action; info.share_target->params.title = ConvertJavaStringToUTF16(java_share_target_param_title); info.share_target->params.text = ConvertJavaStringToUTF16(java_share_target_param_text); info.share_target->params.url = ConvertJavaStringToUTF16(java_share_target_param_url); } base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls, &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes, &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); }
172,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; } Commit Message: Fixed bug #72227: imagescale out-of-bounds read Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a CWE ID: CWE-125
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter) { double width_d; double scale_f_d = 1.0; const double filter_width_d = DEFAULT_BOX_RADIUS; int windows_size; unsigned int u; LineContribType *res; if (scale_d < 1.0) { width_d = filter_width_d / scale_d; scale_f_d = scale_d; } else { width_d= filter_width_d; } windows_size = 2 * (int)ceil(width_d) + 1; res = _gdContributionsAlloc(line_size, windows_size); for (u = 0; u < line_size; u++) { const double dCenter = (double)u / scale_d; /* get the significant edge points affecting the pixel */ register int iLeft = MAX(0, (int)floor (dCenter - width_d)); int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1); double dTotalWeight = 0.0; int iSrc; /* Cut edge points to fit in filter window in case of spill-off */ if (iRight - iLeft + 1 > windows_size) { if (iLeft < ((int)src_size - 1 / 2)) { iLeft++; } else { iRight--; } } res->ContribRow[u].Left = iLeft; res->ContribRow[u].Right = iRight; for (iSrc = iLeft; iSrc <= iRight; iSrc++) { dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); } if (dTotalWeight < 0.0) { _gdContributionsFree(res); return NULL; } if (dTotalWeight > 0.0) { for (iSrc = iLeft; iSrc <= iRight; iSrc++) { res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight; } } } return res; }
170,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } }
167,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); } Commit Message: Set Attr.ownerDocument in Element#setAttributeNode() Attr objects can move across documents by setAttributeNode(). So It needs to reset ownerDocument through TreeScopeAdoptr::adoptIfNeeded(). BUG=248950 TEST=set-attribute-node-from-iframe.html Review URL: https://chromiumcodereview.appspot.com/17583003 git-svn-id: svn://svn.chromium.org/blink/trunk@152938 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionCode& ec) { if (!attrNode) { ec = TYPE_MISMATCH_ERR; return 0; } RefPtr<Attr> oldAttrNode = attrIfExists(attrNode->qualifiedName()); if (oldAttrNode.get() == attrNode) return attrNode; // This Attr is already attached to the element. if (attrNode->ownerElement()) { ec = INUSE_ATTRIBUTE_ERR; return 0; } synchronizeAllAttributes(); UniqueElementData* elementData = ensureUniqueElementData(); size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName()); if (index != notFound) { if (oldAttrNode) detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value()); else oldAttrNode = Attr::create(document(), attrNode->qualifiedName(), elementData->attributeItem(index)->value()); } setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute); attrNode->attachToElement(this); treeScope()->adoptIfNeeded(attrNode); ensureAttrNodeListForElement(this)->append(attrNode); return oldAttrNode.release(); }
171,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintSettingsInitializerWin::InitPrintSettings( HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name, bool print_selection_only, PrintSettings* print_settings) { DCHECK(hdc); DCHECK(print_settings); print_settings->set_printer_name(dev_mode.dmDeviceName); print_settings->set_device_name(new_device_name); print_settings->ranges = new_ranges; print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE); print_settings->selection_only = print_selection_only; int dpi = GetDeviceCaps(hdc, LOGPIXELSX); print_settings->set_dpi(dpi); const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA; print_settings->set_supports_alpha_blend( (GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps); DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); print_settings->SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintSettingsInitializerWin::InitPrintSettings( HDC hdc, const DEVMODE& dev_mode, const PageRanges& new_ranges, const std::wstring& new_device_name, bool print_selection_only, PrintSettings* print_settings) { DCHECK(hdc); DCHECK(print_settings); print_settings->set_printer_name(dev_mode.dmDeviceName); print_settings->set_device_name(new_device_name); print_settings->ranges = const_cast<PageRanges&>(new_ranges); print_settings->set_landscape(dev_mode.dmOrientation == DMORIENT_LANDSCAPE); print_settings->selection_only = print_selection_only; int dpi = GetDeviceCaps(hdc, LOGPIXELSX); print_settings->set_dpi(dpi); const int kAlphaCaps = SB_CONST_ALPHA | SB_PIXEL_ALPHA; print_settings->set_supports_alpha_blend( (GetDeviceCaps(hdc, SHADEBLENDCAPS) & kAlphaCaps) == kAlphaCaps); DCHECK_EQ(dpi, GetDeviceCaps(hdc, LOGPIXELSY)); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); gfx::Size physical_size_device_units(GetDeviceCaps(hdc, PHYSICALWIDTH), GetDeviceCaps(hdc, PHYSICALHEIGHT)); gfx::Rect printable_area_device_units(GetDeviceCaps(hdc, PHYSICALOFFSETX), GetDeviceCaps(hdc, PHYSICALOFFSETY), GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); print_settings->SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, dpi); }
170,265
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AppResult::AppResult(Profile* profile, const std::string& app_id, AppListControllerDelegate* controller, bool is_recommendation) : profile_(profile), app_id_(app_id), controller_(controller), extension_registry_(NULL) { set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec()); if (app_list::switches::IsExperimentalAppListEnabled()) set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE); const extensions::Extension* extension = extensions::ExtensionSystem::Get(profile_)->extension_service() ->GetInstalledExtension(app_id_); DCHECK(extension); is_platform_app_ = extension->is_platform_app(); icon_.reset( new extensions::IconImage(profile_, extension, extensions::IconsInfo::GetIcons(extension), GetPreferredIconDimension(), extensions::util::GetDefaultAppIcon(), this)); UpdateIcon(); StartObservingExtensionRegistry(); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
AppResult::AppResult(Profile* profile, const std::string& app_id, AppListControllerDelegate* controller, bool is_recommendation) : profile_(profile), app_id_(app_id), controller_(controller), extension_registry_(NULL) { set_id(extensions::Extension::GetBaseURLFromExtensionId(app_id_).spec()); if (app_list::switches::IsExperimentalAppListEnabled()) set_display_type(is_recommendation ? DISPLAY_RECOMMENDATION : DISPLAY_TILE); const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension( app_id_); DCHECK(extension); is_platform_app_ = extension->is_platform_app(); icon_.reset( new extensions::IconImage(profile_, extension, extensions::IconsInfo::GetIcons(extension), GetPreferredIconDimension(), extensions::util::GetDefaultAppIcon(), this)); UpdateIcon(); StartObservingExtensionRegistry(); }
171,725
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, String servicesUUID) { if (!connected()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(NetworkError, kGATTServerNotConnected)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); WTF::Optional<String> uuid = WTF::nullopt; if (!servicesUUID.isEmpty()) uuid = servicesUUID; service->RemoteServerGetPrimaryServices( device()->id(), quantity, uuid, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback, wrapPersistent(this), quantity, wrapPersistent(resolver)))); return promise; } Commit Message: Allow serialization of empty bluetooth uuids. This change allows the passing WTF::Optional<String> types as bluetooth.mojom.UUID optional parameter without needing to ensure the passed object isn't empty. BUG=None R=juncai, dcheng Review-Url: https://codereview.chromium.org/2646613003 Cr-Commit-Position: refs/heads/master@{#445809} CWE ID: CWE-119
ScriptPromise BluetoothRemoteGATTServer::getPrimaryServicesImpl( ScriptState* scriptState, mojom::blink::WebBluetoothGATTQueryQuantity quantity, String servicesUUID) { if (!connected()) { return ScriptPromise::rejectWithDOMException( scriptState, DOMException::create(NetworkError, kGATTServerNotConnected)); } ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState); ScriptPromise promise = resolver->promise(); AddToActiveAlgorithms(resolver); mojom::blink::WebBluetoothService* service = m_device->bluetooth()->service(); service->RemoteServerGetPrimaryServices( device()->id(), quantity, servicesUUID, convertToBaseCallback( WTF::bind(&BluetoothRemoteGATTServer::GetPrimaryServicesCallback, wrapPersistent(this), quantity, wrapPersistent(resolver)))); return promise; }
172,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_) { register const struct ip6_rthdr *dp; register const struct ip6_rthdr0 *dp0; register const u_char *ep; int i, len; register const struct in6_addr *addr; dp = (const struct ip6_rthdr *)bp; len = dp->ip6r_len; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->ip6r_segleft); ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/ ND_PRINT((ndo, ", type=%d", dp->ip6r_type)); ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft)); switch (dp->ip6r_type) { case IPV6_RTHDR_TYPE_0: case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */ dp0 = (const struct ip6_rthdr0 *)dp; ND_TCHECK(dp0->ip6r0_reserved); if (dp0->ip6r0_reserved || ndo->ndo_vflag) { ND_PRINT((ndo, ", rsv=0x%0x", EXTRACT_32BITS(&dp0->ip6r0_reserved))); } if (len % 2 == 1) goto trunc; len >>= 1; addr = &dp0->ip6r0_addr[0]; for (i = 0; i < len; i++) { if ((const u_char *)(addr + 1) > ep) goto trunc; ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr))); addr++; } /*(*/ ND_PRINT((ndo, ") ")); return((dp0->ip6r0_len + 1) << 3); break; default: goto trunc; break; } trunc: ND_PRINT((ndo, "[|srcrt]")); return -1; } Commit Message: CVE-2017-13725/IPv6 R.H.: Check for the existence of all fields before fetching them. Don't fetch the length field from the header until after we've checked for the existence of a field at or after that field. (Found by code inspection, not by a capture.) CWE ID: CWE-125
rt6_print(netdissect_options *ndo, register const u_char *bp, const u_char *bp2 _U_) { register const struct ip6_rthdr *dp; register const struct ip6_rthdr0 *dp0; register const u_char *ep; int i, len; register const struct in6_addr *addr; dp = (const struct ip6_rthdr *)bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; ND_TCHECK(dp->ip6r_segleft); len = dp->ip6r_len; ND_PRINT((ndo, "srcrt (len=%d", dp->ip6r_len)); /*)*/ ND_PRINT((ndo, ", type=%d", dp->ip6r_type)); ND_PRINT((ndo, ", segleft=%d", dp->ip6r_segleft)); switch (dp->ip6r_type) { case IPV6_RTHDR_TYPE_0: case IPV6_RTHDR_TYPE_2: /* Mobile IPv6 ID-20 */ dp0 = (const struct ip6_rthdr0 *)dp; ND_TCHECK(dp0->ip6r0_reserved); if (dp0->ip6r0_reserved || ndo->ndo_vflag) { ND_PRINT((ndo, ", rsv=0x%0x", EXTRACT_32BITS(&dp0->ip6r0_reserved))); } if (len % 2 == 1) goto trunc; len >>= 1; addr = &dp0->ip6r0_addr[0]; for (i = 0; i < len; i++) { if ((const u_char *)(addr + 1) > ep) goto trunc; ND_PRINT((ndo, ", [%d]%s", i, ip6addr_string(ndo, addr))); addr++; } /*(*/ ND_PRINT((ndo, ") ")); return((dp0->ip6r0_len + 1) << 3); break; default: goto trunc; break; } trunc: ND_PRINT((ndo, "[|srcrt]")); return -1; }
167,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { DCHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <jsbell@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
IndexedDBTransaction* IndexedDBConnection::CreateTransaction( int64_t id, const std::set<int64_t>& scope, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) { CHECK_EQ(GetTransaction(id), nullptr) << "Duplicate transaction id." << id; std::unique_ptr<IndexedDBTransaction> transaction = IndexedDBClassFactory::Get()->CreateIndexedDBTransaction( id, this, scope, mode, backing_store_transaction); IndexedDBTransaction* transaction_ptr = transaction.get(); transactions_[id] = std::move(transaction); return transaction_ptr; }
172,352
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FolderHeaderView::Update() { if (!folder_item_) return; folder_name_view_->SetVisible(folder_name_visible_); if (folder_name_visible_) folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name())); Layout(); } Commit Message: Enforce the maximum length of the folder name in UI. BUG=355797 R=xiyuan@chromium.org Review URL: https://codereview.chromium.org/203863005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void FolderHeaderView::Update() { if (!folder_item_) return; folder_name_view_->SetVisible(folder_name_visible_); if (folder_name_visible_) { folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name())); folder_name_view_->Update(); } Layout(); }
171,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), interstitial_page_(nullptr), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) }
172,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 svc_rdma_get_write_arrays(struct rpcrdma_msg *rmsgp, struct rpcrdma_write_array **write, struct rpcrdma_write_array **reply) { __be32 *p; p = (__be32 *)&rmsgp->rm_body.rm_chunks[0]; /* Read list */ while (*p++ != xdr_zero) p += 5; /* Write list */ if (*p != xdr_zero) { *write = (struct rpcrdma_write_array *)p; while (*p++ != xdr_zero) p += 1 + be32_to_cpu(*p) * 4; } else { *write = NULL; p++; } /* Reply chunk */ if (*p != xdr_zero) *reply = (struct rpcrdma_write_array *)p; else *reply = 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
static void svc_rdma_get_write_arrays(struct rpcrdma_msg *rmsgp, static void svc_rdma_get_write_arrays(__be32 *rdma_argp, __be32 **write, __be32 **reply) { __be32 *p; p = rdma_argp + rpcrdma_fixed_maxsz; /* Read list */ while (*p++ != xdr_zero) p += 5; /* Write list */ if (*p != xdr_zero) { *write = p; while (*p++ != xdr_zero) p += 1 + be32_to_cpu(*p) * 4; } else { *write = NULL; p++; } /* Reply chunk */ if (*p != xdr_zero) *reply = p; else *reply = NULL; }
168,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) { tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT; uint8_t u8, pdu, *p; uint16_t u16; tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor; pdu = *(p_vendor->p_vendor_data); p_rc_rsp->pdu = pdu; *p_ctype = AVRC_RSP_REJ; /* Check to ansure a valid minimum meta data length */ if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) { /* reject it */ p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM; APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__, p_vendor->vendor_len); return 0; } /* Metadata messages only use PANEL sub-unit type */ if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) { APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__); /* reject it */ evt = 0; p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL; p_vendor->vendor_len = 0; p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM; } else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) { APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu, p_vendor->hdr.ctype); /* reject invalid message without reporting to app */ evt = 0; p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD; } else { switch (pdu) { case AVRC_PDU_GET_CAPABILITIES: /* process GetCapabilities command without reporting the event to app */ evt = 0; u8 = *(p_vendor->p_vendor_data + 4); p = p_vendor->p_vendor_data + 2; p_rc_rsp->get_caps.capability_id = u8; BE_STREAM_TO_UINT16(u16, p); if ((u16 != 1) || (p_vendor->vendor_len != 5)) { p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR; } else { p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR; if (u8 == AVRC_CAP_COMPANY_ID) { *p_ctype = AVRC_RSP_IMPL_STBL; p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids; memcpy(p_rc_rsp->get_caps.param.company_id, p_bta_av_cfg->p_meta_co_ids, (p_bta_av_cfg->num_co_ids << 2)); } else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) { *p_ctype = AVRC_RSP_IMPL_STBL; p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids; memcpy(p_rc_rsp->get_caps.param.event_id, p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids); } else { APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8); /* reject - unknown capability ID */ p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM; } } break; case AVRC_PDU_REGISTER_NOTIFICATION: /* make sure the event_id is implemented */ p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor); if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0; break; } } return evt; } Commit Message: Check packet length in bta_av_proc_meta_cmd Bug: 111893951 Test: manual - connect A2DP Change-Id: Ibbf347863dfd29ea3385312e9dde1082bc90d2f3 (cherry picked from commit ed51887f921263219bcd2fbf6650ead5ec8d334e) CWE ID: CWE-125
tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp, tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) { tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT; uint8_t u8, pdu, *p; uint16_t u16; tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor; pdu = *(p_vendor->p_vendor_data); p_rc_rsp->pdu = pdu; *p_ctype = AVRC_RSP_REJ; /* Check to ansure a valid minimum meta data length */ if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) { /* reject it */ p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM; APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__, p_vendor->vendor_len); return 0; } /* Metadata messages only use PANEL sub-unit type */ if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) { APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__); /* reject it */ evt = 0; p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL; p_vendor->vendor_len = 0; p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM; } else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) { APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu, p_vendor->hdr.ctype); /* reject invalid message without reporting to app */ evt = 0; p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD; } else { switch (pdu) { case AVRC_PDU_GET_CAPABILITIES: /* process GetCapabilities command without reporting the event to app */ evt = 0; if (p_vendor->vendor_len != 5) { android_errorWriteLog(0x534e4554, "111893951"); p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR; break; } u8 = *(p_vendor->p_vendor_data + 4); p = p_vendor->p_vendor_data + 2; p_rc_rsp->get_caps.capability_id = u8; BE_STREAM_TO_UINT16(u16, p); if (u16 != 1) { p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR; } else { p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR; if (u8 == AVRC_CAP_COMPANY_ID) { *p_ctype = AVRC_RSP_IMPL_STBL; p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids; memcpy(p_rc_rsp->get_caps.param.company_id, p_bta_av_cfg->p_meta_co_ids, (p_bta_av_cfg->num_co_ids << 2)); } else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) { *p_ctype = AVRC_RSP_IMPL_STBL; p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids; memcpy(p_rc_rsp->get_caps.param.event_id, p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids); } else { APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8); /* reject - unknown capability ID */ p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM; } } break; case AVRC_PDU_REGISTER_NOTIFICATION: /* make sure the event_id is implemented */ p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor); if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0; break; } } return evt; }
174,078
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_width=1.0; draw_info->alpha=OpaqueAlpha; draw_info->fill_rule=EvenOddRule; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(Quantum) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); draw_info->stroke_antialias=clone_info->antialias; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (clone_info->pointsize != 0.0) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); } Commit Message: Prevent buffer overflow in magick/draw.c CWE ID: CWE-119
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) { const char *option; ExceptionInfo *exception; ImageInfo *clone_info; /* Initialize draw attributes. */ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(draw_info != (DrawInfo *) NULL); (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info)); clone_info=CloneImageInfo(image_info); GetAffineMatrix(&draw_info->affine); exception=AcquireExceptionInfo(); (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#0000",AllCompliance,&draw_info->stroke, exception); draw_info->stroke_width=1.0; draw_info->alpha=OpaqueAlpha; draw_info->fill_rule=EvenOddRule; draw_info->linecap=ButtCap; draw_info->linejoin=MiterJoin; draw_info->miterlimit=10; draw_info->decorate=NoDecoration; draw_info->pointsize=12.0; draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; draw_info->compose=OverCompositeOp; draw_info->render=MagickTrue; draw_info->debug=IsEventLogging(); draw_info->stroke_antialias=clone_info->antialias; if (clone_info->font != (char *) NULL) draw_info->font=AcquireString(clone_info->font); if (clone_info->density != (char *) NULL) draw_info->density=AcquireString(clone_info->density); draw_info->text_antialias=clone_info->antialias; if (clone_info->pointsize != 0.0) draw_info->pointsize=clone_info->pointsize; draw_info->border_color=clone_info->border_color; if (clone_info->server_name != (char *) NULL) draw_info->server_name=AcquireString(clone_info->server_name); option=GetImageOption(clone_info,"direction"); if (option != (const char *) NULL) draw_info->direction=(DirectionType) ParseCommandOption( MagickDirectionOptions,MagickFalse,option); else draw_info->direction=UndefinedDirection; option=GetImageOption(clone_info,"encoding"); if (option != (const char *) NULL) (void) CloneString(&draw_info->encoding,option); option=GetImageOption(clone_info,"family"); if (option != (const char *) NULL) (void) CloneString(&draw_info->family,option); option=GetImageOption(clone_info,"fill"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill, exception); option=GetImageOption(clone_info,"gravity"); if (option != (const char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,option); option=GetImageOption(clone_info,"interline-spacing"); if (option != (const char *) NULL) draw_info->interline_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"interword-spacing"); if (option != (const char *) NULL) draw_info->interword_spacing=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"kerning"); if (option != (const char *) NULL) draw_info->kerning=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"stroke"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke, exception); option=GetImageOption(clone_info,"strokewidth"); if (option != (const char *) NULL) draw_info->stroke_width=StringToDouble(option,(char **) NULL); option=GetImageOption(clone_info,"style"); if (option != (const char *) NULL) draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions, MagickFalse,option); option=GetImageOption(clone_info,"undercolor"); if (option != (const char *) NULL) (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor, exception); option=GetImageOption(clone_info,"weight"); if (option != (const char *) NULL) { ssize_t weight; weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); if (weight == -1) weight=(ssize_t) StringToUnsignedLong(option); draw_info->weight=(size_t) weight; } exception=DestroyExceptionInfo(exception); draw_info->signature=MagickCoreSignature; clone_info=DestroyImageInfo(clone_info); }
167,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: krb5_gss_process_context_token(minor_status, context_handle, token_buffer) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { krb5_gss_ctx_id_rec *ctx; OM_uint32 majerr; ctx = (krb5_gss_ctx_id_t) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* "unseal" the token */ if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle, token_buffer, GSS_C_NO_BUFFER, NULL, NULL, KG_TOK_DEL_CTX))) return(majerr); /* that's it. delete the context */ return(krb5_gss_delete_sec_context(minor_status, &context_handle, GSS_C_NO_BUFFER)); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_process_context_token(minor_status, context_handle, token_buffer) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { krb5_gss_ctx_id_rec *ctx; OM_uint32 majerr; ctx = (krb5_gss_ctx_id_t) context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* We only support context deletion tokens for now, and RFC 4121 does not * define a context deletion token. */ if (ctx->proto) { *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); } /* "unseal" the token */ if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle, token_buffer, GSS_C_NO_BUFFER, NULL, NULL, KG_TOK_DEL_CTX))) return(majerr); /* Mark the context as terminated, but do not delete it (as that would * leave the caller with a dangling context handle). */ ctx->terminated = 1; return(GSS_S_COMPLETE); }
166,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
PageCaptureCustomBindings::PageCaptureCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("CreateBlob", "pageCapture", base::Bind(&PageCaptureCustomBindings::CreateBlob, base::Unretained(this))); RouteFunction("SendResponseAck", "pageCapture", base::Bind(&PageCaptureCustomBindings::SendResponseAck, base::Unretained(this))); }
173,277
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind()
167,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } Commit Message: Merge pull request #131 from benjaminchodroff/master fix memory corruption and other 32bit overflows CWE ID: CWE-190
int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size; if (pkg->body_size > RPC_PKG_MAX_BODY_SIZE) { return -1; } pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); if (send_buf == NULL) { return -1; } } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; }
169,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<GURL, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<url::Origin, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); }
172,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::RejectPairing() { RunPairingCallbacks(REJECTED); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::RejectPairing() { if (!pairing_context_.get()) return; pairing_context_->RejectPairing(); }
171,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool CanCommitURL(const GURL& url) { SchemeMap::const_iterator judgment(scheme_policy_.find(url.scheme())); if (judgment != scheme_policy_.end()) return judgment->second; if (url.SchemeIs(url::kFileScheme)) { base::FilePath path; if (net::FileURLToFilePath(url, &path)) return ContainsKey(request_file_set_, path); } return false; // Unmentioned schemes are disallowed. } Commit Message: This patch implements a mechanism for more granular link URL permissions (filtering on scheme/host). This fixes the bug that allowed PDFs to have working links to any "chrome://" URLs. BUG=528505,226927 Review URL: https://codereview.chromium.org/1362433002 Cr-Commit-Position: refs/heads/master@{#351705} CWE ID: CWE-264
bool CanCommitURL(const GURL& url) { // Having permission to a scheme implies permission to all of its URLs. SchemeMap::const_iterator scheme_judgment( scheme_policy_.find(url.scheme())); if (scheme_judgment != scheme_policy_.end()) return scheme_judgment->second; // Otherwise, check for permission for specific origin. if (ContainsKey(origin_set_, url::Origin(url))) return true; if (url.SchemeIs(url::kFileScheme)) { base::FilePath path; if (net::FileURLToFilePath(url, &path)) return ContainsKey(request_file_set_, path); } return false; // Unmentioned schemes are disallowed. }
171,775
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; int len = OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_write(bio, obj_txt, len); BIO_write(bio, "\n", 1); return 1; } Commit Message: Fix OOB read in TS_OBJ_print_bio(). TS_OBJ_print_bio() misuses OBJ_txt2obj: it should print the result as a null terminated buffer. The length value returned is the total length the complete text reprsentation would need not the amount of data written. CVE-2016-2180 Thanks to Shi Lei for reporting this bug. Reviewed-by: Matt Caswell <matt@openssl.org> CWE ID: CWE-125
int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj) { char obj_txt[128]; OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0); BIO_printf(bio, "%s\n", obj_txt); return 1; }
167,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: monitor_apply_keystate(struct monitor *pmonitor) { struct ssh *ssh = active_state; /* XXX */ struct kex *kex; int r; debug3("%s: packet_set_state", __func__); if ((r = ssh_packet_set_state(ssh, child_state)) != 0) fatal("%s: packet_set_state: %s", __func__, ssh_err(r)); sshbuf_free(child_state); child_state = NULL; if ((kex = ssh->kex) != NULL) { /* XXX set callbacks */ #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; } /* Update with new address */ if (options.compression) { ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib, (ssh_packet_comp_alloc_func *)mm_zalloc, (ssh_packet_comp_free_func *)mm_zfree); } } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
monitor_apply_keystate(struct monitor *pmonitor) { struct ssh *ssh = active_state; /* XXX */ struct kex *kex; int r; debug3("%s: packet_set_state", __func__); if ((r = ssh_packet_set_state(ssh, child_state)) != 0) fatal("%s: packet_set_state: %s", __func__, ssh_err(r)); sshbuf_free(child_state); child_state = NULL; if ((kex = ssh->kex) != NULL) { /* XXX set callbacks */ #ifdef WITH_OPENSSL kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server; kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server; kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server; kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server; kex->kex[KEX_DH_GEX_SHA1] = kexgex_server; kex->kex[KEX_DH_GEX_SHA256] = kexgex_server; kex->kex[KEX_ECDH_SHA2] = kexecdh_server; #endif kex->kex[KEX_C25519_SHA256] = kexc25519_server; kex->load_host_public_key=&get_hostkey_public_by_type; kex->load_host_private_key=&get_hostkey_private_by_type; kex->host_key_index=&get_hostkey_index; kex->sign = sshd_hostkey_sign; } }
168,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TBR=bbudge@chromium.org 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: static void mpeg4_encode_gop_header(MpegEncContext *s) { int hours, minutes, seconds; int64_t time; put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, GOP_STARTCODE); time = s->current_picture_ptr->f->pts; if (s->reordered_input_picture[1]) time = FFMIN(time, s->reordered_input_picture[1]->f->pts); time = time * s->avctx->time_base.num; s->last_time_base = FFUDIV(time, s->avctx->time_base.den); seconds = FFUDIV(time, s->avctx->time_base.den); minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60); hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60); hours = FFUMOD(hours , 24); put_bits(&s->pb, 5, hours); put_bits(&s->pb, 6, minutes); put_bits(&s->pb, 1, 1); put_bits(&s->pb, 6, seconds); put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)); put_bits(&s->pb, 1, 0); // broken link == NO ff_mpeg4_stuffing(&s->pb); } Commit Message: avcodec/mpeg4videoenc: Use 64 bit for times in mpeg4_encode_gop_header() Fixes truncation Fixes Assertion n <= 31 && value < (1U << n) failed at libavcodec/put_bits.h:169 Fixes: ffmpeg_crash_2.avi Found-by: Thuan Pham <thuanpv@comp.nus.edu.sg>, Marcel Böhme, Andrew Santosa and Alexandru RazvanCaciulescu with AFLSmart Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-20
static void mpeg4_encode_gop_header(MpegEncContext *s) { int64_t hours, minutes, seconds; int64_t time; put_bits(&s->pb, 16, 0); put_bits(&s->pb, 16, GOP_STARTCODE); time = s->current_picture_ptr->f->pts; if (s->reordered_input_picture[1]) time = FFMIN(time, s->reordered_input_picture[1]->f->pts); time = time * s->avctx->time_base.num; s->last_time_base = FFUDIV(time, s->avctx->time_base.den); seconds = FFUDIV(time, s->avctx->time_base.den); minutes = FFUDIV(seconds, 60); seconds = FFUMOD(seconds, 60); hours = FFUDIV(minutes, 60); minutes = FFUMOD(minutes, 60); hours = FFUMOD(hours , 24); put_bits(&s->pb, 5, hours); put_bits(&s->pb, 6, minutes); put_bits(&s->pb, 1, 1); put_bits(&s->pb, 6, seconds); put_bits(&s->pb, 1, !!(s->avctx->flags & AV_CODEC_FLAG_CLOSED_GOP)); put_bits(&s->pb, 1, 0); // broken link == NO ff_mpeg4_stuffing(&s->pb); }
169,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) { AcpiPciHpState *s = opaque; uint32_t val = 0; int bsel = s->hotplug_select; if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) { return 0; } switch (addr) { case PCI_UP_BASE: val = s->acpi_pcihp_pci_status[bsel].up; if (!s->legacy_piix) { s->acpi_pcihp_pci_status[bsel].up = 0; } ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); break; case PCI_DOWN_BASE: val = s->acpi_pcihp_pci_status[bsel].down; ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); break; case PCI_EJ_BASE: /* No feature defined yet */ ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); break; case PCI_RMV_BASE: val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); break; case PCI_SEL_BASE: val = s->hotplug_select; ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); default: break; } return val; } Commit Message: CWE ID: CWE-119
static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) { AcpiPciHpState *s = opaque; uint32_t val = 0; int bsel = s->hotplug_select; if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { return 0; } switch (addr) { case PCI_UP_BASE: val = s->acpi_pcihp_pci_status[bsel].up; if (!s->legacy_piix) { s->acpi_pcihp_pci_status[bsel].up = 0; } ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); break; case PCI_DOWN_BASE: val = s->acpi_pcihp_pci_status[bsel].down; ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); break; case PCI_EJ_BASE: /* No feature defined yet */ ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); break; case PCI_RMV_BASE: val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); break; case PCI_SEL_BASE: val = s->hotplug_select; ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); default: break; } return val; }
165,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || 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; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; } Commit Message: Fix several ineffective integer overflow checks Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added several integer overflow checks. Unfortunately, those checks fail to take into account integer promotion rules and are thus themselves subject to an integer overflow. Cast the sizeof() operator to a uint64_t to force promotion while multiplying. Bug: 20139950 (cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32) Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b CWE ID: CWE-189
status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || 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; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; }
173,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j; p = buff1; i = ctm->length; str = (char *)ctm->data; if (ctm->type == V_ASN1_UTCTIME) { if ((i < 11) || (i > 17)) return 0; memcpy(p, str, 10); p += 10; str += 10; } else { if (i < 13) return 0; memcpy(p, str, 12); p += 12; str += 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { *(p++) = *(str++); *(p++) = *(str++); /* Skip any fractional seconds... */ if (*str == '.') { str++; while ((*str >= '0') && (*str <= '9')) str++; } } *(p++) = 'Z'; *(p++) = '\0'; if (*str == 'Z') offset = 0; else { if ((*str != '+') && (*str != '-')) return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; } Commit Message: Fix length checks in X509_cmp_time to avoid out-of-bounds reads. Also tighten X509_cmp_time to reject more than three fractional seconds in the time; and to reject trailing garbage after the offset. CVE-2015-1789 Reviewed-by: Viktor Dukhovni <viktor@openssl.org> Reviewed-by: Richard Levitte <levitte@openssl.org> CWE ID: CWE-119
int X509_cmp_time(const ASN1_TIME *ctm, time_t *cmp_time) { char *str; ASN1_TIME atm; long offset; char buff1[24], buff2[24], *p; int i, j, remaining; p = buff1; remaining = ctm->length; str = (char *)ctm->data; /* * Note that the following (historical) code allows much more slack in the * time format than RFC5280. In RFC5280, the representation is fixed: * UTCTime: YYMMDDHHMMSSZ * GeneralizedTime: YYYYMMDDHHMMSSZ */ if (ctm->type == V_ASN1_UTCTIME) { /* YYMMDDHHMM[SS]Z or YYMMDDHHMM[SS](+-)hhmm */ int min_length = sizeof("YYMMDDHHMMZ") - 1; int max_length = sizeof("YYMMDDHHMMSS+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 10); p += 10; str += 10; remaining -= 10; } else { /* YYYYMMDDHHMM[SS[.fff]]Z or YYYYMMDDHHMM[SS[.f[f[f]]]](+-)hhmm */ int min_length = sizeof("YYYYMMDDHHMMZ") - 1; int max_length = sizeof("YYYYMMDDHHMMSS.fff+hhmm") - 1; if (remaining < min_length || remaining > max_length) return 0; memcpy(p, str, 12); p += 12; str += 12; remaining -= 12; } if ((*str == 'Z') || (*str == '-') || (*str == '+')) { *(p++) = '0'; *(p++) = '0'; } else { /* SS (seconds) */ if (remaining < 2) return 0; *(p++) = *(str++); *(p++) = *(str++); remaining -= 2; /* * Skip any (up to three) fractional seconds... * TODO(emilia): in RFC5280, fractional seconds are forbidden. * Can we just kill them altogether? */ if (remaining && *str == '.') { str++; remaining--; for (i = 0; i < 3 && remaining; i++, str++, remaining--) { if (*str < '0' || *str > '9') break; } } } *(p++) = 'Z'; *(p++) = '\0'; /* We now need either a terminating 'Z' or an offset. */ if (!remaining) return 0; if (*str == 'Z') { if (remaining != 1) return 0; offset = 0; } else { /* (+-)HHMM */ if ((*str != '+') && (*str != '-')) return 0; /* Historical behaviour: the (+-)hhmm offset is forbidden in RFC5280. */ if (remaining != 5) return 0; if (str[1] < '0' || str[1] > '9' || str[2] < '0' || str[2] > '9' || str[3] < '0' || str[3] > '9' || str[4] < '0' || str[4] > '9') return 0; offset = ((str[1] - '0') * 10 + (str[2] - '0')) * 60; offset += (str[3] - '0') * 10 + (str[4] - '0'); if (*str == '-') offset = -offset; } atm.type = ctm->type; atm.flags = 0; atm.length = sizeof(buff2); atm.data = (unsigned char *)buff2; if (X509_time_adj(&atm, offset * 60, cmp_time) == NULL) return 0; if (ctm->type == V_ASN1_UTCTIME) { i = (buff1[0] - '0') * 10 + (buff1[1] - '0'); if (i < 50) i += 100; /* cf. RFC 2459 */ j = (buff2[0] - '0') * 10 + (buff2[1] - '0'); if (j < 50) j += 100; if (i < j) return -1; if (i > j) return 1; } i = strcmp(buff1, buff2); if (i == 0) /* wait a second then return younger :-) */ return -1; else return i; }
166,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pimv1_join_prune_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { int ngroups, njoin, nprune; int njp; /* If it's a single group and a single source, use 1-line output. */ if (ND_TTEST2(bp[0], 30) && bp[11] == 1 && ((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) { int hold; ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp))); hold = EXTRACT_16BITS(&bp[6]); if (hold != 180) { ND_PRINT((ndo, "Hold ")); unsigned_relts_print(ndo, hold); } ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune", ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f, ipaddr_string(ndo, &bp[12]))); if (EXTRACT_32BITS(&bp[16]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16]))); ND_PRINT((ndo, ") %s%s %s", (bp[24] & 0x01) ? "Sparse" : "Dense", (bp[25] & 0x80) ? " WC" : "", (bp[25] & 0x40) ? "RP" : "SPT")); return; } ND_TCHECK2(bp[0], sizeof(struct in_addr)); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp))); ND_TCHECK2(bp[6], 2); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, " Hold time: ")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6])); if (ndo->ndo_vflag < 2) return; bp += 8; len -= 8; ND_TCHECK2(bp[0], 4); ngroups = bp[3]; bp += 4; len -= 4; while (ngroups--) { /* * XXX - does the address have length "addrlen" and the * mask length "maddrlen"? */ ND_TCHECK2(bp[0], sizeof(struct in_addr)); ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp))); ND_TCHECK2(bp[4], sizeof(struct in_addr)); if (EXTRACT_32BITS(&bp[4]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[4]))); ND_TCHECK2(bp[8], 4); njoin = EXTRACT_16BITS(&bp[8]); nprune = EXTRACT_16BITS(&bp[10]); ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune)); bp += 12; len -= 12; for (njp = 0; njp < (njoin + nprune); njp++) { const char *type; if (njp < njoin) type = "Join "; else type = "Prune"; ND_TCHECK2(bp[0], 6); ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type, (bp[0] & 0x01) ? "Sparse " : "Dense ", (bp[1] & 0x80) ? "WC " : "", (bp[1] & 0x40) ? "RP " : "SPT ", ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f)); bp += 6; len -= 6; } } return; trunc: ND_PRINT((ndo, "[|pim]")); return; } Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes. CWE ID: CWE-125
pimv1_join_prune_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { int ngroups, njoin, nprune; int njp; /* If it's a single group and a single source, use 1-line output. */ if (ND_TTEST2(bp[0], 30) && bp[11] == 1 && ((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) { int hold; ND_PRINT((ndo, " RPF %s ", ipaddr_string(ndo, bp))); hold = EXTRACT_16BITS(&bp[6]); if (hold != 180) { ND_PRINT((ndo, "Hold ")); unsigned_relts_print(ndo, hold); } ND_PRINT((ndo, "%s (%s/%d, %s", njoin ? "Join" : "Prune", ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f, ipaddr_string(ndo, &bp[12]))); if (EXTRACT_32BITS(&bp[16]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[16]))); ND_PRINT((ndo, ") %s%s %s", (bp[24] & 0x01) ? "Sparse" : "Dense", (bp[25] & 0x80) ? " WC" : "", (bp[25] & 0x40) ? "RP" : "SPT")); return; } if (len < sizeof(struct in_addr)) goto trunc; ND_TCHECK2(bp[0], sizeof(struct in_addr)); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, " Upstream Nbr: %s", ipaddr_string(ndo, bp))); bp += 4; len -= 4; if (len < 4) goto trunc; ND_TCHECK2(bp[2], 2); if (ndo->ndo_vflag > 1) ND_PRINT((ndo, "\n")); ND_PRINT((ndo, " Hold time: ")); unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); if (ndo->ndo_vflag < 2) return; bp += 4; len -= 4; if (len < 4) goto trunc; ND_TCHECK2(bp[0], 4); ngroups = bp[3]; bp += 4; len -= 4; while (ngroups--) { /* * XXX - does the address have length "addrlen" and the * mask length "maddrlen"? */ if (len < 4) goto trunc; ND_TCHECK2(bp[0], sizeof(struct in_addr)); ND_PRINT((ndo, "\n\tGroup: %s", ipaddr_string(ndo, bp))); bp += 4; len -= 4; if (len < 4) goto trunc; ND_TCHECK2(bp[0], sizeof(struct in_addr)); if (EXTRACT_32BITS(&bp[0]) != 0xffffffff) ND_PRINT((ndo, "/%s", ipaddr_string(ndo, &bp[0]))); bp += 4; len -= 4; if (len < 4) goto trunc; ND_TCHECK2(bp[0], 4); njoin = EXTRACT_16BITS(&bp[0]); nprune = EXTRACT_16BITS(&bp[2]); ND_PRINT((ndo, " joined: %d pruned: %d", njoin, nprune)); bp += 4; len -= 4; for (njp = 0; njp < (njoin + nprune); njp++) { const char *type; if (njp < njoin) type = "Join "; else type = "Prune"; if (len < 6) goto trunc; ND_TCHECK2(bp[0], 6); ND_PRINT((ndo, "\n\t%s %s%s%s%s/%d", type, (bp[0] & 0x01) ? "Sparse " : "Dense ", (bp[1] & 0x80) ? "WC " : "", (bp[1] & 0x40) ? "RP " : "SPT ", ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f)); bp += 6; len -= 6; } } return; trunc: ND_PRINT((ndo, "[|pim]")); return; }
167,855
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnDidPreviewPage(int page_number, int preview_request_id) { DCHECK_GE(page_number, 0); base::FundamentalValue number(page_number); base::FundamentalValue ui_identifier(id_); base::FundamentalValue request_id(preview_request_id); web_ui()->CallJavascriptFunction( "onDidPreviewPage", number, ui_identifier, request_id); }
170,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { register u_int length = h->len; register u_int caplen = h->caplen; if (caplen < CHDLC_HDRLEN) { ND_PRINT((ndo, "[|chdlc]")); return (caplen); } return (chdlc_print(ndo, p,length)); } Commit Message: CVE-2017-13687/CHDLC: Improve bounds and length checks. Prevent a possible buffer overread in chdlc_print() and replace the custom check in chdlc_if_print() with a standard check in chdlc_print() so that the latter certainly does not over-read even when reached via juniper_chdlc_print(). Add length checks. CWE ID: CWE-125
chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { return chdlc_print(ndo, p, h->len); }
170,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } }
167,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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[]) { int ret; struct lxc_lock *lock; lock = lxc_newlock(NULL, NULL); if (!lock) { fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__); exit(1); } ret = lxclock(lock, 0); if (ret) { fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret); exit(1); } ret = lxcunlock(lock); if (ret) { fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret); exit(1); } lxc_putlock(lock); lock = lxc_newlock("/var/lib/lxc", mycontainername); if (!lock) { fprintf(stderr, "%d: failed to get lock\n", __LINE__); exit(1); } struct stat sb; char *pathname = RUNTIME_PATH "/lock/lxc/var/lib/lxc/"; ret = stat(pathname, &sb); if (ret != 0) { fprintf(stderr, "%d: filename %s not created\n", __LINE__, pathname); exit(1); } lxc_putlock(lock); test_two_locks(); fprintf(stderr, "all tests passed\n"); exit(ret); } Commit Message: CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc This prevents an unprivileged user to use LXC to create arbitrary file on the filesystem. Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Signed-off-by: Tyler Hicks <tyhicks@canonical.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com> CWE ID: CWE-59
int main(int argc, char *argv[]) { int ret; struct lxc_lock *lock; lock = lxc_newlock(NULL, NULL); if (!lock) { fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__); exit(1); } ret = lxclock(lock, 0); if (ret) { fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret); exit(1); } ret = lxcunlock(lock); if (ret) { fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret); exit(1); } lxc_putlock(lock); lock = lxc_newlock("/var/lib/lxc", mycontainername); if (!lock) { fprintf(stderr, "%d: failed to get lock\n", __LINE__); exit(1); } struct stat sb; char *pathname = RUNTIME_PATH "/lxc/lock/var/lib/lxc/"; ret = stat(pathname, &sb); if (ret != 0) { fprintf(stderr, "%d: filename %s not created\n", __LINE__, pathname); exit(1); } lxc_putlock(lock); test_two_locks(); fprintf(stderr, "all tests passed\n"); exit(ret); }
166,726
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); } Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug 28076789. Detail: Before the original fix (Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the code allowed a time-to-sample table size to be 0. The change made in that fix disallowed such situation, which in fact should be allowed. This current patch allows it again while maintaining the security of the previous fix. Bug: 28288202 Bug: 28076789 Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295 CWE ID: CWE-20
SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mHasTimeToSample(false), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); }
173,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */ { xml_parser *parser; int auto_detect = 0; char *encoding_param = NULL; int encoding_param_len = 0; char *ns_param = NULL; int ns_param_len = 0; XML_Char *encoding; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) { RETURN_FALSE; } if (encoding_param != NULL) { /* The supported encoding types are hardcoded here because * we are limited to the encodings supported by expat/xmltok. */ if (encoding_param_len == 0) { encoding = XML(default_encoding); auto_detect = 1; } else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) { encoding = "ISO-8859-1"; } else if (strcasecmp(encoding_param, "UTF-8") == 0) { encoding = "UTF-8"; } else if (strcasecmp(encoding_param, "US-ASCII") == 0) { encoding = "US-ASCII"; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param); RETURN_FALSE; } } else { encoding = XML(default_encoding); } if (ns_support && ns_param == NULL){ ns_param = ":"; } parser = ecalloc(1, sizeof(xml_parser)); parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding), &php_xml_mem_hdlrs, ns_param); parser->target_encoding = encoding; parser->case_folding = 1; parser->object = NULL; parser->isparsing = 0; XML_SetUserData(parser->parser, parser); ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser); parser->index = Z_LVAL_P(return_value); } /* }}} */ Commit Message: CWE ID: CWE-119
static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */ { xml_parser *parser; int auto_detect = 0; char *encoding_param = NULL; int encoding_param_len = 0; char *ns_param = NULL; int ns_param_len = 0; XML_Char *encoding; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) { RETURN_FALSE; } if (encoding_param != NULL) { /* The supported encoding types are hardcoded here because * we are limited to the encodings supported by expat/xmltok. */ if (encoding_param_len == 0) { encoding = XML(default_encoding); auto_detect = 1; } else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) { encoding = "ISO-8859-1"; } else if (strcasecmp(encoding_param, "UTF-8") == 0) { encoding = "UTF-8"; } else if (strcasecmp(encoding_param, "US-ASCII") == 0) { encoding = "US-ASCII"; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param); RETURN_FALSE; } } else { encoding = XML(default_encoding); } if (ns_support && ns_param == NULL){ ns_param = ":"; } parser = ecalloc(1, sizeof(xml_parser)); parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding), &php_xml_mem_hdlrs, ns_param); parser->target_encoding = encoding; parser->case_folding = 1; parser->object = NULL; parser->isparsing = 0; XML_SetUserData(parser->parser, parser); ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser); parser->index = Z_LVAL_P(return_value); } /* }}} */
165,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 balloon_init(void) { if (!xen_domain()) return -ENODEV; pr_info("Initialising balloon driver\n"); #ifdef CONFIG_XEN_PV balloon_stats.current_pages = xen_pv_domain() ? min(xen_start_info->nr_pages - xen_released_pages, max_pfn) : get_num_physpages(); #else balloon_stats.current_pages = get_num_physpages(); #endif balloon_stats.target_pages = balloon_stats.current_pages; balloon_stats.balloon_low = 0; balloon_stats.balloon_high = 0; balloon_stats.total_pages = balloon_stats.current_pages; balloon_stats.schedule_delay = 1; balloon_stats.max_schedule_delay = 32; balloon_stats.retry_count = 1; balloon_stats.max_retry_count = RETRY_UNLIMITED; #ifdef CONFIG_XEN_BALLOON_MEMORY_HOTPLUG set_online_page_callback(&xen_online_page); register_memory_notifier(&xen_memory_nb); register_sysctl_table(xen_root); #endif #ifdef CONFIG_XEN_PV { int i; /* * Initialize the balloon with pages from the extra memory * regions (see arch/x86/xen/setup.c). */ for (i = 0; i < XEN_EXTRA_MEM_MAX_REGIONS; i++) if (xen_extra_mem[i].n_pfns) balloon_add_region(xen_extra_mem[i].start_pfn, xen_extra_mem[i].n_pfns); } #endif /* Init the xen-balloon driver. */ xen_balloon_init(); return 0; } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <jgross@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID: CWE-400
static int __init balloon_init(void) { if (!xen_domain()) return -ENODEV; pr_info("Initialising balloon driver\n"); #ifdef CONFIG_XEN_PV balloon_stats.current_pages = xen_pv_domain() ? min(xen_start_info->nr_pages - xen_released_pages, max_pfn) : get_num_physpages(); #else balloon_stats.current_pages = get_num_physpages(); #endif balloon_stats.target_pages = balloon_stats.current_pages; balloon_stats.balloon_low = 0; balloon_stats.balloon_high = 0; balloon_stats.total_pages = balloon_stats.current_pages; balloon_stats.schedule_delay = 1; balloon_stats.max_schedule_delay = 32; balloon_stats.retry_count = 1; balloon_stats.max_retry_count = 4; #ifdef CONFIG_XEN_BALLOON_MEMORY_HOTPLUG set_online_page_callback(&xen_online_page); register_memory_notifier(&xen_memory_nb); register_sysctl_table(xen_root); #endif #ifdef CONFIG_XEN_PV { int i; /* * Initialize the balloon with pages from the extra memory * regions (see arch/x86/xen/setup.c). */ for (i = 0; i < XEN_EXTRA_MEM_MAX_REGIONS; i++) if (xen_extra_mem[i].n_pfns) balloon_add_region(xen_extra_mem[i].start_pfn, xen_extra_mem[i].n_pfns); } #endif /* Init the xen-balloon driver. */ xen_balloon_init(); return 0; }
169,493
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PluginChannel::~PluginChannel() { if (renderer_handle_) base::CloseProcessHandle(renderer_handle_); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); } 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:
PluginChannel::~PluginChannel() { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); }
170,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; tBTM_LE_PENC_KEYS le_key; SMP_TRACE_DEBUG("%s", __func__); smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); STREAM_TO_UINT16(le_key.ediv, p); STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN); /* store the encryption keys from peer device */ memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN); le_key.sec_level = p_cb->sec_level; le_key.key_size = p_cb->loc_enc_size; if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, (tBTM_LE_KEY_VALUE*)&le_key, true); smp_key_distribution(p_cb, NULL); } Commit Message: Add packet length check in smp_proc_master_id Bug: 111937027 Test: manual Change-Id: I1144c9879e84fa79d68ad9d5fece4f58e2a3b075 (cherry picked from commit c8294662d07a98e9b8b1cab1ab681ec0805ce4e8) CWE ID: CWE-200
void smp_proc_master_id(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { uint8_t* p = p_data->p_data; tBTM_LE_PENC_KEYS le_key; SMP_TRACE_DEBUG("%s", __func__); if (p_cb->rcvd_cmd_len < 11) { // 1(Code) + 2(EDIV) + 8(Rand) android_errorWriteLog(0x534e4554, "111937027"); SMP_TRACE_ERROR("%s: Invalid command length: %d, should be at least 11", __func__, p_cb->rcvd_cmd_len); return; } smp_update_key_mask(p_cb, SMP_SEC_KEY_TYPE_ENC, true); STREAM_TO_UINT16(le_key.ediv, p); STREAM_TO_ARRAY(le_key.rand, p, BT_OCTET8_LEN); /* store the encryption keys from peer device */ memcpy(le_key.ltk, p_cb->ltk, BT_OCTET16_LEN); le_key.sec_level = p_cb->sec_level; le_key.key_size = p_cb->loc_enc_size; if ((p_cb->peer_auth_req & SMP_AUTH_BOND) && (p_cb->loc_auth_req & SMP_AUTH_BOND)) btm_sec_save_le_key(p_cb->pairing_bda, BTM_LE_KEY_PENC, (tBTM_LE_KEY_VALUE*)&le_key, true); smp_key_distribution(p_cb, NULL); }
174,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ext2_xattr_put_super(struct super_block *sb) { mb_cache_shrink(sb->s_bdev); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
ext2_xattr_put_super(struct super_block *sb)
169,982
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->origin = url::Origin(url); params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); }
171,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateArray( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_Array; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateArray( void )
167,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: pixel_copy(png_bytep toBuffer, png_uint_32 toIndex, png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize) { /* Assume we can multiply by 'size' without overflow because we are * just working in a single buffer. */ toIndex *= pixelSize; fromIndex *= pixelSize; if (pixelSize < 8) /* Sub-byte */ { /* Mask to select the location of the copied pixel: */ unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7)); /* The following read the entire pixels and clears the extra: */ unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask; unsigned int sourceByte = fromBuffer[fromIndex >> 3]; /* Don't rely on << or >> supporting '0' here, just in case: */ fromIndex &= 7; if (fromIndex > 0) sourceByte <<= fromIndex; if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); } else /* One or more bytes */ memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
pixel_copy(png_bytep toBuffer, png_uint_32 toIndex, png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize, int littleendian) { /* Assume we can multiply by 'size' without overflow because we are * just working in a single buffer. */ toIndex *= pixelSize; fromIndex *= pixelSize; if (pixelSize < 8) /* Sub-byte */ { /* Mask to select the location of the copied pixel: */ unsigned int destMask = ((1U<<pixelSize)-1) << (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7)); /* The following read the entire pixels and clears the extra: */ unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask; unsigned int sourceByte = fromBuffer[fromIndex >> 3]; /* Don't rely on << or >> supporting '0' here, just in case: */ fromIndex &= 7; if (littleendian) { if (fromIndex > 0) sourceByte >>= fromIndex; if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7; } else { if (fromIndex > 0) sourceByte <<= fromIndex; if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; } toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); } else /* One or more bytes */ memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3); }
173,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc=0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* If we use the undocumented feature to suppress * the zlib header, we have to give inflate an * extra dummy byte to read */ if( nread < count && zfx->algo == 1 ) { *(zfx->inbuf + n) = 0xFF; /* is it really needed ? */ zfx->algo1hack = 1; n++; } zs->avail_in = n; } log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while( zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR ); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) } Commit Message: CWE ID: CWE-20
do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc = 0; int leave = 0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* Algo 1 has no zlib header which requires us to to give * inflate an extra dummy byte to read. To be on the safe * side we allow for up to 4 ff bytes. */ if( nread < count && zfx->algo == 1 && zfx->algo1hack < 4) { *(zfx->inbuf + n) = 0xFF; zfx->algo1hack++; n++; leave = 1; } zs->avail_in = n; } log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while (zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR && !leave); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) }
165,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None R=sky@chromium.org Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AssertObserverCount(int added_count, int removed_count, void AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); }
170,468
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; }
169,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mkvparser::IMkvReader::~IMkvReader() { //// Disable MSVC warnings that suggest making code non-portable. } 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
mkvparser::IMkvReader::~IMkvReader() #ifdef _MSC_VER //// Disable MSVC warnings that suggest making code non-portable. #pragma warning(disable : 4996) #endif mkvparser::IMkvReader::~IMkvReader() {} void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { major = 1; minor = 0; build = 0; revision = 28; }
174,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 touch(const char *path) { return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0); } Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere CWE ID: CWE-264
int touch(const char *path) { return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID); }
170,104
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p, const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile) { /* i_ctx_p is NULL running arg (@) files. * lib_path and mem are never NULL */ bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file; bool search_with_no_combine = false; bool search_with_combine = false; char fmode[2] = { 'r', 0}; gx_io_device *iodev = iodev_default(mem); gs_main_instance *minst = get_minst_from_memory(mem); int code; /* when starting arg files (@ files) iodev_default is not yet set */ if (iodev == 0) iodev = (gx_io_device *)gx_io_device_table[0]; search_with_combine = false; } else { search_with_no_combine = starting_arg_file; search_with_combine = true; } Commit Message: CWE ID: CWE-200
lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p, const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile) { /* i_ctx_p is NULL running arg (@) files. * lib_path and mem are never NULL */ bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file; bool search_with_no_combine = false; bool search_with_combine = false; char fmode[2] = { 'r', 0}; gx_io_device *iodev = iodev_default(mem); gs_main_instance *minst = get_minst_from_memory(mem); int code; if (i_ctx_p && starting_arg_file) i_ctx_p->starting_arg_file = false; /* when starting arg files (@ files) iodev_default is not yet set */ if (iodev == 0) iodev = (gx_io_device *)gx_io_device_table[0]; search_with_combine = false; } else { search_with_no_combine = starting_arg_file; search_with_combine = true; }
165,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; viz::LocalSurfaceId old_surface_id = view_->GetLocalSurfaceId(); if (view_) view_->DidNavigate(); viz::LocalSurfaceId new_surface_id = view_->GetLocalSurfaceId(); if (old_surface_id == new_surface_id) return; } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); } Commit Message: Start rendering timer after first navigation Currently the new content rendering timer in the browser process, which clears an old page's contents 4 seconds after a navigation if the new page doesn't draw in that time, is not set on the first navigation for a top-level frame. This is problematic because content can exist before the first navigation, for instance if it was created by a javascript: URL. This CL removes the code that skips the timer activation on the first navigation. Bug: 844881 Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584 Reviewed-on: https://chromium-review.googlesource.com/1188589 Reviewed-by: Fady Samuel <fsamuel@chromium.org> Reviewed-by: ccameron <ccameron@chromium.org> Commit-Queue: Ken Buchanan <kenrb@chromium.org> Cr-Commit-Position: refs/heads/master@{#586913} CWE ID: CWE-20
void RenderWidgetHostImpl::DidNavigate(uint32_t next_source_id) { current_content_source_id_ = next_source_id; did_receive_first_frame_after_navigation_ = false; if (enable_surface_synchronization_) { visual_properties_ack_pending_ = false; if (view_) view_->DidNavigate(); } else { if (last_received_content_source_id_ >= current_content_source_id_) return; } if (!new_content_rendering_timeout_) return; new_content_rendering_timeout_->Start(new_content_rendering_delay_); }
172,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_write_chunks(struct svcxprt_rdma *xprt, struct rpcrdma_write_array *wr_ary, struct rpcrdma_msg *rdma_resp, struct svc_rqst *rqstp, struct svc_rdma_req_map *vec) { u32 xfer_len = rqstp->rq_res.page_len; int write_len; u32 xdr_off; int chunk_off; int chunk_no; int nchunks; struct rpcrdma_write_array *res_ary; int ret; res_ary = (struct rpcrdma_write_array *) &rdma_resp->rm_body.rm_chunks[1]; /* Write chunks start at the pagelist */ nchunks = be32_to_cpu(wr_ary->wc_nchunks); for (xdr_off = rqstp->rq_res.head[0].iov_len, chunk_no = 0; xfer_len && chunk_no < nchunks; chunk_no++) { struct rpcrdma_segment *arg_ch; u64 rs_offset; arg_ch = &wr_ary->wc_array[chunk_no].wc_target; write_len = min(xfer_len, be32_to_cpu(arg_ch->rs_length)); /* Prepare the response chunk given the length actually * written */ xdr_decode_hyper((__be32 *)&arg_ch->rs_offset, &rs_offset); svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no, arg_ch->rs_handle, arg_ch->rs_offset, write_len); chunk_off = 0; while (write_len) { ret = send_write(xprt, rqstp, be32_to_cpu(arg_ch->rs_handle), rs_offset + chunk_off, xdr_off, write_len, vec); if (ret <= 0) goto out_err; chunk_off += ret; xdr_off += ret; xfer_len -= ret; write_len -= ret; } } /* Update the req with the number of chunks actually used */ svc_rdma_xdr_encode_write_list(rdma_resp, chunk_no); return rqstp->rq_res.page_len; out_err: pr_err("svcrdma: failed to send write chunks, rc=%d\n", ret); return -EIO; } 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
static int send_write_chunks(struct svcxprt_rdma *xprt, /* Load the xdr_buf into the ctxt's sge array, and DMA map each * element as it is added. * * Returns the number of sge elements loaded on success, or * a negative errno on failure. */ static int svc_rdma_map_reply_msg(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, struct xdr_buf *xdr, __be32 *wr_lst) { unsigned int len, sge_no, remaining, page_off; struct page **ppages; unsigned char *base; u32 xdr_pad; int ret; sge_no = 1; ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++, xdr->head[0].iov_base, xdr->head[0].iov_len); if (ret < 0) return ret; /* If a Write chunk is present, the xdr_buf's page list * is not included inline. However the Upper Layer may * have added XDR padding in the tail buffer, and that * should not be included inline. */ if (wr_lst) { base = xdr->tail[0].iov_base; len = xdr->tail[0].iov_len; xdr_pad = xdr_padsize(xdr->page_len); if (len && xdr_pad) { base += xdr_pad; len -= xdr_pad; } goto tail; } ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT); page_off = xdr->page_base & ~PAGE_MASK; remaining = xdr->page_len; while (remaining) { len = min_t(u32, PAGE_SIZE - page_off, remaining); ret = svc_rdma_dma_map_page(rdma, ctxt, sge_no++, *ppages++, page_off, len); if (ret < 0) return ret; remaining -= len; page_off = 0; } base = xdr->tail[0].iov_base; len = xdr->tail[0].iov_len; tail: if (len) { ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++, base, len); if (ret < 0) return ret; } return sge_no - 1; }
168,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcPanoramiXGetScreenSize(ClientPtr client) { REQUEST(xPanoramiXGetScreenSizeReq); WindowPtr pWin; xPanoramiXGetScreenSizeReply rep; int rc; if (stuff->screen >= PanoramiXNumScreens) return BadMatch; REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq); rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; rep = (xPanoramiXGetScreenSizeReply) { .type = X_Reply, .sequenceNumber = client->sequence, .length = 0, /* screen dimensions */ .width = screenInfo.screens[stuff->screen]->width, .height = screenInfo.screens[stuff->screen]->height, .window = stuff->window, .screen = stuff->screen }; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.width); swapl(&rep.height); swapl(&rep.window); swapl(&rep.screen); } WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply), &rep); return Success; } Commit Message: CWE ID: CWE-20
ProcPanoramiXGetScreenSize(ClientPtr client) { REQUEST(xPanoramiXGetScreenSizeReq); WindowPtr pWin; xPanoramiXGetScreenSizeReply rep; int rc; REQUEST_SIZE_MATCH(xPanoramiXGetScreenSizeReq); if (stuff->screen >= PanoramiXNumScreens) return BadMatch; rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); if (rc != Success) return rc; rep = (xPanoramiXGetScreenSizeReply) { .type = X_Reply, .sequenceNumber = client->sequence, .length = 0, /* screen dimensions */ .width = screenInfo.screens[stuff->screen]->width, .height = screenInfo.screens[stuff->screen]->height, .window = stuff->window, .screen = stuff->screen }; if (client->swapped) { swaps(&rep.sequenceNumber); swapl(&rep.length); swapl(&rep.width); swapl(&rep.height); swapl(&rep.window); swapl(&rep.screen); } WriteToClient(client, sizeof(xPanoramiXGetScreenSizeReply), &rep); return Success; }
165,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BluetoothDeviceChromeOS::RequestPinCode( const dbus::ObjectPath& device_path, const PinCodeCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestPinCode"; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_REQUEST_PINCODE, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(pincode_callback_.is_null()); pincode_callback_ = callback; pairing_delegate_->RequestPinCode(this); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void BluetoothDeviceChromeOS::RequestPinCode(
171,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scoped_pixel_buffer_object::Init(CGLContextObj cgl_context, int size_in_bytes) { cgl_context_ = cgl_context; CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glGenBuffersARB(1, &pixel_buffer_object_); if (glGetError() == GL_NO_ERROR) { glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); if (glGetError() != GL_NO_ERROR) { Release(); } } else { cgl_context_ = NULL; pixel_buffer_object_ = 0; } return pixel_buffer_object_ != 0; } Commit Message: Workaround for bad driver issue with NVIDIA GeForce 7300 GT on Mac 10.5. BUG=87283 TEST=Run on a machine with NVIDIA GeForce 7300 GT on Mac 10.5 immediately after booting. Review URL: http://codereview.chromium.org/7373018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@92651 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool scoped_pixel_buffer_object::Init(CGLContextObj cgl_context, int size_in_bytes) { // The PBO path is only done on 10.6 (SnowLeopard) and above due to // a driver issue that was found on 10.5 // (specifically on a NVIDIA GeForce 7300 GT). // http://crbug.com/87283 if (base::mac::IsOSLeopardOrEarlier()) { return false; } cgl_context_ = cgl_context; CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glGenBuffersARB(1, &pixel_buffer_object_); if (glGetError() == GL_NO_ERROR) { glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); if (glGetError() != GL_NO_ERROR) { Release(); } } else { cgl_context_ = NULL; pixel_buffer_object_ = 0; } return pixel_buffer_object_ != 0; }
170,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } Commit Message: CWE ID: CWE-189
create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = (size_t)height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); }
165,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: perform_gamma_composition_tests(png_modifier *pm, int do_background, int expand_16) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Skip the non-alpha cases - there is no setting of a transparency colour at * present. */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0) { unsigned int i, j; /* Don't skip the i==j case here - it's relevant. */ for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) { gamma_composition_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], pm->use_input_precision, do_background, expand_16); if (fail(pm)) return; } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
perform_gamma_composition_tests(png_modifier *pm, int do_background, int expand_16) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Skip the non-alpha cases - there is no setting of a transparency colour at * present. * * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do, * however the palette case fails miserably so is commented out below. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_composition, pm->test_tRNS)) if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0 #if 0 /* TODO: FIXME */ /*TODO: FIXME: this should work */ || colour_type == 3 #endif || (colour_type != 3 && palette_number != 0)) { unsigned int i, j; /* Don't skip the i==j case here - it's relevant. */ for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) { gamma_composition_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], pm->use_input_precision, do_background, expand_16); if (fail(pm)) return; } } }
173,679
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: auth_select_file(struct sc_card *card, const struct sc_path *in_path, struct sc_file **file_out) { struct sc_path path; struct sc_file *tmp_file = NULL; size_t offs, ii; int rv; LOG_FUNC_CALLED(card->ctx); assert(card != NULL && in_path != NULL); memcpy(&path, in_path, sizeof(struct sc_path)); sc_log(card->ctx, "in_path; type=%d, path=%s, out %p", in_path->type, sc_print_path(in_path), file_out); sc_log(card->ctx, "current path; type=%d, path=%s", auth_current_df->path.type, sc_print_path(&auth_current_df->path)); if (auth_current_ef) sc_log(card->ctx, "current file; type=%d, path=%s", auth_current_ef->path.type, sc_print_path(&auth_current_ef->path)); if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) { sc_file_free(auth_current_ef); auth_current_ef = NULL; rv = iso_ops->select_file(card, &path, &tmp_file); LOG_TEST_RET(card->ctx, rv, "select file failed"); if (!tmp_file) return SC_ERROR_OBJECT_NOT_FOUND; if (path.type == SC_PATH_TYPE_PARENT) { memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path)); if (tmp_file->path.len > 2) tmp_file->path.len -= 2; sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { if (tmp_file->type == SC_FILE_TYPE_DF) { sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path); sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { sc_file_free(auth_current_ef); sc_file_dup(&auth_current_ef, tmp_file); sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path); } } if (file_out) sc_file_dup(file_out, tmp_file); sc_file_free(tmp_file); } else if (path.type == SC_PATH_TYPE_DF_NAME) { rv = iso_ops->select_file(card, &path, NULL); if (rv) { sc_file_free(auth_current_ef); auth_current_ef = NULL; } LOG_TEST_RET(card->ctx, rv, "select file failed"); } else { for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2) if (path.value[offs] != auth_current_df->path.value[offs] || path.value[offs + 1] != auth_current_df->path.value[offs + 1]) break; sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs); if (offs && offs < auth_current_df->path.len) { size_t deep = auth_current_df->path.len - offs; sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u", deep); for (ii=0; ii<deep; ii+=2) { struct sc_path tmp_path; memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_PARENT; rv = auth_select_file (card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } if (path.len - offs > 0) { struct sc_path tmp_path; memset(&tmp_path, 0, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_FILE_ID; tmp_path.len = 2; for (ii=0; ii < path.len - offs; ii+=2) { memcpy(tmp_path.value, path.value + offs + ii, 2); rv = auth_select_file(card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } else if (path.len - offs == 0 && file_out) { if (sc_compare_path(&path, &auth_current_df->path)) sc_file_dup(file_out, auth_current_df); else if (auth_current_ef) sc_file_dup(file_out, auth_current_ef); else LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF"); } } LOG_FUNC_RETURN(card->ctx, 0); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
auth_select_file(struct sc_card *card, const struct sc_path *in_path, struct sc_file **file_out) { struct sc_path path; struct sc_file *tmp_file = NULL; size_t offs, ii; int rv; LOG_FUNC_CALLED(card->ctx); assert(card != NULL && in_path != NULL); memcpy(&path, in_path, sizeof(struct sc_path)); if (!auth_current_df) return SC_ERROR_OBJECT_NOT_FOUND; sc_log(card->ctx, "in_path; type=%d, path=%s, out %p", in_path->type, sc_print_path(in_path), file_out); sc_log(card->ctx, "current path; type=%d, path=%s", auth_current_df->path.type, sc_print_path(&auth_current_df->path)); if (auth_current_ef) sc_log(card->ctx, "current file; type=%d, path=%s", auth_current_ef->path.type, sc_print_path(&auth_current_ef->path)); if (path.type == SC_PATH_TYPE_PARENT || path.type == SC_PATH_TYPE_FILE_ID) { sc_file_free(auth_current_ef); auth_current_ef = NULL; rv = iso_ops->select_file(card, &path, &tmp_file); LOG_TEST_RET(card->ctx, rv, "select file failed"); if (!tmp_file) return SC_ERROR_OBJECT_NOT_FOUND; if (path.type == SC_PATH_TYPE_PARENT) { memcpy(&tmp_file->path, &auth_current_df->path, sizeof(struct sc_path)); if (tmp_file->path.len > 2) tmp_file->path.len -= 2; sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { if (tmp_file->type == SC_FILE_TYPE_DF) { sc_concatenate_path(&tmp_file->path, &auth_current_df->path, &path); sc_file_free(auth_current_df); sc_file_dup(&auth_current_df, tmp_file); } else { sc_file_free(auth_current_ef); sc_file_dup(&auth_current_ef, tmp_file); sc_concatenate_path(&auth_current_ef->path, &auth_current_df->path, &path); } } if (file_out) sc_file_dup(file_out, tmp_file); sc_file_free(tmp_file); } else if (path.type == SC_PATH_TYPE_DF_NAME) { rv = iso_ops->select_file(card, &path, NULL); if (rv) { sc_file_free(auth_current_ef); auth_current_ef = NULL; } LOG_TEST_RET(card->ctx, rv, "select file failed"); } else { for (offs = 0; offs < path.len && offs < auth_current_df->path.len; offs += 2) if (path.value[offs] != auth_current_df->path.value[offs] || path.value[offs + 1] != auth_current_df->path.value[offs + 1]) break; sc_log(card->ctx, "offs %"SC_FORMAT_LEN_SIZE_T"u", offs); if (offs && offs < auth_current_df->path.len) { size_t deep = auth_current_df->path.len - offs; sc_log(card->ctx, "deep %"SC_FORMAT_LEN_SIZE_T"u", deep); for (ii=0; ii<deep; ii+=2) { struct sc_path tmp_path; memcpy(&tmp_path, &auth_current_df->path, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_PARENT; rv = auth_select_file (card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } if (path.len - offs > 0) { struct sc_path tmp_path; memset(&tmp_path, 0, sizeof(struct sc_path)); tmp_path.type = SC_PATH_TYPE_FILE_ID; tmp_path.len = 2; for (ii=0; ii < path.len - offs; ii+=2) { memcpy(tmp_path.value, path.value + offs + ii, 2); rv = auth_select_file(card, &tmp_path, file_out); LOG_TEST_RET(card->ctx, rv, "select file failed"); } } else if (path.len - offs == 0 && file_out) { if (sc_compare_path(&path, &auth_current_df->path)) sc_file_dup(file_out, auth_current_df); else if (auth_current_ef) sc_file_dup(file_out, auth_current_ef); else LOG_TEST_RET(card->ctx, SC_ERROR_INTERNAL, "No current EF"); } } LOG_FUNC_RETURN(card->ctx, 0); }
169,059
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); } Commit Message: disallow creation (of empty files) in read-only mode; reported by Michal Zalewski, feedback & ok deraadt@ CWE ID: CWE-269
process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT|O_TRUNC)) != 0)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); }
167,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 js_Ast *memberexp(js_State *J) { js_Ast *a; INCREC(); a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } DECREC(); return a; } Commit Message: CWE ID: CWE-674
static js_Ast *memberexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } POPREC(); return a; }
165,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum) { struct map_struct *buf; OFF_T i, len = st_p->st_size; md_context m; int32 remainder; int fd; memset(sum, 0, MAX_DIGEST_LEN); fd = do_open(fname, O_RDONLY, 0); if (fd == -1) return; buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK); switch (checksum_type) { case CSUM_MD5: md5_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK), CSUM_CHUNK); } remainder = (int32)(len - i); if (remainder > 0) md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); md5_result(&m, (uchar *)sum); break; case CSUM_MD4: case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: mdfour_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { } /* Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ remainder = (int32)(len - i); if (remainder > 0 || checksum_type != CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); mdfour_result(&m, (uchar *)sum); rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type); exit_cleanup(RERR_UNSUPPORTED); } close(fd); unmap_file(buf); } Commit Message: CWE ID: CWE-354
void file_checksum(const char *fname, const STRUCT_STAT *st_p, char *sum) { struct map_struct *buf; OFF_T i, len = st_p->st_size; md_context m; int32 remainder; int fd; memset(sum, 0, MAX_DIGEST_LEN); fd = do_open(fname, O_RDONLY, 0); if (fd == -1) return; buf = map_file(fd, len, MAX_MAP_SIZE, CSUM_CHUNK); switch (checksum_type) { case CSUM_MD5: md5_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { md5_update(&m, (uchar *)map_ptr(buf, i, CSUM_CHUNK), CSUM_CHUNK); } remainder = (int32)(len - i); if (remainder > 0) md5_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); md5_result(&m, (uchar *)sum); break; case CSUM_MD4: case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: mdfour_begin(&m); for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) { } /* Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ remainder = (int32)(len - i); if (remainder > 0 || checksum_type > CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)map_ptr(buf, i, remainder), remainder); mdfour_result(&m, (uchar *)sum); rprintf(FERROR, "invalid checksum-choice for the --checksum option (%d)\n", checksum_type); exit_cleanup(RERR_UNSUPPORTED); } close(fd); unmap_file(buf); }
164,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 install_local_socket(asocket* s) { adb_mutex_lock(&socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { local_socket_next_id = 1; } insert_local_socket(s, &local_socket_list); adb_mutex_unlock(&socket_list_lock); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
void install_local_socket(asocket* s) { std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); s->id = local_socket_next_id++; if (local_socket_next_id == 0) { fatal("local socket id overflow"); } insert_local_socket(s, &local_socket_list); }
174,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
void set_cfg_option(char *opt_string) { char *sep, *sep2, szSec[1024], szKey[1024], szVal[1024]; sep = strchr(opt_string, ':'); if (!sep) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep - opt_string; if (sepIdx >= sizeof(szSec)) { fprintf(stderr, "Badly formatted option %s - Section name is too long\n", opt_string); return; } strncpy(szSec, opt_string, sepIdx); szSec[sepIdx] = 0; } sep ++; sep2 = strchr(sep, '='); if (!sep2) { fprintf(stderr, "Badly formatted option %s - expected Section:Name=Value\n", opt_string); return; } { const size_t sepIdx = sep2 - sep; if (sepIdx >= sizeof(szKey)) { fprintf(stderr, "Badly formatted option %s - key name is too long\n", opt_string); return; } strncpy(szKey, sep, sepIdx); szKey[sepIdx] = 0; if (strlen(sep2 + 1) >= sizeof(szVal)) { fprintf(stderr, "Badly formatted option %s - value is too long\n", opt_string); return; } strcpy(szVal, sep2+1); } if (!stricmp(szKey, "*")) { if (stricmp(szVal, "null")) { fprintf(stderr, "Badly formatted option %s - expected Section:*=null\n", opt_string); return; } gf_cfg_del_section(cfg_file, szSec); return; } if (!stricmp(szVal, "null")) { szVal[0]=0; } gf_cfg_set_key(cfg_file, szSec, szKey, szVal[0] ? szVal : NULL); }
169,791