instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-20
int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi, false); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; }
169,413
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert3(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); c* (toc(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->convert3(); return JSValue::encode(jsUndefined()); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestObjPrototypeFunctionConvert3(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestObj::s_info)) return throwVMTypeError(exec); JSTestObj* castedThis = jsCast<JSTestObj*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestObj::s_info); TestObj* impl = static_cast<TestObj*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); c* (toc(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); impl->convert3(); return JSValue::encode(jsUndefined()); }
170,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_METHOD(Phar, offsetExists) { char *fname; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetExists) { char *fname; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_FALSE; } } if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) { /* none of these are real files, so they don't exist */ RETURN_FALSE; } RETURN_TRUE; } else { if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) { RETURN_TRUE; } RETURN_FALSE; } }
165,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb) { ext3_fsblk_t sb_block; char *options = (char *) *data; if (!options || strncmp(options, "sb=", 3) != 0) return 1; /* Default location */ options += 3; /*todo: use simple_strtoll with >32bit ext3 */ sb_block = simple_strtoul(options, &options, 0); if (*options && *options != ',') { ext3_msg(sb, "error: invalid sb specification: %s", (char *) *data); return 1; } if (*options == ',') options++; *data = (void *) options; return sb_block; } Commit Message: ext3: Fix format string issues ext3_msg() takes the printk prefix as the second parameter and the format string as the third parameter. Two callers of ext3_msg omit the prefix and pass the format string as the second parameter and the first parameter to the format string as the third parameter. In both cases this string comes from an arbitrary source. Which means the string may contain format string characters, which will lead to undefined and potentially harmful behavior. The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages in ext3") and is fixed by this patch. CC: [email protected] Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-20
static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb) { ext3_fsblk_t sb_block; char *options = (char *) *data; if (!options || strncmp(options, "sb=", 3) != 0) return 1; /* Default location */ options += 3; /*todo: use simple_strtoll with >32bit ext3 */ sb_block = simple_strtoul(options, &options, 0); if (*options && *options != ',') { ext3_msg(sb, KERN_ERR, "error: invalid sb specification: %s", (char *) *data); return 1; } if (*options == ',') options++; *data = (void *) options; return sb_block; }
166,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create( this, -1, requested_pos); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { // INVARIANT: //[ii, i) < pTP->m_pos //[i, j) ? //[j, jj) > pTP->m_pos Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); // const long long pos_ = pCluster->m_pos; // assert(pos_); // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); // assert(Cluster::HasBlockEntries(this, tp.m_pos)); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); //-1); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; }
174,280
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) { if (cfs_rq->load.weight) return false; if (cfs_rq->avg.load_sum) return false; if (cfs_rq->avg.util_sum) return false; if (cfs_rq->avg.runnable_load_sum) return false; return true; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-400
static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
169,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline bool unconditional(const struct ip6t_ip6 *ipv6) { static const struct ip6t_ip6 uncond; return memcmp(ipv6, &uncond, sizeof(uncond)) == 0; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
static inline bool unconditional(const struct ip6t_ip6 *ipv6) static inline bool unconditional(const struct ip6t_entry *e) { static const struct ip6t_ip6 uncond; return e->target_offset == sizeof(struct ip6t_entry) && memcmp(&e->ipv6, &uncond, sizeof(uncond)) == 0; }
167,376
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sas_destruct_devices(struct work_struct *work) { struct domain_device *dev, *n; struct sas_discovery_event *ev = to_sas_discovery_event(work); struct asd_sas_port *port = ev->port; clear_bit(DISCE_DESTRUCT, &port->disc.pending); list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID:
static void sas_destruct_devices(struct work_struct *work) void sas_destruct_devices(struct asd_sas_port *port) { struct domain_device *dev, *n; list_for_each_entry_safe(dev, n, &port->destroy_list, disco_list_node) { list_del_init(&dev->disco_list_node); sas_remove_children(&dev->rphy->dev); sas_rphy_delete(dev->rphy); sas_unregister_common_dev(port, dev); } }
169,384
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure(buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; } Commit Message: CWE ID:
hb_buffer_create (unsigned int pre_alloc_size) { hb_buffer_t *buffer; if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer)) return &_hb_buffer_nil; if (pre_alloc_size) hb_buffer_ensure (buffer, pre_alloc_size); buffer->unicode = &_hb_unicode_funcs_nil; return buffer; }
164,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); }
167,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { uint8_t ead, eal, fcs; uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset; uint8_t* p_start = p_data; uint16_t len; if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) { RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data); if (!ead) { RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)"); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data); RFCOMM_PARSE_LEN_FIELD(eal, len, p_data); p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */ p_buf->offset += (3 + !ead + !eal); /* handle credit if credit based flow control */ if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) && (p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) { p_frame->credit = *p_data++; p_buf->len--; p_buf->offset++; } else p_frame->credit = 0; if (p_buf->len != len) { RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len); return (RFC_EVENT_BAD_FRAME); } fcs = *(p_data + len); /* All control frames that we are sending are sent with P=1, expect */ /* reply with F=1 */ /* According to TS 07.10 spec ivalid frames are discarded without */ /* notification to the sender */ switch (p_frame->type) { case RFCOMM_SABME: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad SABME"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_SABME); case RFCOMM_UA: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UA"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_UA); case RFCOMM_DM: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DM"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DM); case RFCOMM_DISC: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DISC"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DISC); case RFCOMM_UIH: if (!RFCOMM_VALID_DLCI(p_frame->dlci)) { RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI"); return (RFC_EVENT_BAD_FRAME); } else if (!rfc_check_fcs(2, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UIH - FCS"); return (RFC_EVENT_BAD_FRAME); } else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) { /* we assume that this is ok to allow bad implementations to work */ RFCOMM_TRACE_ERROR("Bad UIH - response"); return (RFC_EVENT_UIH); } else return (RFC_EVENT_UIH); } return (RFC_EVENT_BAD_FRAME); } Commit Message: Add bound check for rfc_parse_data Bug: 78288018 Test: manual Change-Id: I44349cd22c141483d01bce0f5a2131b727d0feb0 (cherry picked from commit 6039cb7225733195192b396ad19c528800feb735) CWE ID: CWE-125
uint8_t rfc_parse_data(tRFC_MCB* p_mcb, MX_FRAME* p_frame, BT_HDR* p_buf) { uint8_t ead, eal, fcs; uint8_t* p_data = (uint8_t*)(p_buf + 1) + p_buf->offset; uint8_t* p_start = p_data; uint16_t len; if (p_buf->len < RFCOMM_CTRL_FRAME_LEN) { RFCOMM_TRACE_ERROR("Bad Length1: %d", p_buf->len); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_CTRL_FIELD(ead, p_frame->cr, p_frame->dlci, p_data); if (!ead) { RFCOMM_TRACE_ERROR("Bad Address(EA must be 1)"); return (RFC_EVENT_BAD_FRAME); } RFCOMM_PARSE_TYPE_FIELD(p_frame->type, p_frame->pf, p_data); eal = *(p_data)&RFCOMM_EA; len = *(p_data)++ >> RFCOMM_SHIFT_LENGTH1; if (eal == 0 && p_buf->len < RFCOMM_CTRL_FRAME_LEN) { len += (*(p_data)++ << RFCOMM_SHIFT_LENGTH2); } else if (eal == 0) { RFCOMM_TRACE_ERROR("Bad Length when EAL = 0: %d", p_buf->len); android_errorWriteLog(0x534e4554, "78288018"); return RFC_EVENT_BAD_FRAME; } p_buf->len -= (3 + !ead + !eal + 1); /* Additional 1 for FCS */ p_buf->offset += (3 + !ead + !eal); /* handle credit if credit based flow control */ if ((p_mcb->flow == PORT_FC_CREDIT) && (p_frame->type == RFCOMM_UIH) && (p_frame->dlci != RFCOMM_MX_DLCI) && (p_frame->pf == 1)) { p_frame->credit = *p_data++; p_buf->len--; p_buf->offset++; } else p_frame->credit = 0; if (p_buf->len != len) { RFCOMM_TRACE_ERROR("Bad Length2 %d %d", p_buf->len, len); return (RFC_EVENT_BAD_FRAME); } fcs = *(p_data + len); /* All control frames that we are sending are sent with P=1, expect */ /* reply with F=1 */ /* According to TS 07.10 spec ivalid frames are discarded without */ /* notification to the sender */ switch (p_frame->type) { case RFCOMM_SABME: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad SABME"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_SABME); case RFCOMM_UA: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UA"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_UA); case RFCOMM_DM: if (RFCOMM_FRAME_IS_CMD(p_mcb->is_initiator, p_frame->cr) || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DM"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DM); case RFCOMM_DISC: if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr) || !p_frame->pf || len || !RFCOMM_VALID_DLCI(p_frame->dlci) || !rfc_check_fcs(RFCOMM_CTRL_FRAME_LEN, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad DISC"); return (RFC_EVENT_BAD_FRAME); } else return (RFC_EVENT_DISC); case RFCOMM_UIH: if (!RFCOMM_VALID_DLCI(p_frame->dlci)) { RFCOMM_TRACE_ERROR("Bad UIH - invalid DLCI"); return (RFC_EVENT_BAD_FRAME); } else if (!rfc_check_fcs(2, p_start, fcs)) { RFCOMM_TRACE_ERROR("Bad UIH - FCS"); return (RFC_EVENT_BAD_FRAME); } else if (RFCOMM_FRAME_IS_RSP(p_mcb->is_initiator, p_frame->cr)) { /* we assume that this is ok to allow bad implementations to work */ RFCOMM_TRACE_ERROR("Bad UIH - response"); return (RFC_EVENT_UIH); } else return (RFC_EVENT_UIH); } return (RFC_EVENT_BAD_FRAME); }
174,612
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); } Commit Message: Do not consider a CR by itself as a valid line terminator Varnish (prior to version 4.0) was not following the standard with regard to line separator. Spotted and analyzed by: Régis Leroy [regilero] [email protected] CWE ID:
http_rxchunk(struct http *hp) { char *q; int l, i; l = hp->prxbuf; do (void)http_rxchar(hp, 1, 0); while (hp->rxbuf[hp->prxbuf - 1] != '\n'); vtc_dump(hp->vl, 4, "len", hp->rxbuf + l, -1); i = strtoul(hp->rxbuf + l, &q, 16); bprintf(hp->chunklen, "%d", i); if ((q == hp->rxbuf + l) || (*q != '\0' && !vct_islws(*q))) { vtc_log(hp->vl, hp->fatal, "chunked fail %02x @ %d", *q, q - (hp->rxbuf + l)); } assert(q != hp->rxbuf + l); assert(*q == '\0' || vct_islws(*q)); hp->prxbuf = l; if (i > 0) { (void)http_rxchar(hp, i, 0); vtc_dump(hp->vl, 4, "chunk", hp->rxbuf + l, i); } l = hp->prxbuf; (void)http_rxchar(hp, 2, 0); if(!vct_iscrlf(&hp->rxbuf[l])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[0] = %02x", hp->rxbuf[l] & 0xff); if(!vct_iscrlf(&hp->rxbuf[l + 1])) vtc_log(hp->vl, hp->fatal, "Wrong chunk tail[1] = %02x", hp->rxbuf[l + 1] & 0xff); hp->prxbuf = l; hp->rxbuf[l] = '\0'; return (i); }
169,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _gnutls_ciphertext2compressed (gnutls_session_t session, opaque * compress_data, int compress_size, gnutls_datum_t ciphertext, uint8_t type, record_parameters_st * params) { uint8_t MAC[MAX_HASH_SIZE]; uint16_t c_length; uint8_t pad; int length; uint16_t blocksize; int ret, i, pad_failed = 0; opaque preamble[PREAMBLE_SIZE]; int preamble_size; int ver = gnutls_protocol_get_version (session); int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (params->cipher_algorithm)) { case CIPHER_STREAM: if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } length = ciphertext.size - hash_size; break; case CIPHER_BLOCK: if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0)) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } /* ignore the IV in TLS 1.1. */ if (_gnutls_version_has_explicit_iv (session->security_parameters.version)) { ciphertext.size -= blocksize; ciphertext.data += blocksize; if (ciphertext.size == 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } } pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ if ((int) pad > (int) ciphertext.size - hash_size) if ((int) pad > (int) ciphertext.size - hash_size) { gnutls_assert (); _gnutls_record_log ("REC[%p]: Short record length %d > %d - %d (under attack?)\n", session, pad, ciphertext.size, hash_size); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; } length = ciphertext.size - hash_size - pad; /* Check the pading bytes (TLS 1.x) */ if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0) for (i = 2; i < pad; i++) { if (ciphertext.data[ciphertext.size - i] != ciphertext.data[ciphertext.size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } break; default: gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } if (length < 0) length = 0; c_length = _gnutls_conv_uint16 ((uint16_t) length); /* Pass the type, version, length and compressed through * MAC. */ if (params->mac_algorithm != GNUTLS_MAC_NULL) { digest_hd_st td; ret = mac_init (&td, params->mac_algorithm, params->read.mac_secret.data, params->read.mac_secret.size, ver); if (ret < 0) { gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } preamble_size = make_preamble (UINT64DATA (params->read.sequence_number), type, c_length, ver, preamble); mac_hash (&td, preamble, preamble_size, ver); if (length > 0) mac_hash (&td, ciphertext.data, length, ver); mac_deinit (&td, MAC, ver); } /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ if (pad_failed != 0) { gnutls_assert (); return pad_failed; } /* HMAC was not the same. */ if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } /* copy the decrypted stuff to compress_data. */ if (compress_size < length) { gnutls_assert (); return GNUTLS_E_DECOMPRESSION_FAILED; } memcpy (compress_data, ciphertext.data, length); return length; } Commit Message: CWE ID: CWE-310
_gnutls_ciphertext2compressed (gnutls_session_t session, opaque * compress_data, int compress_size, gnutls_datum_t ciphertext, uint8_t type, record_parameters_st * params) { uint8_t MAC[MAX_HASH_SIZE]; uint16_t c_length; uint8_t pad; int length; uint16_t blocksize; int ret, i, pad_failed = 0; opaque preamble[PREAMBLE_SIZE]; int preamble_size; int ver = gnutls_protocol_get_version (session); int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); /* actual decryption (inplace) */ switch (_gnutls_cipher_is_block (params->cipher_algorithm)) { case CIPHER_STREAM: if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } length = ciphertext.size - hash_size; break; case CIPHER_BLOCK: if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0)) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } if ((ret = _gnutls_cipher_decrypt (&params->read.cipher_state, ciphertext.data, ciphertext.size)) < 0) { gnutls_assert (); return ret; } /* ignore the IV in TLS 1.1. */ if (_gnutls_version_has_explicit_iv (session->security_parameters.version)) { ciphertext.size -= blocksize; ciphertext.data += blocksize; } if (ciphertext.size < hash_size) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ if ((int) pad > (int) ciphertext.size - hash_size) if ((int) pad > (int) ciphertext.size - hash_size) { gnutls_assert (); _gnutls_record_log ("REC[%p]: Short record length %d > %d - %d (under attack?)\n", session, pad, ciphertext.size, hash_size); /* We do not fail here. We check below for the * the pad_failed. If zero means success. */ pad_failed = GNUTLS_E_DECRYPTION_FAILED; } length = ciphertext.size - hash_size - pad; /* Check the pading bytes (TLS 1.x) */ if (_gnutls_version_has_variable_padding (ver) && pad_failed == 0) for (i = 2; i < pad; i++) { if (ciphertext.data[ciphertext.size - i] != ciphertext.data[ciphertext.size - 1]) pad_failed = GNUTLS_E_DECRYPTION_FAILED; } break; default: gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } if (length < 0) length = 0; c_length = _gnutls_conv_uint16 ((uint16_t) length); /* Pass the type, version, length and compressed through * MAC. */ if (params->mac_algorithm != GNUTLS_MAC_NULL) { digest_hd_st td; ret = mac_init (&td, params->mac_algorithm, params->read.mac_secret.data, params->read.mac_secret.size, ver); if (ret < 0) { gnutls_assert (); return GNUTLS_E_INTERNAL_ERROR; } preamble_size = make_preamble (UINT64DATA (params->read.sequence_number), type, c_length, ver, preamble); mac_hash (&td, preamble, preamble_size, ver); if (length > 0) mac_hash (&td, ciphertext.data, length, ver); mac_deinit (&td, MAC, ver); } /* This one was introduced to avoid a timing attack against the TLS * 1.0 protocol. */ if (pad_failed != 0) { gnutls_assert (); return pad_failed; } /* HMAC was not the same. */ if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0) { gnutls_assert (); return GNUTLS_E_DECRYPTION_FAILED; } /* copy the decrypted stuff to compress_data. */ if (compress_size < length) { gnutls_assert (); return GNUTLS_E_DECOMPRESSION_FAILED; } memcpy (compress_data, ciphertext.data, length); return length; }
165,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct dentry *parent; struct iattr attr; struct rpc_cred *cred; struct nfs4_state *state; struct dentry *res; if (nd->flags & LOOKUP_CREATE) { attr.ia_mode = nd->intent.open.create_mode; attr.ia_valid = ATTR_MODE; if (!IS_POSIXACL(dir)) attr.ia_mode &= ~current->fs->umask; } else { attr.ia_valid = 0; BUG_ON(nd->intent.open.flags & O_CREAT); } cred = rpc_lookup_cred(); if (IS_ERR(cred)) return (struct dentry *)cred; parent = dentry->d_parent; /* Protect against concurrent sillydeletes */ nfs_block_sillyrename(parent); state = nfs4_do_open(dir, &path, nd->intent.open.flags, &attr, cred); put_rpccred(cred); if (IS_ERR(state)) { if (PTR_ERR(state) == -ENOENT) { d_add(dentry, NULL); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); } nfs_unblock_sillyrename(parent); return (struct dentry *)state; } res = d_add_unique(dentry, igrab(state->inode)); if (res != NULL) path.dentry = res; nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir)); nfs_unblock_sillyrename(parent); nfs4_intent_set_file(nd, &path, state); return res; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
nfs4_atomic_open(struct inode *dir, struct dentry *dentry, struct nameidata *nd) { struct path path = { .mnt = nd->path.mnt, .dentry = dentry, }; struct dentry *parent; struct iattr attr; struct rpc_cred *cred; struct nfs4_state *state; struct dentry *res; fmode_t fmode = nd->intent.open.flags & (FMODE_READ | FMODE_WRITE | FMODE_EXEC); if (nd->flags & LOOKUP_CREATE) { attr.ia_mode = nd->intent.open.create_mode; attr.ia_valid = ATTR_MODE; if (!IS_POSIXACL(dir)) attr.ia_mode &= ~current->fs->umask; } else { attr.ia_valid = 0; BUG_ON(nd->intent.open.flags & O_CREAT); } cred = rpc_lookup_cred(); if (IS_ERR(cred)) return (struct dentry *)cred; parent = dentry->d_parent; /* Protect against concurrent sillydeletes */ nfs_block_sillyrename(parent); state = nfs4_do_open(dir, &path, fmode, nd->intent.open.flags, &attr, cred); put_rpccred(cred); if (IS_ERR(state)) { if (PTR_ERR(state) == -ENOENT) { d_add(dentry, NULL); nfs_set_verifier(dentry, nfs_save_change_attribute(dir)); } nfs_unblock_sillyrename(parent); return (struct dentry *)state; } res = d_add_unique(dentry, igrab(state->inode)); if (res != NULL) path.dentry = res; nfs_set_verifier(path.dentry, nfs_save_change_attribute(dir)); nfs_unblock_sillyrename(parent); nfs4_intent_set_file(nd, &path, state, fmode); return res; }
165,688
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport) { struct keydata *keyptr = get_keyptr(); u32 hash[4]; /* * Pick a unique starting offset for each ephemeral port search * (saddr, daddr, dport) and 48bits of random data. */ hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = (__force u32)dport ^ keyptr->secret[10]; hash[3] = keyptr->secret[11]; return half_md4_transform(hash, keyptr->secret); } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
165,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: " "empty extents btree\n"); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node %d too large for file", cur_node); free(node); return 1; } cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_traverse: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 " ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { break; } } if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: did not find any keys in index node %d", cur_node); is_done = 1; break; } if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: node %d references itself as next node", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } } if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: moving forward to next leaf"); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32 " (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; } Commit Message: Merge pull request #1374 from JordyZomer/develop Fix CVE-2018-19497. CWE ID: CWE-125
hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: " "empty extents btree\n"); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node %d too large for file", cur_node); free(node); return 1; } cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_traverse: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if (keylen >= nodesize - rec_off) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, (nodesize - rec_off)); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 " ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { break; } } if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: did not find any keys in index node %d", cur_node); is_done = 1; break; } if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: node %d references itself as next node", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } } if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: moving forward to next leaf"); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32 " (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; }
168,974
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { storage()->MarkEntryAsForeign( main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url, cache_document_was_loaded_from); SelectCache(document_url, kAppCacheNoCacheId, GURL()); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::MarkAsForeignEntry(const GURL& document_url, bool AppCacheHost::MarkAsForeignEntry(const GURL& document_url, int64 cache_document_was_loaded_from) { if (was_select_cache_called_) return false; storage()->MarkEntryAsForeign( main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url, cache_document_was_loaded_from); SelectCache(document_url, kAppCacheNoCacheId, GURL()); return true; }
171,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) { if (prev_options != NULL) { *prev_options = MBREX(regex_default_options); } if (prev_syntax != NULL) { *prev_syntax = MBREX(regex_default_syntax); } MBREX(regex_default_options) = options; MBREX(regex_default_syntax) = syntax; } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) static void _php_mb_regex_set_options(OnigOptionType options, OnigSyntaxType *syntax, OnigOptionType *prev_options, OnigSyntaxType **prev_syntax TSRMLS_DC) { if (prev_options != NULL) { *prev_options = MBREX(regex_default_options); } if (prev_syntax != NULL) { *prev_syntax = MBREX(regex_default_syntax); } MBREX(regex_default_options) = options; MBREX(regex_default_syntax) = syntax; }
167,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ { /* This is how the time string is formatted: snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ time_t ret; struct tm thetime; char * strbuf; char * thestr; long gmadjust = 0; if (timestr->length < 13) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data); return (time_t)-1; } strbuf = estrdup((char *)timestr->data); memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ thestr = strbuf + timestr->length - 3; thetime.tm_sec = atoi(thestr); *thestr = '\0'; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } thetime.tm_isdst = -1; ret = mktime(&thetime); #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #else /* ** If correcting for daylight savings time, we set the adjustment to ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and ** set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); #endif ret += gmadjust; efree(strbuf); return ret; } /* }}} */ Commit Message: CWE ID: CWE-119
static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ { /* This is how the time string is formatted: snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100, ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); */ time_t ret; struct tm thetime; char * strbuf; char * thestr; long gmadjust = 0; if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal ASN1 data type for timestamp"); return (time_t)-1; } if (ASN1_STRING_length(timestr) != strlen(ASN1_STRING_data(timestr))) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "illegal length in timestamp"); return (time_t)-1; } if (ASN1_STRING_length(timestr) < 13) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to parse time string %s correctly", timestr->data); return (time_t)-1; } strbuf = estrdup((char *)ASN1_STRING_data(timestr)); memset(&thetime, 0, sizeof(thetime)); /* we work backwards so that we can use atoi more easily */ thestr = strbuf + ASN1_STRING_length(timestr) - 3; thetime.tm_sec = atoi(thestr); *thestr = '\0'; thetime.tm_mon = atoi(thestr)-1; *thestr = '\0'; thestr -= 2; thetime.tm_year = atoi(thestr); if (thetime.tm_year < 68) { thetime.tm_year += 100; } thetime.tm_isdst = -1; ret = mktime(&thetime); #if HAVE_TM_GMTOFF gmadjust = thetime.tm_gmtoff; #else /* ** If correcting for daylight savings time, we set the adjustment to ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and ** set the adjustment to the main timezone + 3600 seconds. */ gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); #endif ret += gmadjust; efree(strbuf); return ret; } /* }}} */
164,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype) krb5_context context; OM_uint32 *minor_status; krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; int bodysize; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_error_code code; int conflen = 0; int signalg; int sealalg; gss_buffer_desc token; krb5_checksum cksum; krb5_checksum md5cksum; krb5_data plaind; char *data_ptr; unsigned char *plain; unsigned int cksum_len = 0; size_t plainlen; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; if (toktype == KG_TOK_SEAL_MSG) { message_buffer->length = 0; message_buffer->value = NULL; } /* get the sign and seal algorithms */ signalg = ptr[0] + (ptr[1]<<8); sealalg = ptr[2] + (ptr[3]<<8); /* Sanity checks */ if ((ptr[4] != 0xff) || (ptr[5] != 0xff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((toktype != KG_TOK_SEAL_MSG) && (sealalg != 0xffff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* in the current spec, there is only one valid seal algorithm per key type, so a simple comparison is ok */ if ((toktype == KG_TOK_SEAL_MSG) && !((sealalg == 0xffff) || (sealalg == ctx->sealalg))) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* there are several mappings of seal algorithms to sign algorithms, but few enough that we can try them all. */ if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_SEAL_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction, &seqnum))) { *minor_status = code; return(GSS_S_BAD_SIG); } /* decode the message, if SEAL */ if (toktype == KG_TOK_SEAL_MSG) { size_t tmsglen = bodysize-(14+cksum_len); if (sealalg != 0xffff) { if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) { *minor_status = ENOMEM; return(GSS_S_FAILURE); } if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; int i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } assert (enc_key->length == 16); for (i = 0; i <= 15; i++) ((char *) enc_key->contents)[i] ^=0xf0; code = kg_arcfour_docrypt (enc_key, 0, &bigend_seqnum[0], 4, ptr+14+cksum_len, tmsglen, plain); krb5_free_keyblock (context, enc_key); } else { code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL, ptr+14+cksum_len, plain, tmsglen); } if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } } else { plain = ptr+14+cksum_len; } plainlen = tmsglen; conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); token.length = tmsglen - conflen - plain[tmsglen-1]; if (token.length) { if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) { if (sealalg != 0xffff) xfree(plain); *minor_status = ENOMEM; return(GSS_S_FAILURE); } memcpy(token.value, plain+conflen, token.length); } else { token.value = NULL; } } else if (toktype == KG_TOK_SIGN_MSG) { token = *message_buffer; plain = token.value; plainlen = token.length; } else { token.length = 0; token.value = NULL; plain = token.value; plainlen = token.length; } /* compute the checksum of the message */ /* initialize the the cksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort (); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code) return(code); md5cksum.length = sumlen; switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code) { krb5_free_checksum_contents(context, &md5cksum); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (signalg == 0) cksum.length = 8; else cksum.length = 16; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_MD2_5: if (!ctx->seed_init && (code = kg_make_seed(context, ctx->subkey, ctx->seed))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed)); (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen); plaind.length = 8 + sizeof(ctx->seed) + plainlen; plaind.data = data_ptr; krb5_free_checksum_contents(context, &md5cksum); code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, 8); /* Falls through to defective-token?? */ default: *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; } krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); /* compare the computed checksum against the transmitted checksum */ if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = 0; return(GSS_S_BAD_SIG); } /* it got through unscathed. Make sure the context is unexpired */ if (toktype == KG_TOK_SEAL_MSG) *message_buffer = token; if (conf_state) *conf_state = (sealalg != 0xffff); if (qop_state) *qop_state = GSS_C_QOP_DEFAULT; /* do sequencing checks */ if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { if (toktype == KG_TOK_SEAL_MSG) { gssalloc_free(token.value); message_buffer->value = NULL; message_buffer->length = 0; } *minor_status = (OM_uint32)G_BAD_DIRECTION; return(GSS_S_BAD_SIG); } retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum); /* success or ordering violation */ *minor_status = 0; return(retval); } Commit Message: Handle invalid RFC 1964 tokens [CVE-2014-4341...] Detect the following cases which would otherwise cause invalid memory accesses and/or integer underflow: * An RFC 1964 token being processed by an RFC 4121-only context [CVE-2014-4342] * A header with fewer than 22 bytes after the token ID or an incomplete checksum [CVE-2014-4341 CVE-2014-4342] * A ciphertext shorter than the confounder [CVE-2014-4341] * A declared padding length longer than the plaintext [CVE-2014-4341] If we detect a bad pad byte, continue on to compute the checksum to avoid creating a padding oracle, but treat the checksum as invalid even if it compares equal. CVE-2014-4341: In MIT krb5, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when attempting to read beyond the end of a buffer. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C CVE-2014-4342: In MIT krb5 releases krb5-1.7 and later, an unauthenticated remote attacker with the ability to inject packets into a legitimately established GSSAPI application session can cause a program crash due to invalid memory references when reading beyond the end of a buffer or by causing a null pointer dereference. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:P/E:POC/RL:OF/RC:C [[email protected]: CVE summaries, CVSS] (cherry picked from commit fb99962cbd063ac04c9a9d2cc7c75eab73f3533d) ticket: 7949 version_fixed: 1.12.2 status: resolved CWE ID: CWE-119
kg_unseal_v1(context, minor_status, ctx, ptr, bodysize, message_buffer, conf_state, qop_state, toktype) krb5_context context; OM_uint32 *minor_status; krb5_gss_ctx_id_rec *ctx; unsigned char *ptr; int bodysize; gss_buffer_t message_buffer; int *conf_state; gss_qop_t *qop_state; int toktype; { krb5_error_code code; int conflen = 0; int signalg; int sealalg; int bad_pad = 0; gss_buffer_desc token; krb5_checksum cksum; krb5_checksum md5cksum; krb5_data plaind; char *data_ptr; unsigned char *plain; unsigned int cksum_len = 0; size_t plainlen; int direction; krb5_ui_4 seqnum; OM_uint32 retval; size_t sumlen; size_t padlen; krb5_keyusage sign_usage = KG_USAGE_SIGN; if (toktype == KG_TOK_SEAL_MSG) { message_buffer->length = 0; message_buffer->value = NULL; } /* Sanity checks */ if (ctx->seq == NULL) { /* ctx was established using a newer enctype, and cannot process RFC * 1964 tokens. */ *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((bodysize < 22) || (ptr[4] != 0xff) || (ptr[5] != 0xff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } signalg = ptr[0] + (ptr[1]<<8); sealalg = ptr[2] + (ptr[3]<<8); if ((toktype != KG_TOK_SEAL_MSG) && (sealalg != 0xffff)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* in the current spec, there is only one valid seal algorithm per key type, so a simple comparison is ok */ if ((toktype == KG_TOK_SEAL_MSG) && !((sealalg == 0xffff) || (sealalg == ctx->sealalg))) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* there are several mappings of seal algorithms to sign algorithms, but few enough that we can try them all. */ if ((ctx->sealalg == SEAL_ALG_NONE && signalg > 1) || (ctx->sealalg == SEAL_ALG_1 && signalg != SGN_ALG_3) || (ctx->sealalg == SEAL_ALG_DES3KD && signalg != SGN_ALG_HMAC_SHA1_DES3_KD)|| (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4 && signalg != SGN_ALG_HMAC_MD5)) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_HMAC_MD5: cksum_len = 8; if (toktype != KG_TOK_SEAL_MSG) sign_usage = 15; break; case SGN_ALG_3: cksum_len = 16; break; case SGN_ALG_HMAC_SHA1_DES3_KD: cksum_len = 20; break; default: *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } if ((size_t)bodysize < 14 + cksum_len) { *minor_status = 0; return GSS_S_DEFECTIVE_TOKEN; } /* get the token parameters */ if ((code = kg_get_seq_num(context, ctx->seq, ptr+14, ptr+6, &direction, &seqnum))) { *minor_status = code; return(GSS_S_BAD_SIG); } /* decode the message, if SEAL */ if (toktype == KG_TOK_SEAL_MSG) { size_t tmsglen = bodysize-(14+cksum_len); if (sealalg != 0xffff) { if ((plain = (unsigned char *) xmalloc(tmsglen)) == NULL) { *minor_status = ENOMEM; return(GSS_S_FAILURE); } if (ctx->sealalg == SEAL_ALG_MICROSOFT_RC4) { unsigned char bigend_seqnum[4]; krb5_keyblock *enc_key; int i; store_32_be(seqnum, bigend_seqnum); code = krb5_k_key_keyblock(context, ctx->enc, &enc_key); if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } assert (enc_key->length == 16); for (i = 0; i <= 15; i++) ((char *) enc_key->contents)[i] ^=0xf0; code = kg_arcfour_docrypt (enc_key, 0, &bigend_seqnum[0], 4, ptr+14+cksum_len, tmsglen, plain); krb5_free_keyblock (context, enc_key); } else { code = kg_decrypt(context, ctx->enc, KG_USAGE_SEAL, NULL, ptr+14+cksum_len, plain, tmsglen); } if (code) { xfree(plain); *minor_status = code; return(GSS_S_FAILURE); } } else { plain = ptr+14+cksum_len; } plainlen = tmsglen; conflen = kg_confounder_size(context, ctx->enc->keyblock.enctype); if (tmsglen < conflen) { if (sealalg != 0xffff) xfree(plain); *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); } padlen = plain[tmsglen - 1]; if (tmsglen - conflen < padlen) { /* Don't error out yet, to avoid padding oracle attacks. We will * treat this as a checksum failure later on. */ padlen = 0; bad_pad = 1; } token.length = tmsglen - conflen - padlen; if (token.length) { if ((token.value = (void *) gssalloc_malloc(token.length)) == NULL) { if (sealalg != 0xffff) xfree(plain); *minor_status = ENOMEM; return(GSS_S_FAILURE); } memcpy(token.value, plain+conflen, token.length); } else { token.value = NULL; } } else if (toktype == KG_TOK_SIGN_MSG) { token = *message_buffer; plain = token.value; plainlen = token.length; } else { token.length = 0; token.value = NULL; plain = token.value; plainlen = token.length; } /* compute the checksum of the message */ /* initialize the the cksum */ switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_MD2_5: case SGN_ALG_DES_MAC: case SGN_ALG_3: md5cksum.checksum_type = CKSUMTYPE_RSA_MD5; break; case SGN_ALG_HMAC_MD5: md5cksum.checksum_type = CKSUMTYPE_HMAC_MD5_ARCFOUR; break; case SGN_ALG_HMAC_SHA1_DES3_KD: md5cksum.checksum_type = CKSUMTYPE_HMAC_SHA1_DES3; break; default: abort (); } code = krb5_c_checksum_length(context, md5cksum.checksum_type, &sumlen); if (code) return(code); md5cksum.length = sumlen; switch (signalg) { case SGN_ALG_DES_MAC_MD5: case SGN_ALG_3: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = kg_encrypt_inplace(context, ctx->seq, KG_USAGE_SEAL, (g_OID_equal(ctx->mech_used, gss_mech_krb5_old) ? ctx->seq->keyblock.contents : NULL), md5cksum.contents, 16); if (code) { krb5_free_checksum_contents(context, &md5cksum); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (signalg == 0) cksum.length = 8; else cksum.length = 16; cksum.contents = md5cksum.contents + 16 - cksum.length; code = k5_bcmp(cksum.contents, ptr + 14, cksum.length); break; case SGN_ALG_MD2_5: if (!ctx->seed_init && (code = kg_make_seed(context, ctx->subkey, ctx->seed))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return GSS_S_FAILURE; } if (! (data_ptr = xmalloc(sizeof(ctx->seed) + 8 + plainlen))) { krb5_free_checksum_contents(context, &md5cksum); if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, ctx->seed, sizeof(ctx->seed)); (void) memcpy(data_ptr+8+sizeof(ctx->seed), plain, plainlen); plaind.length = 8 + sizeof(ctx->seed) + plainlen; plaind.data = data_ptr; krb5_free_checksum_contents(context, &md5cksum); code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (sealalg == 0) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, 8); /* Falls through to defective-token?? */ default: *minor_status = 0; return(GSS_S_DEFECTIVE_TOKEN); case SGN_ALG_HMAC_SHA1_DES3_KD: case SGN_ALG_HMAC_MD5: /* compute the checksum of the message */ /* 8 = bytes of token body to be checksummed according to spec */ if (! (data_ptr = xmalloc(8 + plainlen))) { if (sealalg != 0xffff) xfree(plain); if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = ENOMEM; return(GSS_S_FAILURE); } (void) memcpy(data_ptr, ptr-2, 8); (void) memcpy(data_ptr+8, plain, plainlen); plaind.length = 8 + plainlen; plaind.data = data_ptr; code = krb5_k_make_checksum(context, md5cksum.checksum_type, ctx->seq, sign_usage, &plaind, &md5cksum); xfree(data_ptr); if (code) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = code; return(GSS_S_FAILURE); } code = k5_bcmp(md5cksum.contents, ptr + 14, cksum_len); break; } krb5_free_checksum_contents(context, &md5cksum); if (sealalg != 0xffff) xfree(plain); /* compare the computed checksum against the transmitted checksum */ if (code || bad_pad) { if (toktype == KG_TOK_SEAL_MSG) gssalloc_free(token.value); *minor_status = 0; return(GSS_S_BAD_SIG); } /* it got through unscathed. Make sure the context is unexpired */ if (toktype == KG_TOK_SEAL_MSG) *message_buffer = token; if (conf_state) *conf_state = (sealalg != 0xffff); if (qop_state) *qop_state = GSS_C_QOP_DEFAULT; /* do sequencing checks */ if ((ctx->initiate && direction != 0xff) || (!ctx->initiate && direction != 0)) { if (toktype == KG_TOK_SEAL_MSG) { gssalloc_free(token.value); message_buffer->value = NULL; message_buffer->length = 0; } *minor_status = (OM_uint32)G_BAD_DIRECTION; return(GSS_S_BAD_SIG); } retval = g_order_check(&(ctx->seqstate), (gssint_uint64)seqnum); /* success or ordering violation */ *minor_status = 0; return(retval); }
166,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: RGBA32 AXNodeObject::colorValue() const { if (!isHTMLInputElement(getNode()) || !isColorWell()) return AXObject::colorValue(); HTMLInputElement* input = toHTMLInputElement(getNode()); const AtomicString& type = input->getAttribute(typeAttr); if (!equalIgnoringCase(type, "color")) return AXObject::colorValue(); Color color; bool success = color.setFromString(input->value()); DCHECK(success); return color.rgb(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
RGBA32 AXNodeObject::colorValue() const { if (!isHTMLInputElement(getNode()) || !isColorWell()) return AXObject::colorValue(); HTMLInputElement* input = toHTMLInputElement(getNode()); const AtomicString& type = input->getAttribute(typeAttr); if (!equalIgnoringASCIICase(type, "color")) return AXObject::colorValue(); Color color; bool success = color.setFromString(input->value()); DCHECK(success); return color.rgb(); }
171,910
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLInputElement::HandleBlurEvent() { input_type_->DisableSecureTextInput(); input_type_view_->HandleBlurEvent(); } Commit Message: MacViews: Enable secure text input for password Textfields. In Cocoa the NSTextInputContext automatically enables secure text input when activated and it's in the secure text entry mode. RenderWidgetHostViewMac did the similar thing for ages following the WebKit example. views::Textfield needs to do the same thing in a fashion that's sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions are possible when the Textfield gets focus, activates the secure text input mode and the RWHVM loses focus immediately afterwards and disables the secure text input instead of leaving it in the enabled state. BUG=818133,677220 Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b Reviewed-on: https://chromium-review.googlesource.com/943064 Commit-Queue: Michail Pishchagin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: Peter Kasting <[email protected]> Cr-Commit-Position: refs/heads/master@{#542517} CWE ID:
void HTMLInputElement::HandleBlurEvent() { input_type_view_->HandleBlurEvent(); }
171,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data if the key is instantiated */ if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) && !test_bit(KEY_FLAG_NEGATIVE, &key->flags) && key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); memzero_explicit(key, sizeof(*key)); kmem_cache_free(key_jar, key); } } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static noinline void key_gc_unused_keys(struct list_head *keys) { while (!list_empty(keys)) { struct key *key = list_entry(keys->next, struct key, graveyard_link); short state = key->state; list_del(&key->graveyard_link); kdebug("- %u", key->serial); key_check(key); /* Throw away the key data if the key is instantiated */ if (state == KEY_IS_POSITIVE && key->type->destroy) key->type->destroy(key); security_key_free(key); /* deal with the user's key tracking and quota */ if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { spin_lock(&key->user->lock); key->user->qnkeys--; key->user->qnbytes -= key->quotalen; spin_unlock(&key->user->lock); } atomic_dec(&key->user->nkeys); if (state != KEY_IS_UNINSTANTIATED) atomic_dec(&key->user->nikeys); key_user_put(key->user); kfree(key->description); memzero_explicit(key, sizeof(*key)); kmem_cache_free(key_jar, key); } }
167,695
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, int *pexit_code, ref * perror_object) { ref *epref = pref; ref doref; ref *perrordict; ref error_name; int code, ccode; ref saref; i_ctx_t *i_ctx_p = *pi_ctx_p; int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; *pexit_code = 0; *gc_signal = 0; ialloc_reset_requested(idmemory); again: /* Avoid a dangling error object that might get traced by a future GC. */ make_null(perror_object); o_stack.requested = e_stack.requested = d_stack.requested = 0; while (*gc_signal) { /* Some routine below triggered a GC. */ gs_gc_root_t epref_root; *gc_signal = 0; /* Make sure that doref will get relocated properly if */ /* a garbage collection happens with epref == &doref. */ gs_register_ref_root(imemory_system, &epref_root, (void **)&epref, "gs_call_interp(epref)"); code = interp_reclaim(pi_ctx_p, -1); i_ctx_p = *pi_ctx_p; gs_unregister_root(imemory_system, &epref_root, "gs_call_interp(epref)"); if (code < 0) return code; } code = interp(pi_ctx_p, epref, perror_object); i_ctx_p = *pi_ctx_p; if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { *perror_object = i_ctx_p->error_object; make_t(&i_ctx_p->error_object, t__invalid); } /* Prevent a dangling reference to the GC signal in ticks_left */ /* in the frame of interp, but be prepared to do a GC if */ /* an allocation in this routine asks for it. */ *gc_signal = 0; set_gc_signal(i_ctx_p, 1); if (esp < esbot) /* popped guard entry */ esp = esbot; switch (code) { case gs_error_Fatal: *pexit_code = 255; return code; case gs_error_Quit: *perror_object = osp[-1]; *pexit_code = code = osp->value.intval; osp -= 2; return (code == 0 ? gs_error_Quit : code < 0 && code > -100 ? code : gs_error_Fatal); case gs_error_InterpreterExit: return 0; case gs_error_ExecStackUnderflow: /****** WRONG -- must keep mark blocks intact ******/ ref_stack_pop_block(&e_stack); doref = *perror_object; epref = &doref; goto again; case gs_error_VMreclaim: /* Do the GC and continue. */ /* We ignore the return value here, if it fails here * we'll call it again having jumped to the "again" label. * Where, assuming it fails again, we'll handle the error. */ (void)interp_reclaim(pi_ctx_p, (osp->value.intval == 2 ? avm_global : avm_local)); i_ctx_p = *pi_ctx_p; make_oper(&doref, 0, zpop); epref = &doref; goto again; case gs_error_NeedInput: case gs_error_interrupt: return code; } /* Adjust osp in case of operand stack underflow */ if (osp < osbot - 1) osp = osbot - 1; /* We have to handle stack over/underflow specially, because */ /* we might be able to recover by adding or removing a block. */ switch (code) { case gs_error_dictstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_dstack, which does a ref_stack_extend, */ /* so if` we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } /* Skip system dictionaries for CET 20-02-02 */ ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); if (ccode < 0) return ccode; ref_stack_pop_to(&d_stack, min_dstack_size); dict_set_top(); *++osp = saref; break; case gs_error_dictstackunderflow: if (ref_stack_pop_block(&d_stack) >= 0) { dict_set_top(); doref = *perror_object; epref = &doref; goto again; } break; case gs_error_execstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_estack, which does a ref_stack_extend, */ /* so if we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); if (ccode < 0) return ccode; { uint count = ref_stack_count(&e_stack); uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; if (count > limit) { /* * If there is an e-stack mark within MIN_BLOCK_ESTACK of * the new top, cut the stack back to remove the mark. */ int skip = count - limit; int i; for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { const ref *ep = ref_stack_index(&e_stack, i); if (r_has_type_attrs(ep, t_null, a_executable)) { skip = i + 1; break; } } pop_estack(i_ctx_p, skip); } } *++osp = saref; break; case gs_error_stackoverflow: if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ /* it might be a procedure being pushed as a */ /* literal. We check for this case specially. */ doref = *perror_object; if (r_is_proc(&doref)) { *++osp = doref; make_null_proc(&doref); } epref = &doref; goto again; } ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); if (ccode < 0) return ccode; ref_stack_clear(&o_stack); *++osp = saref; break; case gs_error_stackunderflow: if (ref_stack_pop_block(&o_stack) >= 0) { doref = *perror_object; epref = &doref; goto again; } break; } if (user_errors < 0) return code; if (gs_errorname(i_ctx_p, code, &error_name) < 0) return code; /* out-of-range error code! */ /* We refer to gserrordict first, which is not accessible to Postcript jobs * If we're running with SAFERERRORS all the handlers are copied to gserrordict * so we'll always find the default one. If not SAFERERRORS, only gs specific * errors are in gserrordict. */ if (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 || (dict_find(perrordict, &error_name, &epref) <= 0 && (dict_find_string(systemdict, "errordict", &perrordict) <= 0 || dict_find(perrordict, &error_name, &epref) <= 0)) ) return code; /* error name not in errordict??? */ doref = *epref; epref = &doref; /* Push the error object on the operand stack if appropriate. */ if (!GS_ERROR_IS_INTERRUPT(code)) { /* Replace the error object if within an oparray or .errorexec. */ osp++; if (osp >= ostop) { } *osp = *perror_object; } *osp = *perror_object; errorexec_find(i_ctx_p, osp); /* If using SAFER, hand a name object to the error handler, rather than the executable * object/operator itself. */ if (i_ctx_p->LockFilePermissions) { code = obj_cvs(imemory, osp, buf + 2, 256, &rlen, (const byte **)&bufptr); if (code < 0) { const char *unknownstr = "--unknown--"; rlen = strlen(unknownstr); memcpy(buf, unknownstr, rlen); } else { buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-'; rlen += 4; } code = name_ref(imemory, buf, rlen, osp, 1); if (code < 0) make_null(osp); } } Commit Message: CWE ID: CWE-209
gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, int *pexit_code, ref * perror_object) { ref *epref = pref; ref doref; ref *perrordict; ref error_name; int code, ccode; ref saref; i_ctx_t *i_ctx_p = *pi_ctx_p; int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; *pexit_code = 0; *gc_signal = 0; ialloc_reset_requested(idmemory); again: /* Avoid a dangling error object that might get traced by a future GC. */ make_null(perror_object); o_stack.requested = e_stack.requested = d_stack.requested = 0; while (*gc_signal) { /* Some routine below triggered a GC. */ gs_gc_root_t epref_root; *gc_signal = 0; /* Make sure that doref will get relocated properly if */ /* a garbage collection happens with epref == &doref. */ gs_register_ref_root(imemory_system, &epref_root, (void **)&epref, "gs_call_interp(epref)"); code = interp_reclaim(pi_ctx_p, -1); i_ctx_p = *pi_ctx_p; gs_unregister_root(imemory_system, &epref_root, "gs_call_interp(epref)"); if (code < 0) return code; } code = interp(pi_ctx_p, epref, perror_object); i_ctx_p = *pi_ctx_p; if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { *perror_object = i_ctx_p->error_object; make_t(&i_ctx_p->error_object, t__invalid); } /* Prevent a dangling reference to the GC signal in ticks_left */ /* in the frame of interp, but be prepared to do a GC if */ /* an allocation in this routine asks for it. */ *gc_signal = 0; set_gc_signal(i_ctx_p, 1); if (esp < esbot) /* popped guard entry */ esp = esbot; switch (code) { case gs_error_Fatal: *pexit_code = 255; return code; case gs_error_Quit: *perror_object = osp[-1]; *pexit_code = code = osp->value.intval; osp -= 2; return (code == 0 ? gs_error_Quit : code < 0 && code > -100 ? code : gs_error_Fatal); case gs_error_InterpreterExit: return 0; case gs_error_ExecStackUnderflow: /****** WRONG -- must keep mark blocks intact ******/ ref_stack_pop_block(&e_stack); doref = *perror_object; epref = &doref; goto again; case gs_error_VMreclaim: /* Do the GC and continue. */ /* We ignore the return value here, if it fails here * we'll call it again having jumped to the "again" label. * Where, assuming it fails again, we'll handle the error. */ (void)interp_reclaim(pi_ctx_p, (osp->value.intval == 2 ? avm_global : avm_local)); i_ctx_p = *pi_ctx_p; make_oper(&doref, 0, zpop); epref = &doref; goto again; case gs_error_NeedInput: case gs_error_interrupt: return code; } /* Adjust osp in case of operand stack underflow */ if (osp < osbot - 1) osp = osbot - 1; /* We have to handle stack over/underflow specially, because */ /* we might be able to recover by adding or removing a block. */ switch (code) { case gs_error_dictstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_dstack, which does a ref_stack_extend, */ /* so if` we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } /* Skip system dictionaries for CET 20-02-02 */ ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); if (ccode < 0) return ccode; ref_stack_pop_to(&d_stack, min_dstack_size); dict_set_top(); *++osp = saref; break; case gs_error_dictstackunderflow: if (ref_stack_pop_block(&d_stack) >= 0) { dict_set_top(); doref = *perror_object; epref = &doref; goto again; } break; case gs_error_execstackoverflow: /* We don't have to handle this specially: */ /* The only places that could generate it */ /* use check_estack, which does a ref_stack_extend, */ /* so if we get this error, it's a real one. */ if (osp >= ostop) { if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) return ccode; } ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); if (ccode < 0) return ccode; { uint count = ref_stack_count(&e_stack); uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; if (count > limit) { /* * If there is an e-stack mark within MIN_BLOCK_ESTACK of * the new top, cut the stack back to remove the mark. */ int skip = count - limit; int i; for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { const ref *ep = ref_stack_index(&e_stack, i); if (r_has_type_attrs(ep, t_null, a_executable)) { skip = i + 1; break; } } pop_estack(i_ctx_p, skip); } } *++osp = saref; break; case gs_error_stackoverflow: if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ /* it might be a procedure being pushed as a */ /* literal. We check for this case specially. */ doref = *perror_object; if (r_is_proc(&doref)) { *++osp = doref; make_null_proc(&doref); } epref = &doref; goto again; } ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); if (ccode < 0) return ccode; ref_stack_clear(&o_stack); *++osp = saref; break; case gs_error_stackunderflow: if (ref_stack_pop_block(&o_stack) >= 0) { doref = *perror_object; epref = &doref; goto again; } break; } if (user_errors < 0) return code; if (gs_errorname(i_ctx_p, code, &error_name) < 0) return code; /* out-of-range error code! */ /* We refer to gserrordict first, which is not accessible to Postcript jobs * If we're running with SAFERERRORS all the handlers are copied to gserrordict * so we'll always find the default one. If not SAFERERRORS, only gs specific * errors are in gserrordict. */ if (dict_find_string(systemdict, "gserrordict", &perrordict) <= 0 || (dict_find(perrordict, &error_name, &epref) <= 0 && (dict_find_string(systemdict, "errordict", &perrordict) <= 0 || dict_find(perrordict, &error_name, &epref) <= 0)) ) return code; /* error name not in errordict??? */ doref = *epref; epref = &doref; /* Push the error object on the operand stack if appropriate. */ if (!GS_ERROR_IS_INTERRUPT(code)) { byte buf[260], *bufptr; uint rlen; /* Replace the error object if within an oparray or .errorexec. */ osp++; if (osp >= ostop) { } *osp = *perror_object; } *osp = *perror_object; errorexec_find(i_ctx_p, osp); if (!r_has_type(osp, t_string) && !r_has_type(osp, t_name)) { code = obj_cvs(imemory, osp, buf + 2, 256, &rlen, (const byte **)&bufptr); if (code < 0) { const char *unknownstr = "--unknown--"; rlen = strlen(unknownstr); memcpy(buf, unknownstr, rlen); bufptr = buf; } else { ref *tobj; bufptr[rlen] = '\0'; /* Only pass a name object if the operator doesn't exist in systemdict * i.e. it's an internal operator we have hidden */ code = dict_find_string(systemdict, (const char *)bufptr, &tobj); if (code < 0) { buf[0] = buf[1] = buf[rlen + 2] = buf[rlen + 3] = '-'; rlen += 4; bufptr = buf; } else { bufptr = NULL; } } if (bufptr) { code = name_ref(imemory, buf, rlen, osp, 1); if (code < 0) make_null(osp); } } }
164,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& native_app_name, const std::string& channel_name, const std::string& connect_message) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL, source_extension_id)); NativeMessageProcessHost::MessageType type = channel_name == "chrome.runtime.sendNativeMessage" ? NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST : NativeMessageProcessHost::TYPE_CONNECT; content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&NativeMessageProcessHost::Create, base::WeakPtr<NativeMessageProcessHost::Client>( weak_factory_.GetWeakPtr()), native_app_name, connect_message, receiver_port_id, type, base::Bind(&MessageService::FinalizeOpenChannelToNativeApp, weak_factory_.GetWeakPtr(), receiver_port_id, channel_name, base::Passed(&channel), tab_json))); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& native_app_name, const std::string& channel_name, const std::string& connect_message) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL, source_extension_id)); NativeMessageProcessHost::MessageType type = channel_name == "chrome.runtime.sendNativeMessage" ? NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST : NativeMessageProcessHost::TYPE_CONNECT; content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&NativeMessageProcessHost::Create, base::WeakPtr<NativeMessageProcessHost::Client>( weak_factory_.GetWeakPtr()), native_app_name, connect_message, receiver_port_id, type, base::Bind(&MessageService::FinalizeOpenChannelToNativeApp, weak_factory_.GetWeakPtr(), receiver_port_id, channel_name, base::Passed(&channel), tab_json))); }
171,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TextTrackCueList::Add(TextTrackCue* cue) { DCHECK_GE(cue->startTime(), 0); DCHECK_GE(cue->endTime(), 0); size_t index = FindInsertionIndex(cue); if (!list_.IsEmpty() && (index > 0) && (list_[index - 1].Get() == cue)) return false; list_.insert(index, cue); InvalidateCueIndex(index); return true; } Commit Message: Support negative timestamps of TextTrackCue Ensure proper behaviour for negative timestamps of TextTrackCue. 1. Cues with negative startTime should become active from 0s. 2. Cues with negative startTime and endTime should never be active. Bug: 314032 Change-Id: Ib53710e58be0be770c933ea8c3c4709a0e5dec0d Reviewed-on: https://chromium-review.googlesource.com/863270 Commit-Queue: srirama chandra sekhar <[email protected]> Reviewed-by: Fredrik Söderquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#529012} CWE ID:
bool TextTrackCueList::Add(TextTrackCue* cue) { size_t index = FindInsertionIndex(cue); if (!list_.IsEmpty() && (index > 0) && (list_[index - 1].Get() == cue)) return false; list_.insert(index, cue); InvalidateCueIndex(index); return true; }
171,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; } Commit Message: rose: fix info leak via msg_name in rose_recvmsg() The code in rose_recvmsg() does not initialize all of the members of struct sockaddr_rose/full_sockaddr_rose when filling the sockaddr info. Nor does it initialize the padding bytes of the structure inserted by the compiler for alignment. This will lead to leaking uninitialized kernel stack bytes in net/socket.c. Fix the issue by initializing the memory used for sockaddr info with memset(0). Cc: Ralf Baechle <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int rose_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name; size_t copied; unsigned char *asmptr; struct sk_buff *skb; int n, er, qbit; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ if (sk->sk_state != TCP_ESTABLISHED) return -ENOTCONN; /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) return er; qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT; skb_pull(skb, ROSE_MIN_LEN); if (rose->qbitincl) { asmptr = skb_push(skb, 1); *asmptr = qbit; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (srose != NULL) { memset(srose, 0, msg->msg_namelen); srose->srose_family = AF_ROSE; srose->srose_addr = rose->dest_addr; srose->srose_call = rose->dest_call; srose->srose_ndigis = rose->dest_ndigis; if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name; for (n = 0 ; n < rose->dest_ndigis ; n++) full_srose->srose_digis[n] = rose->dest_digis[n]; msg->msg_namelen = sizeof(struct full_sockaddr_rose); } else { if (rose->dest_ndigis >= 1) { srose->srose_ndigis = 1; srose->srose_digi = rose->dest_digis[0]; } msg->msg_namelen = sizeof(struct sockaddr_rose); } } skb_free_datagram(sk, skb); return copied; }
166,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserViewRenderer::DidOverscroll(gfx::Vector2dF accumulated_overscroll, gfx::Vector2dF latest_overscroll_delta, gfx::Vector2dF current_fling_velocity) { const float physical_pixel_scale = dip_scale_ * page_scale_factor_; if (accumulated_overscroll == latest_overscroll_delta) overscroll_rounding_error_ = gfx::Vector2dF(); gfx::Vector2dF scaled_overscroll_delta = gfx::ScaleVector2d(latest_overscroll_delta, physical_pixel_scale); gfx::Vector2d rounded_overscroll_delta = gfx::ToRoundedVector2d( scaled_overscroll_delta + overscroll_rounding_error_); overscroll_rounding_error_ = scaled_overscroll_delta - rounded_overscroll_delta; gfx::Vector2dF fling_velocity_pixels = gfx::ScaleVector2d(current_fling_velocity, physical_pixel_scale); client_->DidOverscroll(rounded_overscroll_delta, fling_velocity_pixels); } Commit Message: sync compositor: pass simple gfx types by const ref See bug for reasoning BUG=159273 Review URL: https://codereview.chromium.org/1417893006 Cr-Commit-Position: refs/heads/master@{#356653} CWE ID: CWE-399
void BrowserViewRenderer::DidOverscroll(gfx::Vector2dF accumulated_overscroll, void BrowserViewRenderer::DidOverscroll( const gfx::Vector2dF& accumulated_overscroll, const gfx::Vector2dF& latest_overscroll_delta, const gfx::Vector2dF& current_fling_velocity) { const float physical_pixel_scale = dip_scale_ * page_scale_factor_; if (accumulated_overscroll == latest_overscroll_delta) overscroll_rounding_error_ = gfx::Vector2dF(); gfx::Vector2dF scaled_overscroll_delta = gfx::ScaleVector2d(latest_overscroll_delta, physical_pixel_scale); gfx::Vector2d rounded_overscroll_delta = gfx::ToRoundedVector2d( scaled_overscroll_delta + overscroll_rounding_error_); overscroll_rounding_error_ = scaled_overscroll_delta - rounded_overscroll_delta; gfx::Vector2dF fling_velocity_pixels = gfx::ScaleVector2d(current_fling_velocity, physical_pixel_scale); client_->DidOverscroll(rounded_overscroll_delta, fling_velocity_pixels); }
171,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool HeapAllocator::backingExpand(void* address, size_t newSize) { if (!address) return false; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); ASSERT(header->checkHeader()); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); bool succeed = arena->expandObject(header, newSize); if (succeed) state->allocationPointAdjusted(arena->arenaIndex()); return succeed; } Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect. This requires changing its signature. This is a preliminary stage to making it private. BUG=633030 Review-Url: https://codereview.chromium.org/2698673003 Cr-Commit-Position: refs/heads/master@{#460489} CWE ID: CWE-119
bool HeapAllocator::backingExpand(void* address, size_t newSize) { if (!address) return false; ThreadState* state = ThreadState::current(); if (state->sweepForbidden()) return false; ASSERT(!state->isInGC()); ASSERT(state->isAllocationAllowed()); DCHECK_EQ(&state->heap(), &ThreadState::fromObject(address)->heap()); BasePage* page = pageFromObject(address); if (page->isLargeObjectPage() || page->arena()->getThreadState() != state) return false; HeapObjectHeader* header = HeapObjectHeader::fromPayload(address); header->checkHeader(); NormalPageArena* arena = static_cast<NormalPage*>(page)->arenaForNormalPage(); bool succeed = arena->expandObject(header, newSize); if (succeed) state->allocationPointAdjusted(arena->arenaIndex()); return succeed; }
172,705
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists( int32 download_id, const FilePath& unverified_path, bool should_prompt, bool is_forced_path, content::DownloadDangerType danger_type, const FilePath& default_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath target_path(unverified_path); file_util::CreateDirectory(default_path); FilePath dir = target_path.DirName(); FilePath filename = target_path.BaseName(); if (!file_util::PathIsWritable(dir)) { VLOG(1) << "Unable to write to directory \"" << dir.value() << "\""; should_prompt = true; PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir); target_path = dir.Append(filename); } bool should_uniquify = (!is_forced_path && (danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || should_prompt)); bool should_overwrite = (should_uniquify || is_forced_path); bool should_create_marker = (should_uniquify && !should_prompt); if (should_uniquify) { int uniquifier = download_util::GetUniquePathNumberWithCrDownload(target_path); if (uniquifier > 0) { target_path = target_path.InsertBeforeExtensionASCII( StringPrintf(" (%d)", uniquifier)); } else if (uniquifier == -1) { VLOG(1) << "Unable to find a unique path for suggested path \"" << target_path.value() << "\""; should_prompt = true; } } if (should_create_marker) file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0); DownloadItem::TargetDisposition disposition; if (should_prompt) disposition = DownloadItem::TARGET_DISPOSITION_PROMPT; else if (should_overwrite) disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE; else disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable, this, download_id, target_path, disposition, danger_type)); } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void ChromeDownloadManagerDelegate::CheckIfSuggestedPathExists( int32 download_id, const FilePath& unverified_path, bool should_prompt, bool is_forced_path, content::DownloadDangerType danger_type, const FilePath& default_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath target_path(unverified_path); file_util::CreateDirectory(default_path); FilePath dir = target_path.DirName(); FilePath filename = target_path.BaseName(); if (!file_util::PathIsWritable(dir)) { VLOG(1) << "Unable to write to directory \"" << dir.value() << "\""; should_prompt = true; PathService::Get(chrome::DIR_USER_DOCUMENTS, &dir); target_path = dir.Append(filename); } bool should_uniquify = (!is_forced_path && (danger_type == content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS || should_prompt)); bool should_overwrite = (should_uniquify || is_forced_path); bool should_create_marker = (should_uniquify && !should_prompt); if (should_uniquify) { // the in-progress rename. Ditto for "Forced" downloads. None of the int uniquifier = download_util::GetUniquePathNumberWithCrDownload(target_path); if (uniquifier > 0) { target_path = target_path.InsertBeforeExtensionASCII( StringPrintf(" (%d)", uniquifier)); } else if (uniquifier == -1) { VLOG(1) << "Unable to find a unique path for suggested path \"" << target_path.value() << "\""; should_prompt = true; } } if (should_create_marker) file_util::WriteFile(download_util::GetCrDownloadPath(target_path), "", 0); DownloadItem::TargetDisposition disposition; if (should_prompt) disposition = DownloadItem::TARGET_DISPOSITION_PROMPT; else if (should_overwrite) disposition = DownloadItem::TARGET_DISPOSITION_OVERWRITE; else disposition = DownloadItem::TARGET_DISPOSITION_UNIQUIFY; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ChromeDownloadManagerDelegate::OnPathExistenceAvailable, this, download_id, target_path, disposition, danger_type)); }
170,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::SetAlignment(ShelfAlignment alignment) { if (alignment_ == alignment) return; alignment_ = alignment; UpdateFirstButtonPadding(); LayoutToIdealBounds(); tooltip_->SetArrowLocation(alignment_); if (overflow_bubble_.get()) overflow_bubble_->Hide(); }
170,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UnloadController::TabDetachedAt(TabContents* contents, int index) { TabDetachedImpl(contents); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void UnloadController::TabDetachedAt(TabContents* contents, int index) { void UnloadController::TabDetachedAt(content::WebContents* contents, int index) { TabDetachedImpl(contents); }
171,519
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static mif_hdr_t *mif_hdr_get(jas_stream_t *in) { uchar magicbuf[MIF_MAGICLEN]; char buf[4096]; mif_hdr_t *hdr; bool done; jas_tvparser_t *tvp; int id; hdr = 0; tvp = 0; if (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) { goto error; } if (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) & 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] != (MIF_MAGIC & 0xff)) { jas_eprintf("error: bad signature\n"); goto error; } if (!(hdr = mif_hdr_create(0))) { goto error; } done = false; do { if (!mif_getline(in, buf, sizeof(buf))) { jas_eprintf("mif_getline failed\n"); goto error; } if (buf[0] == '\0') { continue; } JAS_DBGLOG(10, ("header line: len=%d; %s\n", strlen(buf), buf)); if (!(tvp = jas_tvparser_create(buf))) { jas_eprintf("jas_tvparser_create failed\n"); goto error; } if (jas_tvparser_next(tvp)) { jas_eprintf("cannot get record type\n"); goto error; } id = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2, jas_tvparser_gettag(tvp)))->id; jas_tvparser_destroy(tvp); tvp = 0; switch (id) { case MIF_CMPT: if (mif_process_cmpt(hdr, buf)) { jas_eprintf("cannot get component information\n"); goto error; } break; case MIF_END: done = 1; break; default: jas_eprintf("invalid header information: %s\n", buf); goto error; break; } } while (!done); return hdr; error: if (hdr) { mif_hdr_destroy(hdr); } if (tvp) { jas_tvparser_destroy(tvp); } return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
static mif_hdr_t *mif_hdr_get(jas_stream_t *in) { jas_uchar magicbuf[MIF_MAGICLEN]; char buf[4096]; mif_hdr_t *hdr; bool done; jas_tvparser_t *tvp; int id; hdr = 0; tvp = 0; if (jas_stream_read(in, magicbuf, MIF_MAGICLEN) != MIF_MAGICLEN) { goto error; } if (magicbuf[0] != (MIF_MAGIC >> 24) || magicbuf[1] != ((MIF_MAGIC >> 16) & 0xff) || magicbuf[2] != ((MIF_MAGIC >> 8) & 0xff) || magicbuf[3] != (MIF_MAGIC & 0xff)) { jas_eprintf("error: bad signature\n"); goto error; } if (!(hdr = mif_hdr_create(0))) { goto error; } done = false; do { if (!mif_getline(in, buf, sizeof(buf))) { jas_eprintf("mif_getline failed\n"); goto error; } if (buf[0] == '\0') { continue; } JAS_DBGLOG(10, ("header line: len=%d; %s\n", strlen(buf), buf)); if (!(tvp = jas_tvparser_create(buf))) { jas_eprintf("jas_tvparser_create failed\n"); goto error; } if (jas_tvparser_next(tvp)) { jas_eprintf("cannot get record type\n"); goto error; } id = jas_taginfo_nonull(jas_taginfos_lookup(mif_tags2, jas_tvparser_gettag(tvp)))->id; jas_tvparser_destroy(tvp); tvp = 0; switch (id) { case MIF_CMPT: if (mif_process_cmpt(hdr, buf)) { jas_eprintf("cannot get component information\n"); goto error; } break; case MIF_END: done = 1; break; default: jas_eprintf("invalid header information: %s\n", buf); goto error; break; } } while (!done); return hdr; error: if (hdr) { mif_hdr_destroy(hdr); } if (tvp) { jas_tvparser_destroy(tvp); } return 0; }
168,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_decrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_decrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC); }
167,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AppControllerImpl::~AppControllerImpl() { if (apps::AppServiceProxy::Get(profile_)) app_service_proxy_->AppRegistryCache().RemoveObserver(this); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
AppControllerImpl::~AppControllerImpl() { AppControllerService::~AppControllerService() { app_service_proxy_->AppRegistryCache().RemoveObserver(this); }
172,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGLRenderingContextBase::TexImageHelperDOMArrayBufferView( TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, DOMArrayBufferView* pixels, NullDisposition null_disposition, GLuint src_offset) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateTexImageBinding(func_name, function_id, target)) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceArrayBufferView, target, level, internalformat, width, height, depth, border, format, type, xoffset, yoffset, zoffset)) return; TexImageDimension source_type; if (function_id == kTexImage2D || function_id == kTexSubImage2D) source_type = kTex2D; else source_type = kTex3D; if (!ValidateTexFuncData(func_name, source_type, level, width, height, depth, format, type, pixels, null_disposition, src_offset)) return; uint8_t* data = reinterpret_cast<uint8_t*>( pixels ? pixels->BaseAddressMaybeShared() : nullptr); if (src_offset) { DCHECK(pixels); data += src_offset * pixels->TypeSize(); } Vector<uint8_t> temp_data; bool change_unpack_alignment = false; if (data && (unpack_flip_y_ || unpack_premultiply_alpha_)) { if (source_type == kTex2D) { if (!WebGLImageConversion::ExtractTextureData( width, height, format, type, unpack_alignment_, unpack_flip_y_, unpack_premultiply_alpha_, data, temp_data)) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "Invalid format/type combination."); return; } data = temp_data.data(); } change_unpack_alignment = true; } ContextGL()->TexImage3D(target, level, ConvertTexInternalFormat(internalformat, type), width, height, depth, border, format, type, data); return; } if (function_id == kTexSubImage3D) { ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data); return; } ScopedUnpackParametersResetRestore temporary_reset_unpack( this, change_unpack_alignment); if (function_id == kTexImage2D) TexImage2DBase(target, level, internalformat, width, height, border, format, type, data); else if (function_id == kTexSubImage2D) ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data); } Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA. BUG=774174 TEST=https://github.com/KhronosGroup/WebGL/pull/2555 [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I4f4e7636314502451104730501a5048a5d7b9f3f Reviewed-on: https://chromium-review.googlesource.com/808665 Commit-Queue: Zhenyao Mo <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#522003} CWE ID: CWE-125
void WebGLRenderingContextBase::TexImageHelperDOMArrayBufferView( TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, DOMArrayBufferView* pixels, NullDisposition null_disposition, GLuint src_offset) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateTexImageBinding(func_name, function_id, target)) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceArrayBufferView, target, level, internalformat, width, height, depth, border, format, type, xoffset, yoffset, zoffset)) return; TexImageDimension source_type; if (function_id == kTexImage2D || function_id == kTexSubImage2D) source_type = kTex2D; else source_type = kTex3D; if (!ValidateTexFuncData(func_name, source_type, level, width, height, depth, format, type, pixels, null_disposition, src_offset)) return; uint8_t* data = reinterpret_cast<uint8_t*>( pixels ? pixels->BaseAddressMaybeShared() : nullptr); if (src_offset) { DCHECK(pixels); data += src_offset * pixels->TypeSize(); } Vector<uint8_t> temp_data; bool change_unpack_params = false; if (data && width && height && (unpack_flip_y_ || unpack_premultiply_alpha_)) { DCHECK_EQ(kTex2D, source_type); // Only enter here if width or height is non-zero. Otherwise, call to the // underlying driver to generate appropriate GL errors if needed. WebGLImageConversion::PixelStoreParams unpack_params = GetUnpackPixelStoreParams(kTex2D); GLint data_store_width = unpack_params.row_length ? unpack_params.row_length : width; if (unpack_params.skip_pixels + width > data_store_width) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "Invalid unpack params combination."); return; } if (!WebGLImageConversion::ExtractTextureData( width, height, format, type, unpack_params, unpack_flip_y_, unpack_premultiply_alpha_, data, temp_data)) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "Invalid format/type combination."); return; } data = temp_data.data(); change_unpack_params = true; } ContextGL()->TexImage3D(target, level, ConvertTexInternalFormat(internalformat, type), width, height, depth, border, format, type, data); return; } if (function_id == kTexSubImage3D) { ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, data); return; } ScopedUnpackParametersResetRestore temporary_reset_unpack( this, change_unpack_params); if (function_id == kTexImage2D) TexImage2DBase(target, level, internalformat, width, height, border, format, type, data); else if (function_id == kTexSubImage2D) ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, data); }
172,681
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, renderer_process_, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); } 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:
void DXVAVideoDecodeAccelerator::Decode( const media::BitstreamBuffer& bitstream_buffer) { DCHECK(CalledOnValidThread()); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kNormal || state_ == kStopped), "Invalid state: " << state_, ILLEGAL_STATE,); base::win::ScopedComPtr<IMFSample> sample; sample.Attach(CreateSampleFromInputBuffer(bitstream_buffer, input_stream_info_.cbSize, input_stream_info_.cbAlignment)); RETURN_AND_NOTIFY_ON_FAILURE(sample, "Failed to create input sample", PLATFORM_FAILURE,); if (!inputs_before_decode_) { TRACE_EVENT_BEGIN_ETW("DXVAVideoDecodeAccelerator.Decoding", this, ""); } inputs_before_decode_++; RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0), "Failed to create input sample", PLATFORM_FAILURE,); HRESULT hr = decoder_->ProcessInput(0, sample, 0); RETURN_AND_NOTIFY_ON_HR_FAILURE(hr, "Failed to process input sample", PLATFORM_FAILURE,); RETURN_AND_NOTIFY_ON_FAILURE( SendMFTMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0), "Failed to send eos message to MFT", PLATFORM_FAILURE,); state_ = kEosDrain; last_input_buffer_id_ = bitstream_buffer.id(); DoDecode(); RETURN_AND_NOTIFY_ON_FAILURE((state_ == kStopped || state_ == kNormal), "Failed to process output. Unexpected decoder state: " << state_, ILLEGAL_STATE,); MessageLoop::current()->PostTask(FROM_HERE, base::Bind( &DXVAVideoDecodeAccelerator::NotifyInputBufferRead, this, bitstream_buffer.id())); }
170,941
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnUpdatePrintSettings( int document_cookie, const base::DictionaryValue& job_settings, PrintMsg_PrintPages_Params* params) { std::string dummy_string; int margins_type = 0; if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) || !job_settings.GetBoolean(printing::kSettingCollate, NULL) || !job_settings.GetInteger(printing::kSettingColor, NULL) || !job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) || !job_settings.GetBoolean(printing::kIsFirstRequest, NULL) || !job_settings.GetString(printing::kSettingDeviceName, &dummy_string) || !job_settings.GetInteger(printing::kSettingDuplexMode, NULL) || !job_settings.GetInteger(printing::kSettingCopies, NULL) || !job_settings.GetString(printing::kPreviewUIAddr, &dummy_string) || !job_settings.GetInteger(printing::kPreviewRequestID, NULL) || !job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) { return; } if (printer_.get()) { const ListValue* page_range_array; printing::PageRanges new_ranges; if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) { for (size_t index = 0; index < page_range_array->GetSize(); ++index) { const base::DictionaryValue* dict; if (!page_range_array->GetDictionary(index, &dict)) continue; printing::PageRange range; if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) || !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) { continue; } range.from--; range.to--; new_ranges.push_back(range); } } std::vector<int> pages(printing::PageRange::GetPages(new_ranges)); printer_->UpdateSettings(document_cookie, params, pages, margins_type); } } 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 ChromeMockRenderThread::OnUpdatePrintSettings( int document_cookie, const base::DictionaryValue& job_settings, PrintMsg_PrintPages_Params* params) { std::string dummy_string; int margins_type = 0; if (!job_settings.GetBoolean(printing::kSettingLandscape, NULL) || !job_settings.GetBoolean(printing::kSettingCollate, NULL) || !job_settings.GetInteger(printing::kSettingColor, NULL) || !job_settings.GetBoolean(printing::kSettingPrintToPDF, NULL) || !job_settings.GetBoolean(printing::kIsFirstRequest, NULL) || !job_settings.GetString(printing::kSettingDeviceName, &dummy_string) || !job_settings.GetInteger(printing::kSettingDuplexMode, NULL) || !job_settings.GetInteger(printing::kSettingCopies, NULL) || !job_settings.GetInteger(printing::kPreviewUIID, NULL) || !job_settings.GetInteger(printing::kPreviewRequestID, NULL) || !job_settings.GetInteger(printing::kSettingMarginsType, &margins_type)) { return; } const ListValue* page_range_array; printing::PageRanges new_ranges; if (job_settings.GetList(printing::kSettingPageRange, &page_range_array)) { for (size_t index = 0; index < page_range_array->GetSize(); ++index) { const base::DictionaryValue* dict; if (!page_range_array->GetDictionary(index, &dict)) continue; printing::PageRange range; if (!dict->GetInteger(printing::kSettingPageRangeFrom, &range.from) || !dict->GetInteger(printing::kSettingPageRangeTo, &range.to)) { continue; } // Page numbers are 1-based in the dictionary. // Page numbers are 0-based for the printing context. range.from--; range.to--; new_ranges.push_back(range); } } std::vector<int> pages(printing::PageRange::GetPages(new_ranges)); printer_->UpdateSettings(document_cookie, params, pages, margins_type); } MockPrinter* ChromeMockRenderThread::printer() { return printer_.get(); }
170,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt, struct tss_segment_16 *tss) { int ret; u8 cpl; ctxt->_eip = tss->ip; ctxt->eflags = tss->flag | 2; *reg_write(ctxt, VCPU_REGS_RAX) = tss->ax; *reg_write(ctxt, VCPU_REGS_RCX) = tss->cx; *reg_write(ctxt, VCPU_REGS_RDX) = tss->dx; *reg_write(ctxt, VCPU_REGS_RBX) = tss->bx; *reg_write(ctxt, VCPU_REGS_RSP) = tss->sp; *reg_write(ctxt, VCPU_REGS_RBP) = tss->bp; *reg_write(ctxt, VCPU_REGS_RSI) = tss->si; *reg_write(ctxt, VCPU_REGS_RDI) = tss->di; /* * SDM says that segment selectors are loaded before segment * descriptors */ set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); cpl = tss->cs & 3; /* * Now load segment descriptors. If fault happens at this stage * it is handled in a context of new task */ ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; } Commit Message: KVM: x86: Handle errors when RIP is set during far jumps Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not handle this case, and may result in failed vm-entry once the assignment is done. The tricky part of doing so is that loading the new CS affects the VMCS/VMCB state, so if we fail during loading the new RIP, we are left in unconsistent state. Therefore, this patch saves on 64-bit the old CS descriptor and restores it if loading RIP failed. This fixes CVE-2014-3647. Cc: [email protected] Signed-off-by: Nadav Amit <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt, struct tss_segment_16 *tss) { int ret; u8 cpl; ctxt->_eip = tss->ip; ctxt->eflags = tss->flag | 2; *reg_write(ctxt, VCPU_REGS_RAX) = tss->ax; *reg_write(ctxt, VCPU_REGS_RCX) = tss->cx; *reg_write(ctxt, VCPU_REGS_RDX) = tss->dx; *reg_write(ctxt, VCPU_REGS_RBX) = tss->bx; *reg_write(ctxt, VCPU_REGS_RSP) = tss->sp; *reg_write(ctxt, VCPU_REGS_RBP) = tss->bp; *reg_write(ctxt, VCPU_REGS_RSI) = tss->si; *reg_write(ctxt, VCPU_REGS_RDI) = tss->di; /* * SDM says that segment selectors are loaded before segment * descriptors */ set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); cpl = tss->cs & 3; /* * Now load segment descriptors. If fault happens at this stage * it is handled in a context of new task */ ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; }
166,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int CIFSFindNext(const int xid, struct cifs_tcon *tcon, __u16 searchHandle, struct cifs_search_info *psrch_inf) { TRANSACTION2_FNEXT_REQ *pSMB = NULL; TRANSACTION2_FNEXT_RSP *pSMBr = NULL; T2_FNEXT_RSP_PARMS *parms; char *response_data; int rc = 0; int bytes_returned, name_len; __u16 params, byte_count; cFYI(1, "In FindNext"); if (psrch_inf->endOfSearch) return -ENOENT; rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; params = 14; /* includes 2 bytes of null string, converted to LE below*/ byte_count = 0; pSMB->TotalDataCount = 0; /* no EAs */ pSMB->MaxParameterCount = cpu_to_le16(8); pSMB->MaxDataCount = cpu_to_le16((tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFF00); pSMB->MaxSetupCount = 0; pSMB->Reserved = 0; pSMB->Flags = 0; pSMB->Timeout = 0; pSMB->Reserved2 = 0; pSMB->ParameterOffset = cpu_to_le16( offsetof(struct smb_com_transaction2_fnext_req,SearchHandle) - 4); pSMB->DataCount = 0; pSMB->DataOffset = 0; pSMB->SetupCount = 1; pSMB->Reserved3 = 0; pSMB->SubCommand = cpu_to_le16(TRANS2_FIND_NEXT); pSMB->SearchHandle = searchHandle; /* always kept as le */ pSMB->SearchCount = cpu_to_le16(CIFSMaxBufSize / sizeof(FILE_UNIX_INFO)); pSMB->InformationLevel = cpu_to_le16(psrch_inf->info_level); pSMB->ResumeKey = psrch_inf->resume_key; pSMB->SearchFlags = cpu_to_le16(CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME); name_len = psrch_inf->resume_name_len; params += name_len; if (name_len < PATH_MAX) { memcpy(pSMB->ResumeFileName, psrch_inf->presume_name, name_len); byte_count += name_len; /* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] = 0; pSMB->ResumeFileName[name_len+1] = 0; } else { rc = -EINVAL; goto FNext2_err_exit; } byte_count = params + 1 /* pad */ ; pSMB->TotalParameterCount = cpu_to_le16(params); pSMB->ParameterCount = pSMB->TotalParameterCount; inc_rfc1001_len(pSMB, byte_count); pSMB->ByteCount = cpu_to_le16(byte_count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); cifs_stats_inc(&tcon->num_fnext); if (rc) { if (rc == -EBADF) { psrch_inf->endOfSearch = true; cifs_buf_release(pSMB); rc = 0; /* search probably was closed at end of search*/ } else cFYI(1, "FindNext returned = %d", rc); } else { /* decode response */ rc = validate_t2((struct smb_t2_rsp *)pSMBr); if (rc == 0) { unsigned int lnoff; /* BB fixme add lock for file (srch_info) struct here */ if (pSMBr->hdr.Flags2 & SMBFLG2_UNICODE) psrch_inf->unicode = true; else psrch_inf->unicode = false; response_data = (char *) &pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.ParameterOffset); parms = (T2_FNEXT_RSP_PARMS *)response_data; response_data = (char *)&pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.DataOffset); if (psrch_inf->smallBuf) cifs_small_buf_release( psrch_inf->ntwrk_buf_start); else cifs_buf_release(psrch_inf->ntwrk_buf_start); psrch_inf->srch_entries_start = response_data; psrch_inf->ntwrk_buf_start = (char *)pSMB; psrch_inf->smallBuf = 0; if (parms->EndofSearch) psrch_inf->endOfSearch = true; else psrch_inf->endOfSearch = false; psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; lnoff = le16_to_cpu(parms->LastNameOffset); if (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE < lnoff) { cERROR(1, "ignoring corrupt resume name"); psrch_inf->last_entry = NULL; return rc; } else psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; /* cFYI(1, "fnxt2 entries in buf %d index_of_last %d", psrch_inf->entries_in_buffer, psrch_inf->index_of_last_entry); */ /* BB fixme add unlock here */ } } /* BB On error, should we leave previous search buf (and count and last entry fields) intact or free the previous one? */ /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ FNext2_err_exit: if (rc != 0) cifs_buf_release(pSMB); return rc; } Commit Message: cifs: fix possible memory corruption in CIFSFindNext The name_len variable in CIFSFindNext is a signed int that gets set to the resume_name_len in the cifs_search_info. The resume_name_len however is unsigned and for some infolevels is populated directly from a 32 bit value sent by the server. If the server sends a very large value for this, then that value could look negative when converted to a signed int. That would make that value pass the PATH_MAX check later in CIFSFindNext. The name_len would then be used as a length value for a memcpy. It would then be treated as unsigned again, and the memcpy scribbles over a ton of memory. Fix this by making the name_len an unsigned value in CIFSFindNext. Cc: <[email protected]> Reported-by: Darren Lavender <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> CWE ID: CWE-189
int CIFSFindNext(const int xid, struct cifs_tcon *tcon, __u16 searchHandle, struct cifs_search_info *psrch_inf) { TRANSACTION2_FNEXT_REQ *pSMB = NULL; TRANSACTION2_FNEXT_RSP *pSMBr = NULL; T2_FNEXT_RSP_PARMS *parms; char *response_data; int rc = 0; int bytes_returned; unsigned int name_len; __u16 params, byte_count; cFYI(1, "In FindNext"); if (psrch_inf->endOfSearch) return -ENOENT; rc = smb_init(SMB_COM_TRANSACTION2, 15, tcon, (void **) &pSMB, (void **) &pSMBr); if (rc) return rc; params = 14; /* includes 2 bytes of null string, converted to LE below*/ byte_count = 0; pSMB->TotalDataCount = 0; /* no EAs */ pSMB->MaxParameterCount = cpu_to_le16(8); pSMB->MaxDataCount = cpu_to_le16((tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE) & 0xFFFFFF00); pSMB->MaxSetupCount = 0; pSMB->Reserved = 0; pSMB->Flags = 0; pSMB->Timeout = 0; pSMB->Reserved2 = 0; pSMB->ParameterOffset = cpu_to_le16( offsetof(struct smb_com_transaction2_fnext_req,SearchHandle) - 4); pSMB->DataCount = 0; pSMB->DataOffset = 0; pSMB->SetupCount = 1; pSMB->Reserved3 = 0; pSMB->SubCommand = cpu_to_le16(TRANS2_FIND_NEXT); pSMB->SearchHandle = searchHandle; /* always kept as le */ pSMB->SearchCount = cpu_to_le16(CIFSMaxBufSize / sizeof(FILE_UNIX_INFO)); pSMB->InformationLevel = cpu_to_le16(psrch_inf->info_level); pSMB->ResumeKey = psrch_inf->resume_key; pSMB->SearchFlags = cpu_to_le16(CIFS_SEARCH_CLOSE_AT_END | CIFS_SEARCH_RETURN_RESUME); name_len = psrch_inf->resume_name_len; params += name_len; if (name_len < PATH_MAX) { memcpy(pSMB->ResumeFileName, psrch_inf->presume_name, name_len); byte_count += name_len; /* 14 byte parm len above enough for 2 byte null terminator */ pSMB->ResumeFileName[name_len] = 0; pSMB->ResumeFileName[name_len+1] = 0; } else { rc = -EINVAL; goto FNext2_err_exit; } byte_count = params + 1 /* pad */ ; pSMB->TotalParameterCount = cpu_to_le16(params); pSMB->ParameterCount = pSMB->TotalParameterCount; inc_rfc1001_len(pSMB, byte_count); pSMB->ByteCount = cpu_to_le16(byte_count); rc = SendReceive(xid, tcon->ses, (struct smb_hdr *) pSMB, (struct smb_hdr *) pSMBr, &bytes_returned, 0); cifs_stats_inc(&tcon->num_fnext); if (rc) { if (rc == -EBADF) { psrch_inf->endOfSearch = true; cifs_buf_release(pSMB); rc = 0; /* search probably was closed at end of search*/ } else cFYI(1, "FindNext returned = %d", rc); } else { /* decode response */ rc = validate_t2((struct smb_t2_rsp *)pSMBr); if (rc == 0) { unsigned int lnoff; /* BB fixme add lock for file (srch_info) struct here */ if (pSMBr->hdr.Flags2 & SMBFLG2_UNICODE) psrch_inf->unicode = true; else psrch_inf->unicode = false; response_data = (char *) &pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.ParameterOffset); parms = (T2_FNEXT_RSP_PARMS *)response_data; response_data = (char *)&pSMBr->hdr.Protocol + le16_to_cpu(pSMBr->t2.DataOffset); if (psrch_inf->smallBuf) cifs_small_buf_release( psrch_inf->ntwrk_buf_start); else cifs_buf_release(psrch_inf->ntwrk_buf_start); psrch_inf->srch_entries_start = response_data; psrch_inf->ntwrk_buf_start = (char *)pSMB; psrch_inf->smallBuf = 0; if (parms->EndofSearch) psrch_inf->endOfSearch = true; else psrch_inf->endOfSearch = false; psrch_inf->entries_in_buffer = le16_to_cpu(parms->SearchCount); psrch_inf->index_of_last_entry += psrch_inf->entries_in_buffer; lnoff = le16_to_cpu(parms->LastNameOffset); if (tcon->ses->server->maxBuf - MAX_CIFS_HDR_SIZE < lnoff) { cERROR(1, "ignoring corrupt resume name"); psrch_inf->last_entry = NULL; return rc; } else psrch_inf->last_entry = psrch_inf->srch_entries_start + lnoff; /* cFYI(1, "fnxt2 entries in buf %d index_of_last %d", psrch_inf->entries_in_buffer, psrch_inf->index_of_last_entry); */ /* BB fixme add unlock here */ } } /* BB On error, should we leave previous search buf (and count and last entry fields) intact or free the previous one? */ /* Note: On -EAGAIN error only caller can retry on handle based calls since file handle passed in no longer valid */ FNext2_err_exit: if (rc != 0) cifs_buf_release(pSMB); return rc; }
165,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ih264d_init_decoder(void * ps_dec_params) { dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params; dec_slice_params_t *ps_cur_slice; pocstruct_t *ps_prev_poc, *ps_cur_poc; /* Free any dynamic buffers that are allocated */ ih264d_free_dynamic_bufs(ps_dec); ps_cur_slice = ps_dec->ps_cur_slice; ps_dec->init_done = 0; ps_dec->u4_num_cores = 1; ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0; ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE; ps_dec->u4_app_disable_deblk_frm = 0; ps_dec->i4_degrade_type = 0; ps_dec->i4_degrade_pics = 0; ps_dec->i4_app_skip_mode = IVD_SKIP_NONE; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; memset(ps_dec->ps_pps, 0, ((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS)); memset(ps_dec->ps_sps, 0, ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS)); /* Initialization of function pointers ih264d_deblock_picture function*/ ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff; ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff; ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec; ps_dec->u4_num_fld_in_frm = 0; ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec; /* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/ ps_dec->ps_sei->u1_is_valid = 0; /* decParams Initializations */ ps_dec->ps_cur_pps = NULL; ps_dec->ps_cur_sps = NULL; ps_dec->u1_init_dec_flag = 0; ps_dec->u1_first_slice_in_stream = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u4_app_disp_width = 0; ps_dec->i4_header_decoded = 0; ps_dec->u4_total_frames_decoded = 0; ps_dec->i4_error_code = 0; ps_dec->i4_content_type = -1; ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0; ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS; ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN; ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT; ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME; ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN; ps_dec->u1_pr_sl_type = 0xFF; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; ps_dec->u2_total_mbs_coded = 0; /* POC initializations */ ps_prev_poc = &ps_dec->s_prev_pic_poc; ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0] = 0; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1] = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count = 0; ps_prev_poc->i4_bottom_field_order_count = ps_cur_poc->i4_bottom_field_order_count = 0; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0; ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = 0; ps_dec->i4_max_poc = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->u1_recon_mb_grp = 4; /* Field PIC initializations */ ps_dec->u1_second_field = 0; ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; /* Set the cropping parameters as zero */ ps_dec->u2_crop_offset_y = 0; ps_dec->u2_crop_offset_uv = 0; /* The Initial Frame Rate Info is not Present */ ps_dec->i4_vui_frame_rate = -1; ps_dec->i4_pic_type = -1; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u1_res_changed = 0; ps_dec->u1_frame_decoded_flag = 0; /* Set the default frame seek mask mode */ ps_dec->u4_skip_frm_mask = SKIP_NONE; /********************************************************/ /* Initialize CAVLC residual decoding function pointers */ /********************************************************/ ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1; ps_dec->pf_cavlc_4x4res_block[1] = ih264d_cavlc_4x4res_block_totalcoeff_2to10; ps_dec->pf_cavlc_4x4res_block[2] = ih264d_cavlc_4x4res_block_totalcoeff_11to16; ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7; ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8; ps_dec->pf_cavlc_parse_8x8block[0] = ih264d_cavlc_parse_8x8block_none_available; ps_dec->pf_cavlc_parse_8x8block[1] = ih264d_cavlc_parse_8x8block_left_available; ps_dec->pf_cavlc_parse_8x8block[2] = ih264d_cavlc_parse_8x8block_top_available; ps_dec->pf_cavlc_parse_8x8block[3] = ih264d_cavlc_parse_8x8block_both_available; /***************************************************************************/ /* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */ /***************************************************************************/ ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice; ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice; ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice; ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice; ps_dec->pf_fill_bs_xtra_left_edge[0] = ih264d_fill_bs_xtra_left_edge_cur_frm; ps_dec->pf_fill_bs_xtra_left_edge[1] = ih264d_fill_bs_xtra_left_edge_cur_fld; /* Initialize Reference Pic Buffers */ ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr); ps_dec->u2_prv_frame_num = 0; ps_dec->u1_top_bottom_decoded = 0; ps_dec->u1_dangling_field = 0; ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table; ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0]; ps_dec->pi1_left_ref_idx_ctxt_inc = &ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0]; ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb; /* ! */ /* Initializing flush frame u4_flag */ ps_dec->u1_flushfrm = 0; { ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec; ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec; ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec; ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec; } memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t)); memset(ps_dec->u4_disp_buf_mapping, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); memset(ps_dec->u4_disp_buf_to_be_freed, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); ih264d_init_arch(ps_dec); ih264d_init_function_ptr(ps_dec); ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT; ps_dec->init_done = 1; } Commit Message: Decoder: Memset few structures to zero to handle error clips Bug: 27907656 Change-Id: I671d135dd5c324c39b4ede990b7225d52ba882cd CWE ID: CWE-20
void ih264d_init_decoder(void * ps_dec_params) { dec_struct_t * ps_dec = (dec_struct_t *)ps_dec_params; dec_slice_params_t *ps_cur_slice; pocstruct_t *ps_prev_poc, *ps_cur_poc; WORD32 size; size = sizeof(pred_info_t) * 2 * 32; memset(ps_dec->ps_pred, 0 , size); size = sizeof(disp_mgr_t); memset(ps_dec->pv_disp_buf_mgr, 0 , size); size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size(); memset(ps_dec->pv_pic_buf_mgr, 0, size); size = sizeof(dec_err_status_t); memset(ps_dec->ps_dec_err_status, 0, size); size = sizeof(sei); memset(ps_dec->ps_sei, 0, size); size = sizeof(dpb_commands_t); memset(ps_dec->ps_dpb_cmds, 0, size); size = sizeof(dec_bit_stream_t); memset(ps_dec->ps_bitstrm, 0, size); size = sizeof(dec_slice_params_t); memset(ps_dec->ps_cur_slice, 0, size); size = MAX(sizeof(dec_seq_params_t), sizeof(dec_pic_params_t)); memset(ps_dec->pv_scratch_sps_pps, 0, size); size = sizeof(ctxt_inc_mb_info_t); memset(ps_dec->ps_left_mb_ctxt_info, 0, size); size = (sizeof(neighbouradd_t) << 2); memset(ps_dec->ps_left_mvpred_addr, 0 ,size); size = sizeof(buf_mgr_t) + ithread_get_mutex_lock_size(); memset(ps_dec->pv_mv_buf_mgr, 0, size); /* Free any dynamic buffers that are allocated */ ih264d_free_dynamic_bufs(ps_dec); ps_cur_slice = ps_dec->ps_cur_slice; ps_dec->init_done = 0; ps_dec->u4_num_cores = 1; ps_dec->u2_pic_ht = ps_dec->u2_pic_wd = 0; ps_dec->u1_separate_parse = DEFAULT_SEPARATE_PARSE; ps_dec->u4_app_disable_deblk_frm = 0; ps_dec->i4_degrade_type = 0; ps_dec->i4_degrade_pics = 0; ps_dec->i4_app_skip_mode = IVD_SKIP_NONE; ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; memset(ps_dec->ps_pps, 0, ((sizeof(dec_pic_params_t)) * MAX_NUM_PIC_PARAMS)); memset(ps_dec->ps_sps, 0, ((sizeof(dec_seq_params_t)) * MAX_NUM_SEQ_PARAMS)); /* Initialization of function pointers ih264d_deblock_picture function*/ ps_dec->p_DeblockPicture[0] = ih264d_deblock_picture_non_mbaff; ps_dec->p_DeblockPicture[1] = ih264d_deblock_picture_mbaff; ps_dec->s_cab_dec_env.pv_codec_handle = ps_dec; ps_dec->u4_num_fld_in_frm = 0; ps_dec->ps_dpb_mgr->pv_codec_handle = ps_dec; /* Initialize the sei validity u4_flag with zero indiacting sei is not valid*/ ps_dec->ps_sei->u1_is_valid = 0; /* decParams Initializations */ ps_dec->ps_cur_pps = NULL; ps_dec->ps_cur_sps = NULL; ps_dec->u1_init_dec_flag = 0; ps_dec->u1_first_slice_in_stream = 1; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_last_pic_not_decoded = 0; ps_dec->u4_app_disp_width = 0; ps_dec->i4_header_decoded = 0; ps_dec->u4_total_frames_decoded = 0; ps_dec->i4_error_code = 0; ps_dec->i4_content_type = -1; ps_dec->ps_cur_slice->u1_mbaff_frame_flag = 0; ps_dec->ps_dec_err_status->u1_err_flag = ACCEPT_ALL_PICS; //REJECT_PB_PICS; ps_dec->ps_dec_err_status->u1_cur_pic_type = PIC_TYPE_UNKNOWN; ps_dec->ps_dec_err_status->u4_frm_sei_sync = SYNC_FRM_DEFAULT; ps_dec->ps_dec_err_status->u4_cur_frm = INIT_FRAME; ps_dec->ps_dec_err_status->u1_pic_aud_i = PIC_TYPE_UNKNOWN; ps_dec->u1_pr_sl_type = 0xFF; ps_dec->u2_mbx = 0xffff; ps_dec->u2_mby = 0; ps_dec->u2_total_mbs_coded = 0; /* POC initializations */ ps_prev_poc = &ps_dec->s_prev_pic_poc; ps_cur_poc = &ps_dec->s_cur_pic_poc; ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb = 0; ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb = 0; ps_prev_poc->i4_delta_pic_order_cnt_bottom = ps_cur_poc->i4_delta_pic_order_cnt_bottom = 0; ps_prev_poc->i4_delta_pic_order_cnt[0] = ps_cur_poc->i4_delta_pic_order_cnt[0] = 0; ps_prev_poc->i4_delta_pic_order_cnt[1] = ps_cur_poc->i4_delta_pic_order_cnt[1] = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_top_field_order_count = ps_cur_poc->i4_top_field_order_count = 0; ps_prev_poc->i4_bottom_field_order_count = ps_cur_poc->i4_bottom_field_order_count = 0; ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field = 0; ps_prev_poc->u1_mmco_equalto5 = ps_cur_poc->u1_mmco_equalto5 = 0; ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst = 0; ps_cur_slice->u1_mmco_equalto5 = 0; ps_cur_slice->u2_frame_num = 0; ps_dec->i4_max_poc = 0; ps_dec->i4_prev_max_display_seq = 0; ps_dec->u1_recon_mb_grp = 4; /* Field PIC initializations */ ps_dec->u1_second_field = 0; ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; /* Set the cropping parameters as zero */ ps_dec->u2_crop_offset_y = 0; ps_dec->u2_crop_offset_uv = 0; /* The Initial Frame Rate Info is not Present */ ps_dec->i4_vui_frame_rate = -1; ps_dec->i4_pic_type = -1; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u1_res_changed = 0; ps_dec->u1_frame_decoded_flag = 0; /* Set the default frame seek mask mode */ ps_dec->u4_skip_frm_mask = SKIP_NONE; /********************************************************/ /* Initialize CAVLC residual decoding function pointers */ /********************************************************/ ps_dec->pf_cavlc_4x4res_block[0] = ih264d_cavlc_4x4res_block_totalcoeff_1; ps_dec->pf_cavlc_4x4res_block[1] = ih264d_cavlc_4x4res_block_totalcoeff_2to10; ps_dec->pf_cavlc_4x4res_block[2] = ih264d_cavlc_4x4res_block_totalcoeff_11to16; ps_dec->pf_cavlc_parse4x4coeff[0] = ih264d_cavlc_parse4x4coeff_n0to7; ps_dec->pf_cavlc_parse4x4coeff[1] = ih264d_cavlc_parse4x4coeff_n8; ps_dec->pf_cavlc_parse_8x8block[0] = ih264d_cavlc_parse_8x8block_none_available; ps_dec->pf_cavlc_parse_8x8block[1] = ih264d_cavlc_parse_8x8block_left_available; ps_dec->pf_cavlc_parse_8x8block[2] = ih264d_cavlc_parse_8x8block_top_available; ps_dec->pf_cavlc_parse_8x8block[3] = ih264d_cavlc_parse_8x8block_both_available; /***************************************************************************/ /* Initialize Bs calculation function pointers for P and B, 16x16/non16x16 */ /***************************************************************************/ ps_dec->pf_fill_bs1[0][0] = ih264d_fill_bs1_16x16mb_pslice; ps_dec->pf_fill_bs1[0][1] = ih264d_fill_bs1_non16x16mb_pslice; ps_dec->pf_fill_bs1[1][0] = ih264d_fill_bs1_16x16mb_bslice; ps_dec->pf_fill_bs1[1][1] = ih264d_fill_bs1_non16x16mb_bslice; ps_dec->pf_fill_bs_xtra_left_edge[0] = ih264d_fill_bs_xtra_left_edge_cur_frm; ps_dec->pf_fill_bs_xtra_left_edge[1] = ih264d_fill_bs_xtra_left_edge_cur_fld; /* Initialize Reference Pic Buffers */ ih264d_init_ref_bufs(ps_dec->ps_dpb_mgr); ps_dec->u2_prv_frame_num = 0; ps_dec->u1_top_bottom_decoded = 0; ps_dec->u1_dangling_field = 0; ps_dec->s_cab_dec_env.cabac_table = gau4_ih264d_cabac_table; ps_dec->pu1_left_mv_ctxt_inc = ps_dec->u1_left_mv_ctxt_inc_arr[0]; ps_dec->pi1_left_ref_idx_ctxt_inc = &ps_dec->i1_left_ref_idx_ctx_inc_arr[0][0]; ps_dec->pu1_left_yuv_dc_csbp = &ps_dec->u1_yuv_dc_csbp_topmb; /* ! */ /* Initializing flush frame u4_flag */ ps_dec->u1_flushfrm = 0; { ps_dec->s_cab_dec_env.pv_codec_handle = (void*)ps_dec; ps_dec->ps_bitstrm->pv_codec_handle = (void*)ps_dec; ps_dec->ps_cur_slice->pv_codec_handle = (void*)ps_dec; ps_dec->ps_dpb_mgr->pv_codec_handle = (void*)ps_dec; } memset(ps_dec->disp_bufs, 0, (MAX_DISP_BUFS_NEW) * sizeof(disp_buf_t)); memset(ps_dec->u4_disp_buf_mapping, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); memset(ps_dec->u4_disp_buf_to_be_freed, 0, (MAX_DISP_BUFS_NEW) * sizeof(UWORD32)); ih264d_init_arch(ps_dec); ih264d_init_function_ptr(ps_dec); ps_dec->e_frm_out_mode = IVD_DISPLAY_FRAME_OUT; ps_dec->init_done = 1; }
173,758
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CCThreadProxy::stop() { TRACE_EVENT("CCThreadProxy::stop", this, 0); ASSERT(isMainThread()); ASSERT(m_started); CCCompletionEvent completion; s_ccThread->postTask(createCCThreadTask(this, &CCThreadProxy::layerTreeHostClosedOnCCThread, AllowCrossThreadAccess(&completion))); completion.wait(); ASSERT(!m_layerTreeHostImpl); // verify that the impl deleted. m_layerTreeHost = 0; m_started = false; } Commit Message: [chromium] Fix shutdown race when posting main thread task to CCThreadProxy and enable tests https://bugs.webkit.org/show_bug.cgi?id=70161 Reviewed by David Levin. Source/WebCore: Adds a weak pointer mechanism to cancel main thread tasks posted to CCThreadProxy instances from the compositor thread. Previously there was a race condition where main thread tasks could run even after the CCThreadProxy was destroyed. This race does not exist in the other direction because when tearing down a CCThreadProxy we first post a quit task to the compositor thread and then suspend execution of the main thread until all compositor tasks for the CCThreadProxy have been drained. Covered by the now-enabled CCLayerTreeHostTest* unit tests. * WebCore.gypi: * platform/graphics/chromium/cc/CCScopedMainThreadProxy.h: Added. (WebCore::CCScopedMainThreadProxy::create): (WebCore::CCScopedMainThreadProxy::postTask): (WebCore::CCScopedMainThreadProxy::shutdown): (WebCore::CCScopedMainThreadProxy::CCScopedMainThreadProxy): (WebCore::CCScopedMainThreadProxy::runTaskIfNotShutdown): * platform/graphics/chromium/cc/CCThreadProxy.cpp: (WebCore::CCThreadProxy::CCThreadProxy): (WebCore::CCThreadProxy::~CCThreadProxy): (WebCore::CCThreadProxy::createBeginFrameAndCommitTaskOnCCThread): * platform/graphics/chromium/cc/CCThreadProxy.h: Source/WebKit/chromium: Enables the CCLayerTreeHostTest* tests by default. Most tests are run twice in a single thread and multiple thread configuration. Some tests run only in the multiple thread configuration if they depend on the compositor thread scheduling draws by itself. * tests/CCLayerTreeHostTest.cpp: (::CCLayerTreeHostTest::timeout): (::CCLayerTreeHostTest::clearTimeout): (::CCLayerTreeHostTest::CCLayerTreeHostTest): (::CCLayerTreeHostTest::onEndTest): (::CCLayerTreeHostTest::TimeoutTask::TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::clearTest): (::CCLayerTreeHostTest::TimeoutTask::~TimeoutTask): (::CCLayerTreeHostTest::TimeoutTask::Run): (::CCLayerTreeHostTest::runTest): (::CCLayerTreeHostTest::doBeginTest): (::CCLayerTreeHostTestThreadOnly::runTest): (::CCLayerTreeHostTestSetNeedsRedraw::commitCompleteOnCCThread): git-svn-id: svn://svn.chromium.org/blink/trunk@97784 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void CCThreadProxy::stop() { TRACE_EVENT("CCThreadProxy::stop", this, 0); ASSERT(isMainThread()); ASSERT(m_started); CCCompletionEvent completion; s_ccThread->postTask(createCCThreadTask(this, &CCThreadProxy::layerTreeHostClosedOnCCThread, AllowCrossThreadAccess(&completion))); completion.wait(); m_mainThreadProxy->shutdown(); // Stop running tasks posted to us. ASSERT(!m_layerTreeHostImpl); // verify that the impl deleted. m_layerTreeHost = 0; m_started = false; }
170,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending() && !was_select_cache_called_); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return; } FinishCacheSelection(NULL, NULL); } Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer. BUG=551044 Review URL: https://codereview.chromium.org/1418783005 Cr-Commit-Position: refs/heads/master@{#358815} CWE ID:
void AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { bool AppCacheHost::SelectCacheForSharedWorker(int64 appcache_id) { if (was_select_cache_called_) return false; DCHECK(pending_start_update_callback_.is_null() && pending_swap_cache_callback_.is_null() && pending_get_status_callback_.is_null() && !is_selection_pending()); was_select_cache_called_ = true; if (appcache_id != kAppCacheNoCacheId) { LoadSelectedCache(appcache_id); return true; } FinishCacheSelection(NULL, NULL); return true; }
171,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t safecat(char *buffer, size_t bufsize, size_t pos, PNG_CONST char *cat) { while (pos < bufsize && cat != NULL && *cat != 0) buffer[pos++] = *cat++; if (pos >= bufsize) pos = bufsize-1; buffer[pos] = 0; return pos; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static size_t safecat(char *buffer, size_t bufsize, size_t pos, const char *cat) { while (pos < bufsize && cat != NULL && *cat != 0) buffer[pos++] = *cat++; if (pos >= bufsize) pos = bufsize-1; buffer[pos] = 0; return pos; }
173,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: append_quoted (struct stringbuf *sb, const unsigned char *value, size_t length, int skip) { unsigned char tmp[4]; const unsigned char *s = value; size_t n = 0; for (;;) { for (value = s; n+skip < length; n++, s++) { s += skip; n += skip; if (*s < ' ' || *s > 126 || strchr (",+\"\\<>;", *s) ) break; } if (s != value) put_stringbuf_mem_skip (sb, value, s-value, skip); if (n+skip >= length) return; /* ready */ s += skip; n += skip; if ( *s < ' ' || *s > 126 ) { sprintf (tmp, "\\%02X", *s); put_stringbuf_mem (sb, tmp, 3); } else { tmp[0] = '\\'; tmp[1] = *s; put_stringbuf_mem (sb, tmp, 2); } n++; s++; } } Commit Message: CWE ID: CWE-119
append_quoted (struct stringbuf *sb, const unsigned char *value, size_t length, int skip) { unsigned char tmp[4]; const unsigned char *s = value; size_t n = 0; for (;;) { for (value = s; n+skip < length; n++, s++) { s += skip; n += skip; if (*s < ' ' || *s > 126 || strchr (",+\"\\<>;", *s) ) break; } if (s != value) put_stringbuf_mem_skip (sb, value, s-value, skip); if (n+skip >= length) return; /* ready */ s += skip; n += skip; if ( *s < ' ' || *s > 126 ) { snprintf (tmp, sizeof tmp, "\\%02X", *s); put_stringbuf_mem (sb, tmp, 3); } else { tmp[0] = '\\'; tmp[1] = *s; put_stringbuf_mem (sb, tmp, 2); } n++; s++; } }
165,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: i915_gem_execbuffer2(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list = NULL; int ret; if (args->buffer_count < 1) { DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count); return -EINVAL; } exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (exec2_list == NULL) exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %d buffers\n", args->buffer_count); return -ENOMEM; } ret = copy_from_user(exec2_list, (struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, sizeof(*exec2_list) * args->buffer_count); if (ret != 0) { DRM_DEBUG("copy %d exec entries failed %d\n", args->buffer_count, ret); drm_free_large(exec2_list); return -EFAULT; } ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list); if (!ret) { /* Copy the new buffer offsets back to the user's exec list. */ ret = copy_to_user((struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, exec2_list, sizeof(*exec2_list) * args->buffer_count); if (ret) { ret = -EFAULT; DRM_DEBUG("failed to copy %d exec entries " "back to user (%d)\n", args->buffer_count, ret); } } drm_free_large(exec2_list); return ret; } Commit Message: drm/i915: fix integer overflow in i915_gem_execbuffer2() On 32-bit systems, a large args->buffer_count from userspace via ioctl may overflow the allocation size, leading to out-of-bounds access. This vulnerability was introduced in commit 8408c282 ("drm/i915: First try a normal large kmalloc for the temporary exec buffers"). Signed-off-by: Xi Wang <[email protected]> Reviewed-by: Chris Wilson <[email protected]> Cc: [email protected] Signed-off-by: Daniel Vetter <[email protected]> CWE ID: CWE-189
i915_gem_execbuffer2(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list = NULL; int ret; if (args->buffer_count < 1 || args->buffer_count > UINT_MAX / sizeof(*exec2_list)) { DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count); return -EINVAL; } exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (exec2_list == NULL) exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %d buffers\n", args->buffer_count); return -ENOMEM; } ret = copy_from_user(exec2_list, (struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, sizeof(*exec2_list) * args->buffer_count); if (ret != 0) { DRM_DEBUG("copy %d exec entries failed %d\n", args->buffer_count, ret); drm_free_large(exec2_list); return -EFAULT; } ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list); if (!ret) { /* Copy the new buffer offsets back to the user's exec list. */ ret = copy_to_user((struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, exec2_list, sizeof(*exec2_list) * args->buffer_count); if (ret) { ret = -EFAULT; DRM_DEBUG("failed to copy %d exec entries " "back to user (%d)\n", args->buffer_count, ret); } } drm_free_large(exec2_list); return ret; }
165,597
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SavePayload(size_t handle, uint32_t *payload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp && payload) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp); } return; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
void SavePayload(size_t handle, uint32_t *payload, uint32_t index) void LongSeek(mp4object *mp4, int64_t offset) { if (mp4 && offset) { if (mp4->filepos + offset < mp4->filesize) { LONGSEEK(mp4->mediafp, offset, SEEK_CUR); mp4->filepos += offset; } else { mp4->filepos = mp4->filesize; } } }
169,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) { struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr sock; int lock_fd, i; const char *lock_path = "/tmp/.ctdb_socket_lock"; struct flock lock; int one = 1; int sock_size; struct tevent_fd *fde; /* If there are no nodes, then it won't be possible to find * the first one. Log a failure and short circuit the whole * process. */ if (ctdb->num_nodes == 0) { DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n")); return -1; } /* in order to ensure that we don't get two nodes with the same adddress, we must make the bind() and listen() calls atomic. The SO_REUSEADDR setsockopt only prevents double binds if the first socket is in LISTEN state */ lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666); if (lock_fd == -1) { DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path)); return -1; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; if (fcntl(lock_fd, F_SETLKW, &lock) != 0) { DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path)); close(lock_fd); return -1; } for (i=0; i < ctdb->num_nodes; i++) { if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) { continue; } ZERO_STRUCT(sock); if (ctdb_tcp_get_address(ctdb, ctdb->nodes[i]->address.address, &sock) != 0) { continue; } switch (sock.sa.sa_family) { case AF_INET: sock.ip.sin_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip); break; case AF_INET6: sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip6); break; default: DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n", sock.sa.sa_family)); continue; } #ifdef HAVE_SOCK_SIN_LEN sock.ip.sin_len = sock_size; #endif ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (ctcp->listen_fd == -1) { ctdb_set_error(ctdb, "socket failed\n"); continue; } set_close_on_exec(ctcp->listen_fd); setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)); if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) { break; } if (errno == EADDRNOTAVAIL) { DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } else { DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } } if (i == ctdb->num_nodes) { DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n")); goto failed; } ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address); ctdb->address.port = ctdb->nodes[i]->address.port; ctdb->name = talloc_asprintf(ctdb, "%s:%u", ctdb->address.address, ctdb->address.port); ctdb->pnn = ctdb->nodes[i]->pnn; DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n", ctdb->address.address, ctdb->address.port, ctdb->pnn)); if (listen(ctcp->listen_fd, 10) == -1) { goto failed; } fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ, ctdb_listen_event, ctdb); tevent_fd_set_auto_close(fde); close(lock_fd); return 0; failed: close(lock_fd); close(ctcp->listen_fd); ctcp->listen_fd = -1; return -1; } Commit Message: CWE ID: CWE-264
static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) { struct ctdb_tcp *ctcp = talloc_get_type(ctdb->private_data, struct ctdb_tcp); ctdb_sock_addr sock; int lock_fd, i; const char *lock_path = VARDIR "/run/ctdb/.socket_lock"; struct flock lock; int one = 1; int sock_size; struct tevent_fd *fde; /* If there are no nodes, then it won't be possible to find * the first one. Log a failure and short circuit the whole * process. */ if (ctdb->num_nodes == 0) { DEBUG(DEBUG_CRIT,("No nodes available to attempt bind to - is the nodes file empty?\n")); return -1; } /* in order to ensure that we don't get two nodes with the same adddress, we must make the bind() and listen() calls atomic. The SO_REUSEADDR setsockopt only prevents double binds if the first socket is in LISTEN state */ lock_fd = open(lock_path, O_RDWR|O_CREAT, 0666); if (lock_fd == -1) { DEBUG(DEBUG_CRIT,("Unable to open %s\n", lock_path)); return -1; } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 1; lock.l_pid = 0; if (fcntl(lock_fd, F_SETLKW, &lock) != 0) { DEBUG(DEBUG_CRIT,("Unable to lock %s\n", lock_path)); close(lock_fd); return -1; } for (i=0; i < ctdb->num_nodes; i++) { if (ctdb->nodes[i]->flags & NODE_FLAGS_DELETED) { continue; } ZERO_STRUCT(sock); if (ctdb_tcp_get_address(ctdb, ctdb->nodes[i]->address.address, &sock) != 0) { continue; } switch (sock.sa.sa_family) { case AF_INET: sock.ip.sin_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip); break; case AF_INET6: sock.ip6.sin6_port = htons(ctdb->nodes[i]->address.port); sock_size = sizeof(sock.ip6); break; default: DEBUG(DEBUG_ERR, (__location__ " unknown family %u\n", sock.sa.sa_family)); continue; } #ifdef HAVE_SOCK_SIN_LEN sock.ip.sin_len = sock_size; #endif ctcp->listen_fd = socket(sock.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); if (ctcp->listen_fd == -1) { ctdb_set_error(ctdb, "socket failed\n"); continue; } set_close_on_exec(ctcp->listen_fd); setsockopt(ctcp->listen_fd,SOL_SOCKET,SO_REUSEADDR,(char *)&one,sizeof(one)); if (bind(ctcp->listen_fd, (struct sockaddr * )&sock, sock_size) == 0) { break; } if (errno == EADDRNOTAVAIL) { DEBUG(DEBUG_DEBUG,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } else { DEBUG(DEBUG_ERR,(__location__ " Failed to bind() to socket. %s(%d)\n", strerror(errno), errno)); } } if (i == ctdb->num_nodes) { DEBUG(DEBUG_CRIT,("Unable to bind to any of the node addresses - giving up\n")); goto failed; } ctdb->address.address = talloc_strdup(ctdb, ctdb->nodes[i]->address.address); ctdb->address.port = ctdb->nodes[i]->address.port; ctdb->name = talloc_asprintf(ctdb, "%s:%u", ctdb->address.address, ctdb->address.port); ctdb->pnn = ctdb->nodes[i]->pnn; DEBUG(DEBUG_INFO,("ctdb chose network address %s:%u pnn %u\n", ctdb->address.address, ctdb->address.port, ctdb->pnn)); if (listen(ctcp->listen_fd, 10) == -1) { goto failed; } fde = event_add_fd(ctdb->ev, ctcp, ctcp->listen_fd, EVENT_FD_READ, ctdb_listen_event, ctdb); tevent_fd_set_auto_close(fde); close(lock_fd); return 0; failed: close(lock_fd); close(ctcp->listen_fd); ctcp->listen_fd = -1; return -1; }
165,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void OnImageDecoded(const gfx::Image& decoded_image) { image_decoded_callback_.Run(decoded_image.AsBitmap()); delete this; } Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
void OnImageDecoded(const gfx::Image& decoded_image) {
171,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf14_pop_transparency_group(gs_gstate *pgs, pdf14_ctx *ctx, const pdf14_nonseparable_blending_procs_t * pblend_procs, int tos_num_color_comp, cmm_profile_t *curr_icc_profile, gx_device *dev) { pdf14_buf *tos = ctx->stack; pdf14_buf *nos = tos->saved; pdf14_mask_t *mask_stack = tos->mask_stack; pdf14_buf *maskbuf; int x0, x1, y0, y1; byte *new_data_buf = NULL; int num_noncolor_planes, new_num_planes; int num_cols, num_rows, nos_num_color_comp; bool icc_match; gsicc_rendering_param_t rendering_params; gsicc_link_t *icc_link; gsicc_bufferdesc_t input_buff_desc; gsicc_bufferdesc_t output_buff_desc; pdf14_device *pdev = (pdf14_device *)dev; bool overprint = pdev->overprint; gx_color_index drawn_comps = pdev->drawn_comps; bool nonicc_conversion = true; nos_num_color_comp = nos->parent_color_info_procs->num_components - nos->num_spots; tos_num_color_comp = tos_num_color_comp - tos->num_spots; if (mask_stack == NULL) { maskbuf = NULL; } else { maskbuf = mask_stack->rc_mask->mask_buf; } if (nos == NULL) return_error(gs_error_rangecheck); /* Sanitise the dirty rectangles, in case some of the drawing routines * have made them overly large. */ rect_intersect(tos->dirty, tos->rect); rect_intersect(nos->dirty, nos->rect); /* dirty = the marked bbox. rect = the entire bounds of the buffer. */ /* Everything marked on tos that fits onto nos needs to be merged down. */ y0 = max(tos->dirty.p.y, nos->rect.p.y); y1 = min(tos->dirty.q.y, nos->rect.q.y); x0 = max(tos->dirty.p.x, nos->rect.p.x); x1 = min(tos->dirty.q.x, nos->rect.q.x); if (ctx->mask_stack) { /* This can occur when we have a situation where we are ending out of a group that has internal to it a soft mask and another group. The soft mask left over from the previous trans group pop is put into ctx->masbuf, since it is still active if another trans group push occurs to use it. If one does not occur, but instead we find ourselves popping from a parent group, then this softmask is no longer needed. We will rc_decrement and set it to NULL. */ rc_decrement(ctx->mask_stack->rc_mask, "pdf14_pop_transparency_group"); if (ctx->mask_stack->rc_mask == NULL ){ gs_free_object(ctx->memory, ctx->mask_stack, "pdf14_pop_transparency_group"); } ctx->mask_stack = NULL; } ctx->mask_stack = mask_stack; /* Restore the mask saved by pdf14_push_transparency_group. */ tos->mask_stack = NULL; /* Clean the pointer sinse the mask ownership is now passed to ctx. */ if (tos->idle) goto exit; if (maskbuf != NULL && maskbuf->data == NULL && maskbuf->alpha == 255) goto exit; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_planes, ctx->stack->planestride, ctx->stack->rowstride, "aaTrans_Group_Pop",ctx->stack->data); #endif /* Note currently if a pattern space has transparency, the ICC profile is not used for blending purposes. Instead we rely upon the gray, rgb, or cmyk parent space. This is partially due to the fact that pdf14_pop_transparency_group and pdf14_push_transparnecy_group have no real ICC interaction and those are the operations called in the tile transparency code. Instead we may want to look at pdf14_begin_transparency_group and pdf14_end_transparency group which is where all the ICC information is handled. We will return to look at that later */ if (nos->parent_color_info_procs->icc_profile != NULL) { icc_match = (nos->parent_color_info_procs->icc_profile->hashcode != curr_icc_profile->hashcode); } else { /* Let the other tests make the decision if we need to transform */ icc_match = false; } /* If the color spaces are different and we actually did do a swap of the procs for color */ if ((nos->parent_color_info_procs->parent_color_mapping_procs != NULL && nos_num_color_comp != tos_num_color_comp) || icc_match) { if (x0 < x1 && y0 < y1) { /* The NOS blending color space is different than that of the TOS. It is necessary to transform the TOS buffer data to the color space of the NOS prior to doing the pdf14_compose_group operation. */ num_noncolor_planes = tos->n_planes - tos_num_color_comp; new_num_planes = num_noncolor_planes + nos_num_color_comp; /* See if we are doing ICC based conversion */ if (nos->parent_color_info_procs->icc_profile != NULL && curr_icc_profile != NULL) { /* Use the ICC color management for buffer color conversion */ /* Define the rendering intents */ rendering_params.black_point_comp = gsBLACKPTCOMP_ON; rendering_params.graphics_type_tag = GS_IMAGE_TAG; rendering_params.override_icc = false; rendering_params.preserve_black = gsBKPRESNOTSPECIFIED; rendering_params.rendering_intent = gsPERCEPTUAL; rendering_params.cmm = gsCMM_DEFAULT; /* Request the ICC link for the transform that we will need to use */ /* Note that if pgs is NULL we assume the same color space. This is due to a call to pop the group from fill_mask when filling with a mask with transparency. In that case, the parent and the child will have the same color space anyway */ icc_link = gsicc_get_link_profile(pgs, dev, curr_icc_profile, nos->parent_color_info_procs->icc_profile, &rendering_params, pgs->memory, false); if (icc_link != NULL) { /* if problem with link we will do non-ICC approach */ nonicc_conversion = false; /* If the link is the identity, then we don't need to do any color conversions */ if ( !(icc_link->is_identity) ) { /* Before we do any allocations check if we can get away with reusing the existing buffer if it is the same size ( if it is smaller go ahead and allocate). We could reuse it in this case too. We need to do a bit of testing to determine what would be best. */ /* FIXME: RJW: Could we get away with just color converting * the area that's actually active (i.e. dirty, not rect)? */ if(nos_num_color_comp != tos_num_color_comp) { /* Different size. We will need to allocate */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); /* Copy over the noncolor planes. */ memcpy(new_data_buf + tos->planestride * nos_num_color_comp, tos->data + tos->planestride * tos_num_color_comp, tos->planestride * num_noncolor_planes); } else { /* In place color conversion! */ new_data_buf = tos->data; } /* Set up the buffer descriptors. Note that pdf14 always has the alpha channels at the back end (last planes). We will just handle that here and let the CMM know nothing about it */ num_rows = tos->rect.q.y - tos->rect.p.y; num_cols = tos->rect.q.x - tos->rect.p.x; gsicc_init_buffer(&input_buff_desc, tos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); gsicc_init_buffer(&output_buff_desc, nos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); /* Transform the data. Since the pdf14 device should be using RGB, CMYK or Gray buffers, this transform does not need to worry about the cmap procs of the target device. Those are handled when we do the pdf14 put image operation */ (icc_link->procs.map_buffer)(dev, icc_link, &input_buff_desc, &output_buff_desc, tos->data, new_data_buf); } /* Release the link */ gsicc_release_link(icc_link); /* free the old object if the color spaces were different sizes */ if(!(icc_link->is_identity) && nos_num_color_comp != tos_num_color_comp) { gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } } } if (nonicc_conversion) { /* Non ICC based transform */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); gs_transform_color_buffer_generic(tos->data, tos->rowstride, tos->planestride, tos_num_color_comp, tos->rect, new_data_buf, nos_num_color_comp, num_noncolor_planes); /* Free the old object */ gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } /* Adjust the plane and channel size now */ tos->n_chan = nos->n_chan; tos->n_planes = nos->n_planes; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_chan, ctx->stack->planestride, ctx->stack->rowstride, "aCMTrans_Group_ColorConv",ctx->stack->data); #endif /* compose. never do overprint in this case */ pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, nos->parent_color_info_procs->isadditive, nos->parent_color_info_procs->parent_blending_procs, false, drawn_comps, ctx->memory, dev); } } else { /* Group color spaces are the same. No color conversions needed */ if (x0 < x1 && y0 < y1) pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, ctx->additive, pblend_procs, overprint, drawn_comps, ctx->memory, dev); } exit: ctx->stack = nos; /* We want to detect the cases where we have luminosity soft masks embedded within one another. The "alpha" channel really needs to be merged into the luminosity channel in this case. This will occur during the mask pop */ if (ctx->smask_depth > 0 && maskbuf != NULL) { /* Set the trigger so that we will blend if not alpha. Since we have softmasks embedded in softmasks */ ctx->smask_blend = true; } if_debug1m('v', ctx->memory, "[v]pop buf, idle=%d\n", tos->idle); pdf14_buf_free(tos, ctx->memory); return 0; } Commit Message: CWE ID: CWE-476
pdf14_pop_transparency_group(gs_gstate *pgs, pdf14_ctx *ctx, const pdf14_nonseparable_blending_procs_t * pblend_procs, int tos_num_color_comp, cmm_profile_t *curr_icc_profile, gx_device *dev) { pdf14_buf *tos = ctx->stack; pdf14_buf *nos = tos->saved; pdf14_mask_t *mask_stack = tos->mask_stack; pdf14_buf *maskbuf; int x0, x1, y0, y1; byte *new_data_buf = NULL; int num_noncolor_planes, new_num_planes; int num_cols, num_rows, nos_num_color_comp; bool icc_match; gsicc_rendering_param_t rendering_params; gsicc_link_t *icc_link; gsicc_bufferdesc_t input_buff_desc; gsicc_bufferdesc_t output_buff_desc; pdf14_device *pdev = (pdf14_device *)dev; bool overprint = pdev->overprint; gx_color_index drawn_comps = pdev->drawn_comps; bool nonicc_conversion = true; if (nos == NULL) return_error(gs_error_unknownerror); /* Unmatched group pop */ nos_num_color_comp = nos->parent_color_info_procs->num_components - nos->num_spots; tos_num_color_comp = tos_num_color_comp - tos->num_spots; if (mask_stack == NULL) { maskbuf = NULL; } else { maskbuf = mask_stack->rc_mask->mask_buf; } if (nos == NULL) return_error(gs_error_rangecheck); /* Sanitise the dirty rectangles, in case some of the drawing routines * have made them overly large. */ rect_intersect(tos->dirty, tos->rect); rect_intersect(nos->dirty, nos->rect); /* dirty = the marked bbox. rect = the entire bounds of the buffer. */ /* Everything marked on tos that fits onto nos needs to be merged down. */ y0 = max(tos->dirty.p.y, nos->rect.p.y); y1 = min(tos->dirty.q.y, nos->rect.q.y); x0 = max(tos->dirty.p.x, nos->rect.p.x); x1 = min(tos->dirty.q.x, nos->rect.q.x); if (ctx->mask_stack) { /* This can occur when we have a situation where we are ending out of a group that has internal to it a soft mask and another group. The soft mask left over from the previous trans group pop is put into ctx->masbuf, since it is still active if another trans group push occurs to use it. If one does not occur, but instead we find ourselves popping from a parent group, then this softmask is no longer needed. We will rc_decrement and set it to NULL. */ rc_decrement(ctx->mask_stack->rc_mask, "pdf14_pop_transparency_group"); if (ctx->mask_stack->rc_mask == NULL ){ gs_free_object(ctx->memory, ctx->mask_stack, "pdf14_pop_transparency_group"); } ctx->mask_stack = NULL; } ctx->mask_stack = mask_stack; /* Restore the mask saved by pdf14_push_transparency_group. */ tos->mask_stack = NULL; /* Clean the pointer sinse the mask ownership is now passed to ctx. */ if (tos->idle) goto exit; if (maskbuf != NULL && maskbuf->data == NULL && maskbuf->alpha == 255) goto exit; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_planes, ctx->stack->planestride, ctx->stack->rowstride, "aaTrans_Group_Pop",ctx->stack->data); #endif /* Note currently if a pattern space has transparency, the ICC profile is not used for blending purposes. Instead we rely upon the gray, rgb, or cmyk parent space. This is partially due to the fact that pdf14_pop_transparency_group and pdf14_push_transparnecy_group have no real ICC interaction and those are the operations called in the tile transparency code. Instead we may want to look at pdf14_begin_transparency_group and pdf14_end_transparency group which is where all the ICC information is handled. We will return to look at that later */ if (nos->parent_color_info_procs->icc_profile != NULL) { icc_match = (nos->parent_color_info_procs->icc_profile->hashcode != curr_icc_profile->hashcode); } else { /* Let the other tests make the decision if we need to transform */ icc_match = false; } /* If the color spaces are different and we actually did do a swap of the procs for color */ if ((nos->parent_color_info_procs->parent_color_mapping_procs != NULL && nos_num_color_comp != tos_num_color_comp) || icc_match) { if (x0 < x1 && y0 < y1) { /* The NOS blending color space is different than that of the TOS. It is necessary to transform the TOS buffer data to the color space of the NOS prior to doing the pdf14_compose_group operation. */ num_noncolor_planes = tos->n_planes - tos_num_color_comp; new_num_planes = num_noncolor_planes + nos_num_color_comp; /* See if we are doing ICC based conversion */ if (nos->parent_color_info_procs->icc_profile != NULL && curr_icc_profile != NULL) { /* Use the ICC color management for buffer color conversion */ /* Define the rendering intents */ rendering_params.black_point_comp = gsBLACKPTCOMP_ON; rendering_params.graphics_type_tag = GS_IMAGE_TAG; rendering_params.override_icc = false; rendering_params.preserve_black = gsBKPRESNOTSPECIFIED; rendering_params.rendering_intent = gsPERCEPTUAL; rendering_params.cmm = gsCMM_DEFAULT; /* Request the ICC link for the transform that we will need to use */ /* Note that if pgs is NULL we assume the same color space. This is due to a call to pop the group from fill_mask when filling with a mask with transparency. In that case, the parent and the child will have the same color space anyway */ icc_link = gsicc_get_link_profile(pgs, dev, curr_icc_profile, nos->parent_color_info_procs->icc_profile, &rendering_params, pgs->memory, false); if (icc_link != NULL) { /* if problem with link we will do non-ICC approach */ nonicc_conversion = false; /* If the link is the identity, then we don't need to do any color conversions */ if ( !(icc_link->is_identity) ) { /* Before we do any allocations check if we can get away with reusing the existing buffer if it is the same size ( if it is smaller go ahead and allocate). We could reuse it in this case too. We need to do a bit of testing to determine what would be best. */ /* FIXME: RJW: Could we get away with just color converting * the area that's actually active (i.e. dirty, not rect)? */ if(nos_num_color_comp != tos_num_color_comp) { /* Different size. We will need to allocate */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); /* Copy over the noncolor planes. */ memcpy(new_data_buf + tos->planestride * nos_num_color_comp, tos->data + tos->planestride * tos_num_color_comp, tos->planestride * num_noncolor_planes); } else { /* In place color conversion! */ new_data_buf = tos->data; } /* Set up the buffer descriptors. Note that pdf14 always has the alpha channels at the back end (last planes). We will just handle that here and let the CMM know nothing about it */ num_rows = tos->rect.q.y - tos->rect.p.y; num_cols = tos->rect.q.x - tos->rect.p.x; gsicc_init_buffer(&input_buff_desc, tos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); gsicc_init_buffer(&output_buff_desc, nos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); /* Transform the data. Since the pdf14 device should be using RGB, CMYK or Gray buffers, this transform does not need to worry about the cmap procs of the target device. Those are handled when we do the pdf14 put image operation */ (icc_link->procs.map_buffer)(dev, icc_link, &input_buff_desc, &output_buff_desc, tos->data, new_data_buf); } /* Release the link */ gsicc_release_link(icc_link); /* free the old object if the color spaces were different sizes */ if(!(icc_link->is_identity) && nos_num_color_comp != tos_num_color_comp) { gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } } } if (nonicc_conversion) { /* Non ICC based transform */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); gs_transform_color_buffer_generic(tos->data, tos->rowstride, tos->planestride, tos_num_color_comp, tos->rect, new_data_buf, nos_num_color_comp, num_noncolor_planes); /* Free the old object */ gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } /* Adjust the plane and channel size now */ tos->n_chan = nos->n_chan; tos->n_planes = nos->n_planes; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_chan, ctx->stack->planestride, ctx->stack->rowstride, "aCMTrans_Group_ColorConv",ctx->stack->data); #endif /* compose. never do overprint in this case */ pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, nos->parent_color_info_procs->isadditive, nos->parent_color_info_procs->parent_blending_procs, false, drawn_comps, ctx->memory, dev); } } else { /* Group color spaces are the same. No color conversions needed */ if (x0 < x1 && y0 < y1) pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, ctx->additive, pblend_procs, overprint, drawn_comps, ctx->memory, dev); } exit: ctx->stack = nos; /* We want to detect the cases where we have luminosity soft masks embedded within one another. The "alpha" channel really needs to be merged into the luminosity channel in this case. This will occur during the mask pop */ if (ctx->smask_depth > 0 && maskbuf != NULL) { /* Set the trigger so that we will blend if not alpha. Since we have softmasks embedded in softmasks */ ctx->smask_blend = true; } if_debug1m('v', ctx->memory, "[v]pop buf, idle=%d\n", tos->idle); pdf14_buf_free(tos, ctx->memory); return 0; }
165,235
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaElementAudioSourceHandler::MediaElementAudioSourceHandler( AudioNode& node, HTMLMediaElement& media_element) : AudioHandler(kNodeTypeMediaElementAudioSource, node, node.context()->sampleRate()), media_element_(media_element), source_number_of_channels_(0), source_sample_rate_(0), passes_current_src_cors_access_check_( PassesCurrentSrcCORSAccessCheck(media_element.currentSrc())), maybe_print_cors_message_(!passes_current_src_cors_access_check_), current_src_string_(media_element.currentSrc().GetString()) { DCHECK(IsMainThread()); AddOutput(2); if (Context()->GetExecutionContext()) { task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( TaskType::kMediaElementEvent); } Initialize(); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
MediaElementAudioSourceHandler::MediaElementAudioSourceHandler( AudioNode& node, HTMLMediaElement& media_element) : AudioHandler(kNodeTypeMediaElementAudioSource, node, node.context()->sampleRate()), media_element_(media_element), source_number_of_channels_(0), source_sample_rate_(0), is_origin_tainted_(false) { DCHECK(IsMainThread()); AddOutput(2); if (Context()->GetExecutionContext()) { task_runner_ = Context()->GetExecutionContext()->GetTaskRunner( TaskType::kMediaElementEvent); } Initialize(); }
173,144
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: XOpenDevice( register Display *dpy, register XID id) { register long rlen; /* raw length */ xOpenDeviceReq *req; xOpenDeviceReply rep; XDevice *dev; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(OpenDevice, req); req->reqType = info->codes->major_opcode; req->ReqType = X_OpenDevice; req->deviceid = id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (XDevice *) NULL; return (XDevice *) NULL; } rlen = rep.length << 2; dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes * sizeof(XInputClassInfo)); if (dev) { int dlen; /* data length */ _XEatData(dpy, (unsigned long)rlen - dlen); } else _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (dev); } Commit Message: CWE ID: CWE-284
XOpenDevice( register Display *dpy, register XID id) { register long rlen; /* raw length */ xOpenDeviceReq *req; xOpenDeviceReply rep; XDevice *dev; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(OpenDevice, req); req->reqType = info->codes->major_opcode; req->ReqType = X_OpenDevice; req->deviceid = id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) { UnlockDisplay(dpy); SyncHandle(); return (XDevice *) NULL; return (XDevice *) NULL; } if (rep.length < INT_MAX >> 2 && (rep.length << 2) >= rep.num_classes * sizeof(xInputClassInfo)) { rlen = rep.length << 2; dev = (XDevice *) Xmalloc(sizeof(XDevice) + rep.num_classes * sizeof(XInputClassInfo)); } else { rlen = 0; dev = NULL; } if (dev) { int dlen; /* data length */ _XEatData(dpy, (unsigned long)rlen - dlen); } else _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (dev); }
164,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: GpuProcessHost::~GpuProcessHost() { DCHECK(CalledOnValidThread()); SendOutstandingReplies(); if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) { if (software_rendering_) { if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) { gpu_enabled_ = false; } } else { if (++g_gpu_crash_count >= kGpuMaxCrashCount) { #if !defined(OS_CHROMEOS) hardware_gpu_enabled_ = false; GpuDataManagerImpl::GetInstance()->BlacklistCard(); #endif } } } UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents", DIED_FIRST_TIME + g_gpu_crash_count, GPU_PROCESS_LIFETIME_EVENT_MAX); int exit_code; base::TerminationStatus status = process_->GetTerminationStatus(&exit_code); UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus", status, base::TERMINATION_STATUS_MAX_ENUM); if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION || status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) { UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode", exit_code, content::RESULT_CODE_LAST_CODE); } #if defined(OS_WIN) if (gpu_process_) CloseHandle(gpu_process_); #endif while (!queued_messages_.empty()) { delete queued_messages_.front(); queued_messages_.pop(); } if (g_gpu_process_hosts[kind_] == this) g_gpu_process_hosts[kind_] = NULL; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&GpuProcessHostUIShim::Destroy, host_id_)); } 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:
GpuProcessHost::~GpuProcessHost() { DCHECK(CalledOnValidThread()); SendOutstandingReplies(); if (process_launched_ && kind_ == GPU_PROCESS_KIND_SANDBOXED) { if (software_rendering_) { if (++g_gpu_software_crash_count >= kGpuMaxCrashCount) { gpu_enabled_ = false; } } else { if (++g_gpu_crash_count >= kGpuMaxCrashCount) { #if !defined(OS_CHROMEOS) hardware_gpu_enabled_ = false; GpuDataManagerImpl::GetInstance()->BlacklistCard(); #endif } } } UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessLifetimeEvents", DIED_FIRST_TIME + g_gpu_crash_count, GPU_PROCESS_LIFETIME_EVENT_MAX); int exit_code; base::TerminationStatus status = process_->GetTerminationStatus(&exit_code); UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessTerminationStatus", status, base::TERMINATION_STATUS_MAX_ENUM); if (status == base::TERMINATION_STATUS_NORMAL_TERMINATION || status == base::TERMINATION_STATUS_ABNORMAL_TERMINATION) { UMA_HISTOGRAM_ENUMERATION("GPU.GPUProcessExitCode", exit_code, content::RESULT_CODE_LAST_CODE); } while (!queued_messages_.empty()) { delete queued_messages_.front(); queued_messages_.pop(); } if (g_gpu_process_hosts[kind_] == this) g_gpu_process_hosts[kind_] = NULL; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&GpuProcessHostUIShim::Destroy, host_id_)); }
170,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint32_t color_string_to_rgba(const char *p, int len) { uint32_t ret = 0xFF000000; const ColorEntry *entry; char color_name[100]; if (*p == '#') { p++; len--; if (len == 3) { ret |= (hex_char_to_number(p[2]) << 4) | (hex_char_to_number(p[1]) << 12) | (hex_char_to_number(p[0]) << 20); } else if (len == 4) { ret = (hex_char_to_number(p[3]) << 4) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 20) | (hex_char_to_number(p[0]) << 28); } else if (len == 6) { ret |= hex_char_to_number(p[5]) | (hex_char_to_number(p[4]) << 4) | (hex_char_to_number(p[3]) << 8) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 16) | (hex_char_to_number(p[0]) << 20); } else if (len == 8) { ret = hex_char_to_number(p[7]) | (hex_char_to_number(p[6]) << 4) | (hex_char_to_number(p[5]) << 8) | (hex_char_to_number(p[4]) << 12) | (hex_char_to_number(p[3]) << 16) | (hex_char_to_number(p[2]) << 20) | (hex_char_to_number(p[1]) << 24) | (hex_char_to_number(p[0]) << 28); } } else { strncpy(color_name, p, len); color_name[len] = '\0'; entry = bsearch(color_name, color_table, FF_ARRAY_ELEMS(color_table), sizeof(ColorEntry), color_table_compare); if (!entry) return ret; ret = entry->rgb_color; } return ret; } Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues Most of these were found through code review in response to fixing 1466/clusterfuzz-testcase-minimized-5961584419536896 There is thus no testcase for most of this. The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static uint32_t color_string_to_rgba(const char *p, int len) { uint32_t ret = 0xFF000000; const ColorEntry *entry; char color_name[100]; len = FFMIN(FFMAX(len, 0), sizeof(color_name) - 1); if (*p == '#') { p++; len--; if (len == 3) { ret |= (hex_char_to_number(p[2]) << 4) | (hex_char_to_number(p[1]) << 12) | (hex_char_to_number(p[0]) << 20); } else if (len == 4) { ret = (hex_char_to_number(p[3]) << 4) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 20) | (hex_char_to_number(p[0]) << 28); } else if (len == 6) { ret |= hex_char_to_number(p[5]) | (hex_char_to_number(p[4]) << 4) | (hex_char_to_number(p[3]) << 8) | (hex_char_to_number(p[2]) << 12) | (hex_char_to_number(p[1]) << 16) | (hex_char_to_number(p[0]) << 20); } else if (len == 8) { ret = hex_char_to_number(p[7]) | (hex_char_to_number(p[6]) << 4) | (hex_char_to_number(p[5]) << 8) | (hex_char_to_number(p[4]) << 12) | (hex_char_to_number(p[3]) << 16) | (hex_char_to_number(p[2]) << 20) | (hex_char_to_number(p[1]) << 24) | (hex_char_to_number(p[0]) << 28); } } else { strncpy(color_name, p, len); color_name[len] = '\0'; entry = bsearch(color_name, color_table, FF_ARRAY_ELEMS(color_table), sizeof(ColorEntry), color_table_compare); if (!entry) return ret; ret = entry->rgb_color; } return ret; }
168,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg) { char fnam[PROCLEN]; FILE *f; bool answer = false; char *line = NULL; size_t len = 0; int ret; ret = snprintf(fnam, PROCLEN, "/proc/%d/cgroup", pid); if (ret < 0 || ret >= PROCLEN) return false; if (!(f = fopen(fnam, "r"))) return false; while (getline(&line, &len, f) != -1) { char *c1, *c2, *linecmp; if (!line[0]) continue; c1 = strchr(line, ':'); if (!c1) goto out; c1++; c2 = strchr(c1, ':'); if (!c2) goto out; *c2 = '\0'; if (strcmp(c1, contrl) != 0) continue; c2++; stripnewline(c2); prune_init_slice(c2); /* * callers pass in '/' for root cgroup, otherwise they pass * in a cgroup without leading '/' */ linecmp = *cg == '/' ? c2 : c2+1; if (strncmp(linecmp, cg, strlen(linecmp)) != 0) { if (nextcg) *nextcg = get_next_cgroup_dir(linecmp, cg); goto out; } answer = true; goto out; } out: fclose(f); free(line); return answer; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static bool caller_is_in_ancestor(pid_t pid, const char *contrl, const char *cg, char **nextcg) { bool answer = false; char *c2 = get_pid_cgroup(pid, contrl); char *linecmp; if (!c2) return false; prune_init_slice(c2); /* * callers pass in '/' for root cgroup, otherwise they pass * in a cgroup without leading '/' */ linecmp = *cg == '/' ? c2 : c2+1; if (strncmp(linecmp, cg, strlen(linecmp)) != 0) { if (nextcg) { *nextcg = get_next_cgroup_dir(linecmp, cg); } goto out; } answer = true; out: free(c2); return answer; } /* * If caller is in /a/b/c, he may see that /a exists, but not /b or /a/c. */ static bool caller_may_see_dir(pid_t pid, const char *contrl, const char *cg) { bool answer = false; char *c2, *task_cg; size_t target_len, task_len; if (strcmp(cg, "/") == 0) return true; c2 = get_pid_cgroup(pid, contrl); if (!c2) return false; task_cg = c2 + 1; target_len = strlen(cg); task_len = strlen(task_cg); if (strcmp(cg, task_cg) == 0) { answer = true; goto out; } if (target_len < task_len) { /* looking up a parent dir */ if (strncmp(task_cg, cg, target_len) == 0 && task_cg[target_len] == '/') answer = true; goto out; } if (target_len > task_len) { /* looking up a child dir */ if (strncmp(task_cg, cg, task_len) == 0 && cg[task_len] == '/') answer = true; goto out; } out: free(c2); return answer; }
166,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void XMLHttpRequest::genericError() { clearResponse(); clearRequest(); m_error = true; changeState(DONE); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::genericError() void XMLHttpRequest::handleDidFailGeneric() { clearResponse(); clearRequest(); m_error = true; }
171,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { if (key == "can_dock" || key == "debugFrontend" || key == "experiments" || key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend") return "true"; if (key == "ws" || key == "service-backend") return SanitizeEndpoint(value); if (key == "dockSide" && value == "undocked") return value; if (key == "panel" && (value == "elements" || value == "console")) return value; if (key == "remoteBase") return SanitizeRemoteBase(value); if (key == "remoteFrontendUrl") return SanitizeRemoteFrontendURL(value); return std::string(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeFrontendQueryParam(
172,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeFloat( IMkvReader* pReader, long long pos, long long size_, double& result) { assert(pReader); assert(pos >= 0); if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) //error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long mkvparser::UnserializeFloat( { signed char b; const long status = pReader->Read(pos, 1, (unsigned char*)&b); if (status < 0) return status; result = b; ++pos; } for (long i = 1; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } return 0; // success }
174,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val) { jas_ulonglong tmp; if (jas_iccgetuint(in, 8, &tmp)) return -1; *val = tmp; return 0; }
168,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response, const GURL& url) { //// static DCHECK(response && response->headers.get()); std::string location; if (!response->headers->IsRedirect(&location)) return false; std::string fake_response_headers = base::StringPrintf("HTTP/1.0 302 Found\n" "Location: %s\n" "Content-length: 0\n" "Connection: close\n" "\n", location.c_str()); std::string raw_headers = HttpUtil::AssembleRawHeaders(fake_response_headers.data(), fake_response_headers.length()); response->headers = new HttpResponseHeaders(raw_headers); return true; } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19
bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response, bool ProxyClientSocket::SanitizeProxyAuth(HttpResponseInfo* response) { DCHECK(response && response->headers.get()); scoped_refptr<HttpResponseHeaders> old_headers = response->headers; const char kHeaders[] = "HTTP/1.1 407 Proxy Authentication Required\n\n"; scoped_refptr<HttpResponseHeaders> new_headers = new HttpResponseHeaders( HttpUtil::AssembleRawHeaders(kHeaders, arraysize(kHeaders))); new_headers->ReplaceStatusLine(old_headers->GetStatusLine()); CopyHeaderValues(old_headers, new_headers, "Connection"); CopyHeaderValues(old_headers, new_headers, "Proxy-Authenticate"); response->headers = new_headers; return true; } //// static bool ProxyClientSocket::SanitizeProxyRedirect(HttpResponseInfo* response) { DCHECK(response && response->headers.get()); std::string location; if (!response->headers->IsRedirect(&location)) return false; // Return minimal headers; set "Content-Length: 0" to ignore response body. std::string fake_response_headers = base::StringPrintf( "HTTP/1.0 302 Found\n" "Location: %s\n" "Content-Length: 0\n" "Connection: close\n" "\n", location.c_str()); std::string raw_headers = HttpUtil::AssembleRawHeaders(fake_response_headers.data(), fake_response_headers.length()); response->headers = new HttpResponseHeaders(raw_headers); return true; }
172,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: unsigned int get_random_int(void) { struct keydata *keyptr; __u32 *hash = get_cpu_var(get_random_int_hash); int ret; keyptr = get_keyptr(); hash[0] += current->pid + jiffies + get_cycles(); ret = half_md4_transform(hash, keyptr->secret); put_cpu_var(get_random_int_hash); return ret; } Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5. Computers have become a lot faster since we compromised on the partial MD4 hash which we use currently for performance reasons. MD5 is a much safer choice, and is inline with both RFC1948 and other ISS generators (OpenBSD, Solaris, etc.) Furthermore, only having 24-bits of the sequence number be truly unpredictable is a very serious limitation. So the periodic regeneration and 8-bit counter have been removed. We compute and use a full 32-bit sequence number. For ipv6, DCCP was found to use a 32-bit truncated initial sequence number (it needs 43-bits) and that is fixed here as well. Reported-by: Dan Kaminsky <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
unsigned int get_random_int(void) { __u32 *hash = get_cpu_var(get_random_int_hash); unsigned int ret; hash[0] += current->pid + jiffies + get_cycles(); md5_transform(hash, random_int_secret); ret = hash[0]; put_cpu_var(get_random_int_hash); return ret; }
165,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = fcntl(semaphore->fd, F_GETFL); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (fcntl(semaphore->fd, F_SETFL, flags) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; } 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
bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_GETFL)); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK)) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags)) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; }
173,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeRemoteFrontendURL(const std::string& value) { GURL url(net::UnescapeURLComponent(value, net::UnescapeRule::SPACES | net::UnescapeRule::PATH_SEPARATORS | net::UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS | net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); std::string filename = parts.size() ? parts[parts.size() - 1] : ""; if (filename != "devtools.html") filename = "inspector.html"; path = base::StringPrintf("/serve_rev/%s/%s", revision.c_str(), filename.c_str()); std::string sanitized = SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, true).spec(); return net::EscapeQueryParamValue(sanitized, false); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteFrontendURL(const std::string& value) {
172,463
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool InputMethodController::FinishComposingText( ConfirmCompositionBehavior confirm_behavior) { if (!HasComposition()) return false; const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition()); const String& composing = ComposingText(); if (confirm_behavior == kKeepSelection) { const bool is_handle_visible = GetFrame().Selection().IsHandleVisible(); const PlainTextRange& old_offsets = GetSelectionOffsets(); Editor::RevealSelectionScope reveal_selection_scope(&GetEditor()); if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); DispatchCompositionEndEvent(GetFrame(), composing); } GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& old_selection_range = EphemeralRangeForOffsets(old_offsets); if (old_selection_range.IsNull()) return false; const SelectionInDOMTree& selection = SelectionInDOMTree::Builder() .SetBaseAndExtent(old_selection_range) .SetIsHandleVisible(is_handle_visible) .Build(); GetFrame().Selection().SetSelection( selection, SetSelectionData::Builder().SetShouldCloseTyping(true).Build()); return true; } Element* root_editable_element = GetFrame() .Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .RootEditableElement(); if (!root_editable_element) return false; PlainTextRange composition_range = PlainTextRange::Create(*root_editable_element, *composition_range_); if (composition_range.IsNull()) return false; if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); } if (!MoveCaret(composition_range.End())) return false; DispatchCompositionEndEvent(GetFrame(), composing); return true; } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool InputMethodController::FinishComposingText( ConfirmCompositionBehavior confirm_behavior) { if (!HasComposition()) return false; const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition()); const String& composing = ComposingText(); if (confirm_behavior == kKeepSelection) { const bool is_handle_visible = GetFrame().Selection().IsHandleVisible(); const PlainTextRange& old_offsets = GetSelectionOffsets(); Editor::RevealSelectionScope reveal_selection_scope(&GetEditor()); if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); DispatchCompositionEndEvent(GetFrame(), composing); } GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& old_selection_range = EphemeralRangeForOffsets(old_offsets); if (old_selection_range.IsNull()) return false; const SelectionInDOMTree& selection = SelectionInDOMTree::Builder() .SetBaseAndExtent(old_selection_range) .Build(); GetFrame().Selection().SetSelection( selection, SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldShowHandle(is_handle_visible) .Build()); return true; } Element* root_editable_element = GetFrame() .Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .RootEditableElement(); if (!root_editable_element) return false; PlainTextRange composition_range = PlainTextRange::Create(*root_editable_element, *composition_range_); if (composition_range.IsNull()) return false; if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); } if (!MoveCaret(composition_range.End())) return false; DispatchCompositionEndEvent(GetFrame(), composing); return true; }
171,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void Process_ipfix_template_add(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { input_translation_t *translation_table; ipfix_template_record_t *ipfix_template_record; ipfix_template_elements_std_t *NextElement; int i; while ( size_left ) { uint32_t table_id, count, size_required; uint32_t num_extensions = 0; if ( size_left && size_left < 4 ) { LogError("Process_ipfix [%u] Template size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; table_id = ntohs(ipfix_template_record->TemplateID); count = ntohs(ipfix_template_record->FieldCount); dbg_printf("\n[%u] Template ID: %u\n", exporter->info.id, table_id); dbg_printf("FieldCount: %u buffersize: %u\n", count, size_left); memset((void *)cache.common_extensions, 0, (Max_num_extensions+1)*sizeof(uint32_t)); memset((void *)cache.lookup_info, 0, 65536 * sizeof(struct element_param_s)); for (i=1; ipfix_element_map[i].id != 0; i++ ) { uint32_t Type = ipfix_element_map[i].id; if ( ipfix_element_map[i].id == ipfix_element_map[i-1].id ) continue; cache.lookup_info[Type].index = i; } cache.input_order = calloc(count, sizeof(struct order_s)); if ( !cache.input_order ) { LogError("Process_ipfix: Panic! malloc(): %s line %d: %s", __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } cache.input_count = count; size_required = 4*count; if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } NextElement = (ipfix_template_elements_std_t *)ipfix_template_record->elements; for ( i=0; i<count; i++ ) { uint16_t Type, Length; uint32_t ext_id; int Enterprise; Type = ntohs(NextElement->Type); Length = ntohs(NextElement->Length); Enterprise = Type & 0x8000 ? 1 : 0; Type = Type & 0x7FFF; ext_id = MapElement(Type, Length, i); if ( ext_id && extension_descriptor[ext_id].enabled ) { if ( cache.common_extensions[ext_id] == 0 ) { cache.common_extensions[ext_id] = 1; num_extensions++; } } if ( Enterprise ) { ipfix_template_elements_e_t *e = (ipfix_template_elements_e_t *)NextElement; size_required += 4; // ad 4 for enterprise value if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } if ( ntohl(e->EnterpriseNumber) == IPFIX_ReverseInformationElement ) { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u Reverse Information Element: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } else { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u EnterpriseNumber: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } e++; NextElement = (ipfix_template_elements_std_t *)e; } else { dbg_printf(" [%i] Enterprise: 0, Type: %u, Length %u\n", i, Type, Length); NextElement++; } } dbg_printf("Processed: %u\n", size_required); if ( compact_input_order() ) { if ( extension_descriptor[EX_ROUTER_IP_v4].enabled ) { if ( cache.common_extensions[EX_ROUTER_IP_v4] == 0 ) { cache.common_extensions[EX_ROUTER_IP_v4] = 1; num_extensions++; } dbg_printf("Add sending router IP address (%s) => Extension: %u\n", fs->sa_family == PF_INET6 ? "ipv6" : "ipv4", EX_ROUTER_IP_v4); } extension_descriptor[EX_ROUTER_ID].enabled = 0; /* if ( extension_descriptor[EX_ROUTER_ID].enabled ) { if ( cache.common_extensions[EX_ROUTER_ID] == 0 ) { cache.common_extensions[EX_ROUTER_ID] = 1; num_extensions++; } dbg_printf("Force add router ID (engine type/ID), Extension: %u\n", EX_ROUTER_ID); } */ if ( extension_descriptor[EX_RECEIVED].enabled ) { if ( cache.common_extensions[EX_RECEIVED] == 0 ) { cache.common_extensions[EX_RECEIVED] = 1; num_extensions++; } dbg_printf("Force add packet received time, Extension: %u\n", EX_RECEIVED); } #ifdef DEVEL { int i; for (i=4; extension_descriptor[i].id; i++ ) { if ( cache.common_extensions[i] ) { printf("Enabled extension: %i\n", i); } } } #endif translation_table = setup_translation_table(exporter, table_id); if (translation_table->extension_map_changed ) { dbg_printf("Translation Table changed! Add extension map ID: %i\n", translation_table->extension_info.map->map_id); AddExtensionMap(fs, translation_table->extension_info.map); translation_table->extension_map_changed = 0; dbg_printf("Translation Table added! map ID: %i\n", translation_table->extension_info.map->map_id); } if ( !reorder_sequencer(translation_table) ) { LogError("Process_ipfix: [%u] Failed to reorder sequencer. Remove table id: %u", exporter->info.id, table_id); remove_translation_table(fs, exporter, table_id); } } else { dbg_printf("Template does not contain any common fields - skip\n"); } size_left -= size_required; DataPtr = DataPtr + size_required+4; // +4 for header if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } free(cache.input_order); cache.input_order = NULL; } } // End of Process_ipfix_template_add Commit Message: Fix potential unsigned integer underflow CWE ID: CWE-190
static void Process_ipfix_template_add(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) { input_translation_t *translation_table; ipfix_template_record_t *ipfix_template_record; ipfix_template_elements_std_t *NextElement; int i; while ( size_left ) { uint32_t table_id, count, size_required; uint32_t num_extensions = 0; if ( size_left < 4 ) { LogError("Process_ipfix [%u] Template size error at %s line %u" , exporter->info.id, __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } ipfix_template_record = (ipfix_template_record_t *)DataPtr; size_left -= 4; table_id = ntohs(ipfix_template_record->TemplateID); count = ntohs(ipfix_template_record->FieldCount); dbg_printf("\n[%u] Template ID: %u\n", exporter->info.id, table_id); dbg_printf("FieldCount: %u buffersize: %u\n", count, size_left); memset((void *)cache.common_extensions, 0, (Max_num_extensions+1)*sizeof(uint32_t)); memset((void *)cache.lookup_info, 0, 65536 * sizeof(struct element_param_s)); for (i=1; ipfix_element_map[i].id != 0; i++ ) { uint32_t Type = ipfix_element_map[i].id; if ( ipfix_element_map[i].id == ipfix_element_map[i-1].id ) continue; cache.lookup_info[Type].index = i; } cache.input_order = calloc(count, sizeof(struct order_s)); if ( !cache.input_order ) { LogError("Process_ipfix: Panic! malloc(): %s line %d: %s", __FILE__, __LINE__, strerror (errno)); size_left = 0; continue; } cache.input_count = count; size_required = 4*count; if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } NextElement = (ipfix_template_elements_std_t *)ipfix_template_record->elements; for ( i=0; i<count; i++ ) { uint16_t Type, Length; uint32_t ext_id; int Enterprise; Type = ntohs(NextElement->Type); Length = ntohs(NextElement->Length); Enterprise = Type & 0x8000 ? 1 : 0; Type = Type & 0x7FFF; ext_id = MapElement(Type, Length, i); if ( ext_id && extension_descriptor[ext_id].enabled ) { if ( cache.common_extensions[ext_id] == 0 ) { cache.common_extensions[ext_id] = 1; num_extensions++; } } if ( Enterprise ) { ipfix_template_elements_e_t *e = (ipfix_template_elements_e_t *)NextElement; size_required += 4; // ad 4 for enterprise value if ( size_left < size_required ) { LogError("Process_ipfix: [%u] Not enough data for template elements! required: %i, left: %u", exporter->info.id, size_required, size_left); dbg_printf("ERROR: Not enough data for template elements! required: %i, left: %u", size_required, size_left); return; } if ( ntohl(e->EnterpriseNumber) == IPFIX_ReverseInformationElement ) { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u Reverse Information Element: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } else { dbg_printf(" [%i] Enterprise: 1, Type: %u, Length %u EnterpriseNumber: %u\n", i, Type, Length, ntohl(e->EnterpriseNumber)); } e++; NextElement = (ipfix_template_elements_std_t *)e; } else { dbg_printf(" [%i] Enterprise: 0, Type: %u, Length %u\n", i, Type, Length); NextElement++; } } dbg_printf("Processed: %u\n", size_required); if ( compact_input_order() ) { if ( extension_descriptor[EX_ROUTER_IP_v4].enabled ) { if ( cache.common_extensions[EX_ROUTER_IP_v4] == 0 ) { cache.common_extensions[EX_ROUTER_IP_v4] = 1; num_extensions++; } dbg_printf("Add sending router IP address (%s) => Extension: %u\n", fs->sa_family == PF_INET6 ? "ipv6" : "ipv4", EX_ROUTER_IP_v4); } extension_descriptor[EX_ROUTER_ID].enabled = 0; /* if ( extension_descriptor[EX_ROUTER_ID].enabled ) { if ( cache.common_extensions[EX_ROUTER_ID] == 0 ) { cache.common_extensions[EX_ROUTER_ID] = 1; num_extensions++; } dbg_printf("Force add router ID (engine type/ID), Extension: %u\n", EX_ROUTER_ID); } */ if ( extension_descriptor[EX_RECEIVED].enabled ) { if ( cache.common_extensions[EX_RECEIVED] == 0 ) { cache.common_extensions[EX_RECEIVED] = 1; num_extensions++; } dbg_printf("Force add packet received time, Extension: %u\n", EX_RECEIVED); } #ifdef DEVEL { int i; for (i=4; extension_descriptor[i].id; i++ ) { if ( cache.common_extensions[i] ) { printf("Enabled extension: %i\n", i); } } } #endif translation_table = setup_translation_table(exporter, table_id); if (translation_table->extension_map_changed ) { dbg_printf("Translation Table changed! Add extension map ID: %i\n", translation_table->extension_info.map->map_id); AddExtensionMap(fs, translation_table->extension_info.map); translation_table->extension_map_changed = 0; dbg_printf("Translation Table added! map ID: %i\n", translation_table->extension_info.map->map_id); } if ( !reorder_sequencer(translation_table) ) { LogError("Process_ipfix: [%u] Failed to reorder sequencer. Remove table id: %u", exporter->info.id, table_id); remove_translation_table(fs, exporter, table_id); } } else { dbg_printf("Template does not contain any common fields - skip\n"); } size_left -= size_required; DataPtr = DataPtr + size_required+4; // +4 for header if ( size_left < 4 ) { dbg_printf("Skip %u bytes padding\n", size_left); size_left = 0; } free(cache.input_order); cache.input_order = NULL; } } // End of Process_ipfix_template_add
169,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; } 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
bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (content::GetContentClient()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; }
171,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } Commit Message: CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes. Probably a copy-and-pasteo. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); }
167,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { if (original_skia_image_) { std::unique_ptr<gpu::SyncToken> sync_token = base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken())); if (original_skia_image_thread_id_ != Platform::Current()->CurrentThread()->ThreadId()) { PostCrossThreadTask( *original_skia_image_task_runner_, FROM_HERE, CrossThreadBind( &DestroySkImageOnOriginalThread, std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), WTF::Passed(std::move(sync_token)))); } else { DestroySkImageOnOriginalThread( std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), std::move(sync_token)); } } } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
AcceleratedStaticBitmapImage::~AcceleratedStaticBitmapImage() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (original_skia_image_) { std::unique_ptr<gpu::SyncToken> sync_token = base::WrapUnique(new gpu::SyncToken(texture_holder_->GetSyncToken())); if (!original_skia_image_task_runner_->BelongsToCurrentThread()) { PostCrossThreadTask( *original_skia_image_task_runner_, FROM_HERE, CrossThreadBind( &DestroySkImageOnOriginalThread, std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), WTF::Passed(std::move(sync_token)))); } else { DestroySkImageOnOriginalThread( std::move(original_skia_image_), std::move(original_skia_image_context_provider_wrapper_), std::move(sync_token)); } } }
172,599
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> setter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::Local<v8::Value> argv[] = { v8Value }; v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(setter), scriptState->getExecutionContext(), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className); block.ReThrow(); return false; } return true; } Commit Message: Blink-in-JS should not run micro tasks If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug (see 645211 for concrete steps). This CL makes Blink-in-JS use callInternalFunction (instead of callFunction) to avoid running micro tasks after Blink-in-JS' callbacks. BUG=645211 Review-Url: https://codereview.chromium.org/2330843002 Cr-Commit-Position: refs/heads/master@{#417874} CWE ID: CWE-79
bool PrivateScriptRunner::runDOMAttributeSetter(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* attributeName, v8::Local<v8::Value> holder, v8::Local<v8::Value> v8Value) { v8::Isolate* isolate = scriptState->isolate(); v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className); v8::Local<v8::Value> descriptor; if (!classObject->GetOwnPropertyDescriptor(scriptState->context(), v8String(isolate, attributeName)).ToLocal(&descriptor) || !descriptor->IsObject()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } v8::Local<v8::Value> setter; if (!v8::Local<v8::Object>::Cast(descriptor)->Get(scriptState->context(), v8String(isolate, "set")).ToLocal(&setter) || !setter->IsFunction()) { fprintf(stderr, "Private script error: Target DOM attribute setter was not found. (Class name = %s, Attribute name = %s)\n", className, attributeName); RELEASE_NOTREACHED(); } initializeHolderIfNeeded(scriptState, classObject, holder); v8::Local<v8::Value> argv[] = { v8Value }; v8::TryCatch block(isolate); v8::Local<v8::Value> result; if (!V8ScriptRunner::callInternalFunction(v8::Local<v8::Function>::Cast(setter), holder, WTF_ARRAY_LENGTH(argv), argv, isolate).ToLocal(&result)) { rethrowExceptionInPrivateScript(isolate, block, scriptStateInUserScript, ExceptionState::SetterContext, attributeName, className); block.ReThrow(); return false; } return true; }
172,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) return false; if(buffer[len-1] != '\0') SLOGW("String is not zero-terminated"); int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ dispatchCommand(c, buffer + offset); offset = i + 1; } } return true; } Commit Message: Fix vold vulnerability in FrameworkListener Modify FrameworkListener to ignore commands that exceed the maximum buffer length and send an error message. Bug: 29831647 Change-Id: I9e57d1648d55af2ca0191bb47868e375ecc26950 Signed-off-by: Connor O'Brien <[email protected]> (cherry picked from commit baa126dc158a40bc83c17c6d428c760e5b93fb1a) (cherry picked from commit 470484d2a25ad432190a01d1c763b4b36db33c7e) CWE ID: CWE-264
bool FrameworkListener::onDataAvailable(SocketClient *c) { char buffer[CMD_BUF_SIZE]; int len; len = TEMP_FAILURE_RETRY(read(c->getSocket(), buffer, sizeof(buffer))); if (len < 0) { SLOGE("read() failed (%s)", strerror(errno)); return false; } else if (!len) { return false; } else if (buffer[len-1] != '\0') { SLOGW("String is not zero-terminated"); android_errorWriteLog(0x534e4554, "29831647"); c->sendMsg(500, "Command too large for buffer", false); mSkipToNextNullByte = true; return false; } int offset = 0; int i; for (i = 0; i < len; i++) { if (buffer[i] == '\0') { /* IMPORTANT: dispatchCommand() expects a zero-terminated string */ if (mSkipToNextNullByte) { mSkipToNextNullByte = false; } else { dispatchCommand(c, buffer + offset); } offset = i + 1; } } mSkipToNextNullByte = false; return true; }
173,391
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsSession::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_, 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 <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void DevToolsSession::SetRenderer(RenderProcessHost* process_host, void DevToolsSession::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { process_host_id_ = process_host_id; host_ = frame_host; for (auto& pair : handlers_) pair.second->SetRenderer(process_host_id_, host_); }
172,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0644); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); } Commit Message: Fix heap-use-after-free in BookmarksIOFunction::ShowSelectFileDialog. BUG=177410 Review URL: https://chromiumcodereview.appspot.com/12326086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { if (!dispatcher()) return; // Extension was unloaded. AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); }
171,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void toggle_fpga_eeprom_bus(bool cpu_own) { qrio_gpio_direction_output(GPIO_A, PROM_SEL_L, !cpu_own); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
static void toggle_fpga_eeprom_bus(bool cpu_own) { qrio_gpio_direction_output(QRIO_GPIO_A, PROM_SEL_L, !cpu_own); }
169,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) { unsigned int cpy_len, rem_len; uint32_t list_len; uint8_t* p; uint8_t type; #if (SDP_DEBUG_RAW == TRUE) uint8_t num_array[SDP_MAX_LIST_BYTE_COUNT]; uint32_t i; for (i = 0; i < p_ccb->list_len; i++) { snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", (uint8_t)(p_ccb->rsp_list[i])); } SDP_TRACE_WARNING("result :%s", num_array); #endif if (p_ccb->p_db->raw_data) { cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used; list_len = p_ccb->list_len; p = &p_ccb->rsp_list[0]; if (offset) { type = *p++; p = sdpu_get_len_from_type(p, type, &list_len); } if (list_len < cpy_len) { cpy_len = list_len; } rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]); if (cpy_len > rem_len) { SDP_TRACE_WARNING("rem_len :%d less than cpy_len:%d", rem_len, cpy_len); cpy_len = rem_len; } SDP_TRACE_WARNING( "%s: list_len:%d cpy_len:%d p:%p p_ccb:%p p_db:%p raw_size:%d " "raw_used:%d raw_data:%p", __func__, list_len, cpy_len, p, p_ccb, p_ccb->p_db, p_ccb->p_db->raw_size, p_ccb->p_db->raw_used, p_ccb->p_db->raw_data); memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); p_ccb->p_db->raw_used += cpy_len; } } Commit Message: Fix copy length calculation in sdp_copy_raw_data Test: compilation Bug: 110216176 Change-Id: Ic4a19c9f0fe8cd592bc6c25dcec7b1da49ff7459 (cherry picked from commit 23aa15743397b345f3d948289fe90efa2a2e2b3e) CWE ID: CWE-787
static void sdp_copy_raw_data(tCONN_CB* p_ccb, bool offset) { unsigned int cpy_len, rem_len; uint32_t list_len; uint8_t* p; uint8_t type; #if (SDP_DEBUG_RAW == TRUE) uint8_t num_array[SDP_MAX_LIST_BYTE_COUNT]; uint32_t i; for (i = 0; i < p_ccb->list_len; i++) { snprintf((char*)&num_array[i * 2], sizeof(num_array) - i * 2, "%02X", (uint8_t)(p_ccb->rsp_list[i])); } SDP_TRACE_WARNING("result :%s", num_array); #endif if (p_ccb->p_db->raw_data) { cpy_len = p_ccb->p_db->raw_size - p_ccb->p_db->raw_used; list_len = p_ccb->list_len; p = &p_ccb->rsp_list[0]; if (offset) { cpy_len -= 1; type = *p++; uint8_t* old_p = p; p = sdpu_get_len_from_type(p, type, &list_len); if ((int)cpy_len < (p - old_p)) { SDP_TRACE_WARNING("%s: no bytes left for data", __func__); return; } cpy_len -= (p - old_p); } if (list_len < cpy_len) { cpy_len = list_len; } rem_len = SDP_MAX_LIST_BYTE_COUNT - (unsigned int)(p - &p_ccb->rsp_list[0]); if (cpy_len > rem_len) { SDP_TRACE_WARNING("rem_len :%d less than cpy_len:%d", rem_len, cpy_len); cpy_len = rem_len; } SDP_TRACE_WARNING( "%s: list_len:%d cpy_len:%d p:%p p_ccb:%p p_db:%p raw_size:%d " "raw_used:%d raw_data:%p", __func__, list_len, cpy_len, p, p_ccb, p_ccb->p_db, p_ccb->p_db->raw_size, p_ccb->p_db->raw_used, p_ccb->p_db->raw_data); memcpy(&p_ccb->p_db->raw_data[p_ccb->p_db->raw_used], p, cpy_len); p_ccb->p_db->raw_used += cpy_len; } }
174,081
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len) { int offset = 0; const uint8_t *ptr = NULL; if (asn1_next_obj(asn1_sig, &offset, ASN1_SEQUENCE) < 0 || asn1_skip_obj(asn1_sig, &offset, ASN1_SEQUENCE)) goto end_get_sig; if (asn1_sig[offset++] != ASN1_OCTET_STRING) goto end_get_sig; *len = get_asn1_length(asn1_sig, &offset); ptr = &asn1_sig[offset]; /* all ok */ end_get_sig: return ptr; } Commit Message: Apply CVE fixes for X509 parsing Apply patches developed by Sze Yiu which correct a vulnerability in X509 parsing. See CVE-2018-16150 and CVE-2018-16149 for more info. CWE ID: CWE-347
static const uint8_t *get_signature(const uint8_t *asn1_sig, int *len)
169,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid) { const struct nd_opt_hdr *op; const struct nd_opt_prefix_info *opp; const struct nd_opt_mtu *opm; const struct nd_opt_rdnss *oprd; const struct nd_opt_dnssl *opds; const struct nd_opt_advinterval *opa; const struct nd_opt_homeagent_info *oph; const struct nd_opt_route_info *opri; const u_char *cp, *ep, *domp; struct in6_addr in6; const struct in6_addr *in6p; size_t l; u_int i; #define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return cp = bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; while (cp < ep) { op = (const struct nd_opt_hdr *)cp; ECHECK(op->nd_opt_len); if (resid <= 0) return; if (op->nd_opt_len == 0) goto trunc; if (cp + (op->nd_opt_len << 3) > ep) goto trunc; ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ", tok2str(icmp6_opt_values, "unknown", op->nd_opt_type), op->nd_opt_type, op->nd_opt_len << 3, op->nd_opt_len)); switch (op->nd_opt_type) { case ND_OPT_SOURCE_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_TARGET_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_PREFIX_INFORMATION: opp = (const struct nd_opt_prefix_info *)op; ND_TCHECK(opp->nd_opt_pi_prefix); ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s", ip6addr_string(ndo, &opp->nd_opt_pi_prefix), opp->nd_opt_pi_prefix_len, (op->nd_opt_len != 4) ? "badlen" : "", bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved), get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time)))); ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time)))); break; case ND_OPT_REDIRECTED_HEADER: print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3); /* xxx */ break; case ND_OPT_MTU: opm = (const struct nd_opt_mtu *)op; ND_TCHECK(opm->nd_opt_mtu_mtu); ND_PRINT((ndo," %u%s", EXTRACT_32BITS(&opm->nd_opt_mtu_mtu), (op->nd_opt_len != 1) ? "bad option length" : "" )); break; case ND_OPT_RDNSS: oprd = (const struct nd_opt_rdnss *)op; l = (op->nd_opt_len - 1) / 2; ND_PRINT((ndo," lifetime %us,", EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime))); for (i = 0; i < l; i++) { ND_TCHECK(oprd->nd_opt_rdnss_addr[i]); ND_PRINT((ndo," addr: %s", ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i]))); } break; case ND_OPT_DNSSL: opds = (const struct nd_opt_dnssl *)op; ND_PRINT((ndo," lifetime %us, domain(s):", EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime))); domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */ while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0') { ND_PRINT((ndo, " ")); if ((domp = ns_nprint (ndo, domp, bp)) == NULL) goto trunc; } break; case ND_OPT_ADVINTERVAL: opa = (const struct nd_opt_advinterval *)op; ND_TCHECK(opa->nd_opt_adv_interval); ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval))); break; case ND_OPT_HOMEAGENT_INFO: oph = (const struct nd_opt_homeagent_info *)op; ND_TCHECK(oph->nd_opt_hai_lifetime); ND_PRINT((ndo," preference %u, lifetime %u", EXTRACT_16BITS(&oph->nd_opt_hai_preference), EXTRACT_16BITS(&oph->nd_opt_hai_lifetime))); break; case ND_OPT_ROUTE_INFO: opri = (const struct nd_opt_route_info *)op; ND_TCHECK(opri->nd_opt_rti_lifetime); memset(&in6, 0, sizeof(in6)); in6p = (const struct in6_addr *)(opri + 1); switch (op->nd_opt_len) { case 1: break; case 2: ND_TCHECK2(*in6p, 8); memcpy(&in6, opri + 1, 8); break; case 3: ND_TCHECK(*in6p); memcpy(&in6, opri + 1, sizeof(in6)); break; default: goto trunc; } ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6), opri->nd_opt_rti_prefixlen)); ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags))); ND_PRINT((ndo,", lifetime=%s", get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime)))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ return; } break; } /* do we want to see an additional hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ cp += op->nd_opt_len << 3; resid -= op->nd_opt_len << 3; } return; trunc: ND_PRINT((ndo, "[ndp opt]")); return; #undef ECHECK } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid) { const struct nd_opt_hdr *op; const struct nd_opt_prefix_info *opp; const struct nd_opt_mtu *opm; const struct nd_opt_rdnss *oprd; const struct nd_opt_dnssl *opds; const struct nd_opt_advinterval *opa; const struct nd_opt_homeagent_info *oph; const struct nd_opt_route_info *opri; const u_char *cp, *ep, *domp; struct in6_addr in6; const struct in6_addr *in6p; size_t l; u_int i; #define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return cp = bp; /* 'ep' points to the end of available data. */ ep = ndo->ndo_snapend; while (cp < ep) { op = (const struct nd_opt_hdr *)cp; ECHECK(op->nd_opt_len); if (resid <= 0) return; if (op->nd_opt_len == 0) goto trunc; if (cp + (op->nd_opt_len << 3) > ep) goto trunc; ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ", tok2str(icmp6_opt_values, "unknown", op->nd_opt_type), op->nd_opt_type, op->nd_opt_len << 3, op->nd_opt_len)); switch (op->nd_opt_type) { case ND_OPT_SOURCE_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_TARGET_LINKADDR: l = (op->nd_opt_len << 3) - 2; print_lladdr(ndo, cp + 2, l); break; case ND_OPT_PREFIX_INFORMATION: opp = (const struct nd_opt_prefix_info *)op; ND_TCHECK(opp->nd_opt_pi_prefix); ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s", ip6addr_string(ndo, &opp->nd_opt_pi_prefix), opp->nd_opt_pi_prefix_len, (op->nd_opt_len != 4) ? "badlen" : "", bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved), get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time)))); ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time)))); break; case ND_OPT_REDIRECTED_HEADER: print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3); /* xxx */ break; case ND_OPT_MTU: opm = (const struct nd_opt_mtu *)op; ND_TCHECK(opm->nd_opt_mtu_mtu); ND_PRINT((ndo," %u%s", EXTRACT_32BITS(&opm->nd_opt_mtu_mtu), (op->nd_opt_len != 1) ? "bad option length" : "" )); break; case ND_OPT_RDNSS: oprd = (const struct nd_opt_rdnss *)op; l = (op->nd_opt_len - 1) / 2; ND_PRINT((ndo," lifetime %us,", EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime))); for (i = 0; i < l; i++) { ND_TCHECK(oprd->nd_opt_rdnss_addr[i]); ND_PRINT((ndo," addr: %s", ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i]))); } break; case ND_OPT_DNSSL: opds = (const struct nd_opt_dnssl *)op; ND_PRINT((ndo," lifetime %us, domain(s):", EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime))); domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */ while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0') { ND_PRINT((ndo, " ")); if ((domp = ns_nprint (ndo, domp, bp)) == NULL) goto trunc; } break; case ND_OPT_ADVINTERVAL: opa = (const struct nd_opt_advinterval *)op; ND_TCHECK(opa->nd_opt_adv_interval); ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval))); break; case ND_OPT_HOMEAGENT_INFO: oph = (const struct nd_opt_homeagent_info *)op; ND_TCHECK(oph->nd_opt_hai_lifetime); ND_PRINT((ndo," preference %u, lifetime %u", EXTRACT_16BITS(&oph->nd_opt_hai_preference), EXTRACT_16BITS(&oph->nd_opt_hai_lifetime))); break; case ND_OPT_ROUTE_INFO: opri = (const struct nd_opt_route_info *)op; ND_TCHECK(opri->nd_opt_rti_lifetime); memset(&in6, 0, sizeof(in6)); in6p = (const struct in6_addr *)(opri + 1); switch (op->nd_opt_len) { case 1: break; case 2: ND_TCHECK2(*in6p, 8); memcpy(&in6, opri + 1, 8); break; case 3: ND_TCHECK(*in6p); memcpy(&in6, opri + 1, sizeof(in6)); break; default: goto trunc; } ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6), opri->nd_opt_rti_prefixlen)); ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags))); ND_PRINT((ndo,", lifetime=%s", get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime)))); break; default: if (ndo->ndo_vflag <= 1) { print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ return; } break; } /* do we want to see an additional hexdump ? */ if (ndo->ndo_vflag> 1) print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */ cp += op->nd_opt_len << 3; resid -= op->nd_opt_len << 3; } return; trunc: ND_PRINT((ndo, "%s", icmp6_tstr)); return; #undef ECHECK }
169,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkHandler::GetAllCookies( std::unique_ptr<GetAllCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveAllCookiesOnIO, retriever, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::GetAllCookies( std::unique_ptr<GetAllCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } scoped_refptr<CookieRetriever> retriever = new CookieRetriever(std::move(callback)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &CookieRetriever::RetrieveAllCookiesOnIO, retriever, base::Unretained(storage_partition_->GetURLRequestContext()))); }
172,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionDispatchEvent(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; Event* evt(toEvent(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = jsBoolean(impl->dispatchEvent(evt, ec)); setDOMException(exec, ec); return JSValue::encode(result); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionDispatchEvent(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSTestEventTarget::s_info)) return throwVMTypeError(exec); JSTestEventTarget* castedThis = jsCast<JSTestEventTarget*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSTestEventTarget::s_info); TestEventTarget* impl = static_cast<TestEventTarget*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); ExceptionCode ec = 0; Event* evt(toEvent(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = jsBoolean(impl->dispatchEvent(evt, ec)); setDOMException(exec, ec); return JSValue::encode(result); }
170,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg) { int nid; long ret; nid = OBJ_obj2nid(p7->type); switch (cmd) { case PKCS7_OP_SET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { ret = p7->detached = (int)larg; ASN1_OCTET_STRING *os; os = p7->d.sign->contents->d.data; ASN1_OCTET_STRING_free(os); p7->d.sign->contents->d.data = NULL; } } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; case PKCS7_OP_GET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { if (!p7->d.sign || !p7->d.sign->contents->d.ptr) ret = 1; else ret = 0; p7->detached = ret; } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; default: PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION); ret = 0; } Commit Message: CWE ID:
long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg) { int nid; long ret; nid = OBJ_obj2nid(p7->type); switch (cmd) { /* NOTE(emilia): does not support detached digested data. */ case PKCS7_OP_SET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { ret = p7->detached = (int)larg; ASN1_OCTET_STRING *os; os = p7->d.sign->contents->d.data; ASN1_OCTET_STRING_free(os); p7->d.sign->contents->d.data = NULL; } } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; case PKCS7_OP_GET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { if (!p7->d.sign || !p7->d.sign->contents->d.ptr) ret = 1; else ret = 0; p7->detached = ret; } else { PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; default: PKCS7err(PKCS7_F_PKCS7_CTRL, PKCS7_R_UNKNOWN_OPERATION); ret = 0; }
164,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; int ret = 0; int ret2 = 0; if (list_empty(&EXT4_I(inode)->i_completed_io_list)) return ret; dump_completed_IO(inode); while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){ io = list_entry(EXT4_I(inode)->i_completed_io_list.next, ext4_io_end_t, list); /* * Calling ext4_end_io_nolock() to convert completed * IO to written. * * When ext4_sync_file() is called, run_queue() may already * about to flush the work corresponding to this io structure. * It will be upset if it founds the io structure related * to the work-to-be schedule is freed. * * Thus we need to keep the io structure still valid here after * convertion finished. The io structure has a flag to * avoid double converting from both fsync and background work * queue work. */ ret = ext4_end_io_nolock(io); if (ret < 0) ret2 = ret; else list_del_init(&io->list); } return (ret2 < 0) ? ret2 : 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
int flush_completed_IO(struct inode *inode) { ext4_io_end_t *io; struct ext4_inode_info *ei = EXT4_I(inode); unsigned long flags; int ret = 0; int ret2 = 0; if (list_empty(&ei->i_completed_io_list)) return ret; dump_completed_IO(inode); spin_lock_irqsave(&ei->i_completed_io_lock, flags); while (!list_empty(&ei->i_completed_io_list)){ io = list_entry(ei->i_completed_io_list.next, ext4_io_end_t, list); /* * Calling ext4_end_io_nolock() to convert completed * IO to written. * * When ext4_sync_file() is called, run_queue() may already * about to flush the work corresponding to this io structure. * It will be upset if it founds the io structure related * to the work-to-be schedule is freed. * * Thus we need to keep the io structure still valid here after * convertion finished. The io structure has a flag to * avoid double converting from both fsync and background work * queue work. */ spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); ret = ext4_end_io_nolock(io); spin_lock_irqsave(&ei->i_completed_io_lock, flags); if (ret < 0) ret2 = ret; else list_del_init(&io->list); } spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); return (ret2 < 0) ? ret2 : 0; }
167,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) { mAACProfile = aacParams->eAACProfile; } if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 0; mSBRRatio = 0; } else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 1; } else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 2; } else { mSBRMode = -1; // codec default sbr mode mSBRRatio = 0; } if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAACEncoder2::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.aac", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAAC)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } mBitRate = aacParams->nBitRate; mNumChannels = aacParams->nChannels; mSampleRate = aacParams->nSampleRate; if (aacParams->eAACProfile != OMX_AUDIO_AACObjectNull) { mAACProfile = aacParams->eAACProfile; } if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 0; mSBRRatio = 0; } else if ((aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && !(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 1; } else if (!(aacParams->nAACtools & OMX_AUDIO_AACToolAndroidSSBR) && (aacParams->nAACtools & OMX_AUDIO_AACToolAndroidDSBR)) { mSBRMode = 1; mSBRRatio = 2; } else { mSBRMode = -1; // codec default sbr mode mSBRRatio = 0; } if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mNumChannels = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; if (setAudioParams() != OK) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,191
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } s->s_flags = flags; rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_alloc_root(inode); if (!s->s_root) { iput(inode); rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); ecryptfs_set_dentry_lower(s->s_root, path.dentry); ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt); s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } Commit Message: Ecryptfs: Add mount option to check uid of device being mounted = expect uid Close a TOCTOU race for mounts done via ecryptfs-mount-private. The mount source (device) can be raced when the ownership test is done in userspace. Provide Ecryptfs a means to force the uid check at mount time. Signed-off-by: John Johansen <[email protected]> Cc: <[email protected]> Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-264
static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } s->s_flags = flags; rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && path.dentry->d_inode->i_uid != current_uid()) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", path.dentry->d_inode->i_uid, current_uid()); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_alloc_root(inode); if (!s->s_root) { iput(inode); rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); ecryptfs_set_dentry_lower(s->s_root, path.dentry); ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt); s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); }
165,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; VAPICHandlers *handlers; uint8_t opcode[2]; uint32_t imm32; target_ulong current_pc = 0; target_ulong current_cs_base = 0; uint32_t current_flags = 0; if (smp_cpus == 1) { handlers = &s->rom_state.up; } else { handlers = &s->rom_state.mp; } if (!kvm_enabled()) { cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base, &current_flags); } pause_all_vcpus(); cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0); switch (opcode[0]) { case 0x89: /* mov r32 to r/m32 */ patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */ patch_call(s, cpu, ip + 1, handlers->set_tpr); break; case 0x8b: /* mov r/m32 to r32 */ patch_byte(cpu, ip, 0x90); patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]); break; case 0xa1: /* mov abs to eax */ patch_call(s, cpu, ip, handlers->get_tpr[0]); break; case 0xa3: /* mov eax to abs */ patch_call(s, cpu, ip, handlers->set_tpr_eax); break; case 0xc7: /* mov imm32, r/m32 (c7/0) */ patch_byte(cpu, ip, 0x68); /* push imm32 */ cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0); cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1); patch_call(s, cpu, ip + 5, handlers->set_tpr); break; case 0xff: /* push r/m32 */ patch_byte(cpu, ip, 0x50); /* push eax */ patch_call(s, cpu, ip + 1, handlers->get_tpr_stack); break; default: abort(); } resume_all_vcpus(); if (!kvm_enabled()) { tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1); cpu_resume_from_signal(cs, NULL); } } Commit Message: CWE ID: CWE-200
static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip) { CPUState *cs = CPU(cpu); CPUX86State *env = &cpu->env; VAPICHandlers *handlers; uint8_t opcode[2]; uint32_t imm32 = 0; target_ulong current_pc = 0; target_ulong current_cs_base = 0; uint32_t current_flags = 0; if (smp_cpus == 1) { handlers = &s->rom_state.up; } else { handlers = &s->rom_state.mp; } if (!kvm_enabled()) { cpu_get_tb_cpu_state(env, &current_pc, &current_cs_base, &current_flags); } pause_all_vcpus(); cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0); switch (opcode[0]) { case 0x89: /* mov r32 to r/m32 */ patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */ patch_call(s, cpu, ip + 1, handlers->set_tpr); break; case 0x8b: /* mov r/m32 to r32 */ patch_byte(cpu, ip, 0x90); patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]); break; case 0xa1: /* mov abs to eax */ patch_call(s, cpu, ip, handlers->get_tpr[0]); break; case 0xa3: /* mov eax to abs */ patch_call(s, cpu, ip, handlers->set_tpr_eax); break; case 0xc7: /* mov imm32, r/m32 (c7/0) */ patch_byte(cpu, ip, 0x68); /* push imm32 */ cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0); cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1); patch_call(s, cpu, ip + 5, handlers->set_tpr); break; case 0xff: /* push r/m32 */ patch_byte(cpu, ip, 0x50); /* push eax */ patch_call(s, cpu, ip + 1, handlers->get_tpr_stack); break; default: abort(); } resume_all_vcpus(); if (!kvm_enabled()) { tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1); cpu_resume_from_signal(cs, NULL); } }
165,076
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int dtls1_get_record(SSL *s) { int ssl_major,ssl_minor; int i,n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr= &(s->s3->rrec); /* The epoch may have changed. If so, process all the * pending records. This is a non-blocking operation. */ dtls1_process_buffered_records(s); /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return(n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate=SSL_ST_READ_BODY; p=s->packet; if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Pull apart the header into the DTLS1_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p,rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p+=6; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); /* this packet contained a partial record, dump it */ if ( n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* now n == rr->length, * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if ( bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* Check whether this is a repeat, or aged record. * Don't check if we're listening and this message is * a ClientHello. They can look as if they're replayed, * since they arrive from different connections and * would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && *p == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length=0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* If this record is from the next epoch (either HM or ALERT), * and a handshake is currently in progress, buffer it since it * cannot be processed at this time. However, do not buffer * anything while listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num); } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } return(1); } Commit Message: Follow on from CVE-2014-3571. This fixes the code that was the original source of the crash due to p being NULL. Steve's fix prevents this situation from occuring - however this is by no means obvious by looking at the code for dtls1_get_record. This fix just makes things look a bit more sane. Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID:
int dtls1_get_record(SSL *s) { int ssl_major,ssl_minor; int i,n; SSL3_RECORD *rr; unsigned char *p = NULL; unsigned short version; DTLS1_BITMAP *bitmap; unsigned int is_next_epoch; rr= &(s->s3->rrec); /* The epoch may have changed. If so, process all the * pending records. This is a non-blocking operation. */ dtls1_process_buffered_records(s); /* if we're renegotiating, then there may be buffered records */ if (dtls1_get_processed_record(s)) return 1; /* get something from the wire */ again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < DTLS1_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); /* read timeout is handled by dtls1_read_bytes */ if (n <= 0) return(n); /* error or non-blocking */ /* this packet contained a partial record, dump it */ if (s->packet_length != DTLS1_RT_HEADER_LENGTH) { s->packet_length = 0; goto again; } s->rstate=SSL_ST_READ_BODY; p=s->packet; if (s->msg_callback) s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg); /* Pull apart the header into the DTLS1_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; /* sequence number is 64 bits, with top 2 bytes = epoch */ n2s(p,rr->epoch); memcpy(&(s->s3->read_sequence[2]), p, 6); p+=6; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { /* unexpected version, silently discard */ rr->length = 0; s->packet_length = 0; goto again; } } if ((version & 0xff00) != (s->version & 0xff00)) { /* wrong version, silently discard record */ rr->length = 0; s->packet_length = 0; goto again; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { /* record too long, silently discard it */ rr->length = 0; s->packet_length = 0; goto again; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH) { /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); /* this packet contained a partial record, dump it */ if ( n != i) { rr->length = 0; s->packet_length = 0; goto again; } /* now n == rr->length, * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* match epochs. NULL means the packet is dropped on the floor */ bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch); if ( bitmap == NULL) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP /* Only do replay check if no SCTP bio */ if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) { #endif /* Check whether this is a repeat, or aged record. * Don't check if we're listening and this message is * a ClientHello. They can look as if they're replayed, * since they arrive from different connections and * would be dropped unnecessarily. */ if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE && s->packet_length > DTLS1_RT_HEADER_LENGTH && s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) && !dtls1_record_replay_check(s, bitmap)) { rr->length = 0; s->packet_length=0; /* dump this record */ goto again; /* get another record */ } #ifndef OPENSSL_NO_SCTP } #endif /* just read a 0 length packet */ if (rr->length == 0) goto again; /* If this record is from the next epoch (either HM or ALERT), * and a handshake is currently in progress, buffer it since it * cannot be processed at this time. However, do not buffer * anything while listening. */ if (is_next_epoch) { if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) { dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num); } rr->length = 0; s->packet_length = 0; goto again; } if (!dtls1_process_record(s)) { rr->length = 0; s->packet_length = 0; /* dump this record */ goto again; /* get another record */ } return(1); }
166,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; if ((number_pixels*number_planes) != (size_t) (number_pixels*number_planes)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows*MagickMax(number_planes,4); pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: Fixed check for the number of pixels that will be allocated. CWE ID: CWE-125
static Image *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define SkipLinesOp 0x01 #define SetColorOp 0x02 #define SkipPixelsOp 0x03 #define ByteDataOp 0x05 #define RunDataOp 0x06 #define EOFOp 0x07 char magick[12]; Image *image; int opcode, operand, status; MagickStatusType flags; MagickSizeType number_pixels; MemoryInfo *pixel_info; Quantum index; register ssize_t x; register Quantum *q; register ssize_t i; register unsigned char *p; size_t bits_per_pixel, map_length, number_colormaps, number_planes, number_planes_filled, one, offset, pixel_info_length; ssize_t count, y; unsigned char background_color[256], *colormap, pixel, plane, *pixels; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Determine if this a RLE file. */ count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 2) || (memcmp(magick,"\122\314",2) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { /* Read image header. */ image->page.x=ReadBlobLSBShort(image); image->page.y=ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); flags=(MagickStatusType) ReadBlobByte(image); image->alpha_trait=flags & 0x04 ? BlendPixelTrait : UndefinedPixelTrait; number_planes=(size_t) ReadBlobByte(image); bits_per_pixel=(size_t) ReadBlobByte(image); number_colormaps=(size_t) ReadBlobByte(image); map_length=(unsigned char) ReadBlobByte(image); if (map_length >= 64) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); one=1; map_length=one << map_length; if ((number_planes == 0) || (number_planes == 2) || (bits_per_pixel != 8) || (image->columns == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (flags & 0x02) { /* No background color-- initialize to black. */ for (i=0; i < (ssize_t) number_planes; i++) background_color[i]=0; (void) ReadBlobByte(image); } else { /* Initialize background color. */ p=background_color; for (i=0; i < (ssize_t) number_planes; i++) *p++=(unsigned char) ReadBlobByte(image); } if ((number_planes & 0x01) == 0) (void) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } colormap=(unsigned char *) NULL; if (number_colormaps != 0) { /* Read image colormaps. */ colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps, 3*map_length*sizeof(*colormap)); if (colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; for (i=0; i < (ssize_t) number_colormaps; i++) for (x=0; x < (ssize_t) map_length; x++) *p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image)); } if ((flags & 0x08) != 0) { char *comment; size_t length; /* Read image comment. */ length=ReadBlobLSBShort(image); if (length != 0) { comment=(char *) AcquireQuantumMemory(length,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length-1,(unsigned char *) comment); comment[length-1]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); if ((length & 0x01) == 0) (void) ReadBlobByte(image); } } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Allocate RLE pixels. */ if (image->alpha_trait != UndefinedPixelTrait) number_planes++; number_pixels=(MagickSizeType) image->columns*image->rows; number_planes_filled=(number_planes % 2 == 0) ? number_planes : number_planes+1; if ((number_pixels*number_planes_filled) != (size_t) (number_pixels* number_planes_filled)) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info_length=image->columns*image->rows*number_planes_filled; pixel_info=AcquireVirtualMemory(pixel_info_length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if ((flags & 0x01) && !(flags & 0x02)) { ssize_t j; /* Set background color. */ p=pixels; for (i=0; i < (ssize_t) number_pixels; i++) { if (image->alpha_trait == UndefinedPixelTrait) for (j=0; j < (ssize_t) number_planes; j++) *p++=background_color[j]; else { for (j=0; j < (ssize_t) (number_planes-1); j++) *p++=background_color[j]; *p++=0; /* initialize matte channel */ } } } /* Read runlength-encoded image. */ plane=0; x=0; y=0; opcode=ReadBlobByte(image); do { switch (opcode & 0x3f) { case SkipLinesOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x=0; y+=operand; break; } case SetColorOp: { operand=ReadBlobByte(image); plane=(unsigned char) operand; if (plane == 255) plane=(unsigned char) (number_planes-1); x=0; break; } case SkipPixelsOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); x+=operand; break; } case ByteDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { pixel=(unsigned char) ReadBlobByte(image); if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } if (operand & 0x01) (void) ReadBlobByte(image); x+=operand; break; } case RunDataOp: { operand=ReadBlobByte(image); if (opcode & 0x40) operand=(int) ReadBlobLSBShort(image); pixel=(unsigned char) ReadBlobByte(image); (void) ReadBlobByte(image); offset=((image->rows-y-1)*image->columns*number_planes)+x* number_planes+plane; operand++; if (offset+((size_t) operand*number_planes) > pixel_info_length) { if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } p=pixels+offset; for (i=0; i < (ssize_t) operand; i++) { if ((y < (ssize_t) image->rows) && ((x+i) < (ssize_t) image->columns)) *p=pixel; p+=number_planes; } x+=operand; break; } default: break; } opcode=ReadBlobByte(image); } while (((opcode & 0x3f) != EOFOp) && (opcode != EOF)); if (number_colormaps != 0) { MagickStatusType mask; /* Apply colormap affineation to image. */ mask=(MagickStatusType) (map_length-1); p=pixels; x=(ssize_t) number_planes; if (number_colormaps == 1) for (i=0; i < (ssize_t) number_pixels; i++) { if (IsValidColormapIndex(image,*p & mask,&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } else if ((number_planes >= 3) && (number_colormaps >= 3)) for (i=0; i < (ssize_t) number_pixels; i++) for (x=0; x < (ssize_t) number_planes; x++) { if (IsValidColormapIndex(image,(size_t) (x*map_length+ (*p & mask)),&index,exception) == MagickFalse) break; *p=colormap[(ssize_t) index]; p++; } if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes)) { colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } } /* Initialize image structure. */ if (number_planes >= 3) { /* Convert raster image to DirectClass pixel packets. */ p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } } else { /* Create colormap. */ if (number_colormaps == 0) map_length=256; if (AcquireImageColormap(image,map_length,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=colormap; if (number_colormaps == 1) for (i=0; i < (ssize_t) image->colors; i++) { /* Pseudocolor. */ image->colormap[i].red=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum((unsigned char) i); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum((unsigned char) i); } else if (number_colormaps > 1) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*(p+map_length)); image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*(p+map_length*2)); p++; } p=pixels; if (image->alpha_trait == UndefinedPixelTrait) { /* Convert raster image to PseudoClass pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); } else { /* Image has a matte channel-- promote to DirectClass. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) index].red),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) index].green),q); if (IsValidColormapIndex(image,(ssize_t) *p++,&index, exception) == MagickFalse) break; SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) index].blue),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } image->colormap=(PixelInfo *) RelinquishMagickMemory( image->colormap); image->storage_class=DirectClass; image->colors=0; } } if (number_colormaps != 0) colormap=(unsigned char *) RelinquishMagickMemory(colormap); pixel_info=RelinquishVirtualMemory(pixel_info); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; (void) ReadBlobByte(image); count=ReadBlob(image,2,(unsigned char *) magick); if ((count != 0) && (memcmp(magick,"\122\314",2) == 0)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while ((count != 0) && (memcmp(magick,"\122\314",2) == 0)); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,808
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */
167,078
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetBrightnessLibrary( BrightnessLibrary* library, bool own) { library_->brightness_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetBrightnessLibrary(
170,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: CheckClientDownloadRequest( content::DownloadItem* item, const CheckDownloadCallback& callback, DownloadProtectionService* service, const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, BinaryFeatureExtractor* binary_feature_extractor) : item_(item), url_chain_(item->GetUrlChain()), referrer_url_(item->GetReferrerUrl()), tab_url_(item->GetTabUrl()), tab_referrer_url_(item->GetTabReferrerUrl()), zipped_executable_(false), callback_(callback), service_(service), binary_feature_extractor_(binary_feature_extractor), database_manager_(database_manager), pingback_enabled_(service_->enabled()), finished_(false), type_(ClientDownloadRequest::WIN_EXECUTABLE), start_time_(base::TimeTicks::Now()), weakptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); item_->AddObserver(this); } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
CheckClientDownloadRequest( content::DownloadItem* item, const CheckDownloadCallback& callback, DownloadProtectionService* service, const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager, BinaryFeatureExtractor* binary_feature_extractor) : item_(item), url_chain_(item->GetUrlChain()), referrer_url_(item->GetReferrerUrl()), tab_url_(item->GetTabUrl()), tab_referrer_url_(item->GetTabReferrerUrl()), archived_executable_(false), callback_(callback), service_(service), binary_feature_extractor_(binary_feature_extractor), database_manager_(database_manager), pingback_enabled_(service_->enabled()), finished_(false), type_(ClientDownloadRequest::WIN_EXECUTABLE), start_time_(base::TimeTicks::Now()), weakptr_factory_(this) { DCHECK_CURRENTLY_ON(BrowserThread::UI); item_->AddObserver(this); }
171,712
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(finfo_open) { long options = MAGIC_NONE; char *file = NULL; int file_len = 0; struct php_fileinfo *finfo; FILEINFO_DECLARE_INIT_OBJECT(object) char resolved_path[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lp", &options, &file, &file_len) == FAILURE) { FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (object) { struct finfo_object *finfo_obj = (struct finfo_object*)zend_object_store_get_object(object TSRMLS_CC); if (finfo_obj->ptr) { magic_close(finfo_obj->ptr->magic); efree(finfo_obj->ptr); finfo_obj->ptr = NULL; } } if (file_len == 0) { file = NULL; } else if (file && *file) { /* user specified file, perform open_basedir checks */ #if PHP_API_VERSION < 20100412 if ((PG(safe_mode) && (!php_checkuid(file, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(file TSRMLS_CC)) { #else if (php_check_open_basedir(file TSRMLS_CC)) { #endif FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (!expand_filepath_with_mode(file, resolved_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } file = resolved_path; } finfo = emalloc(sizeof(struct php_fileinfo)); finfo->options = options; finfo->magic = magic_open(options); if (finfo->magic == NULL) { efree(finfo); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid mode '%ld'.", options); FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (magic_load(finfo->magic, file) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database at '%s'.", file); magic_close(finfo->magic); efree(finfo); FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (object) { FILEINFO_REGISTER_OBJECT(object, finfo); } else { ZEND_REGISTER_RESOURCE(return_value, finfo, le_fileinfo); } } /* }}} */ /* {{{ proto resource finfo_close(resource finfo) Close fileinfo resource. */ PHP_FUNCTION(finfo_close) { struct php_fileinfo *finfo; zval *zfinfo; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zfinfo) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); zend_list_delete(Z_RESVAL_P(zfinfo)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool finfo_set_flags(resource finfo, int options) Set libmagic configuration options. */ PHP_FUNCTION(finfo_set_flags) { long options; struct php_fileinfo *finfo; zval *zfinfo; FILEINFO_DECLARE_INIT_OBJECT(object) if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &options) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zfinfo, &options) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); } FINFO_SET_OPTION(finfo->magic, options) finfo->options = options; RETURN_TRUE; } /* }}} */ #define FILEINFO_MODE_BUFFER 0 #define FILEINFO_MODE_STREAM 1 #define FILEINFO_MODE_FILE 2 static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */ { long options = 0; char *ret_val = NULL, *buffer = NULL; int buffer_len; struct php_fileinfo *finfo = NULL; zval *zfinfo, *zcontext = NULL; zval *what; char mime_directory[] = "directory"; struct magic_set *magic = NULL; FILEINFO_DECLARE_INIT_OBJECT(object) if (mimetype_emu) { /* mime_content_type(..) emulation */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &what) == FAILURE) { return; } switch (Z_TYPE_P(what)) { case IS_STRING: buffer = Z_STRVAL_P(what); buffer_len = Z_STRLEN_P(what); mode = FILEINFO_MODE_FILE; break; case IS_RESOURCE: mode = FILEINFO_MODE_STREAM; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); RETURN_FALSE; } magic = magic_open(MAGIC_MIME_TYPE); if (magic_load(magic, NULL) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database."); goto common; } } else if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); magic = finfo->magic; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); magic = finfo->magic; } /* Set options for the current file/buffer. */ if (options) { FINFO_SET_OPTION(magic, options) } switch (mode) { case FILEINFO_MODE_BUFFER: { ret_val = (char *) magic_buffer(magic, buffer, buffer_len); break; } case FILEINFO_MODE_STREAM: { php_stream *stream; off_t streampos; php_stream_from_zval_no_verify(stream, &what); if (!stream) { goto common; } streampos = php_stream_tell(stream); /* remember stream position for restoration */ php_stream_seek(stream, 0, SEEK_SET); ret_val = (char *) magic_stream(magic, stream); php_stream_seek(stream, streampos, SEEK_SET); break; } case FILEINFO_MODE_FILE: { /* determine if the file is a local file or remote URL */ char *tmp2; php_stream_wrapper *wrap; php_stream_statbuf ssb; if (buffer == NULL || !*buffer) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename or path"); RETVAL_FALSE; goto clean; } wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0 TSRMLS_CC); if (php_stream_stat_path_ex(buffer, 0, &ssb, context) == SUCCESS) { if (ssb.sb.st_mode & S_IFDIR) { ret_val = mime_directory; goto common; } } #endif #if PHP_API_VERSION < 20100412 stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context); #else stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context); #endif if (!stream) { RETVAL_FALSE; goto clean; } if (php_stream_stat(stream, &ssb) == SUCCESS) { if (ssb.sb.st_mode & S_IFDIR) { ret_val = mime_directory; } else { ret_val = (char *)magic_stream(magic, stream); } } php_stream_close(stream); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); } common: if (ret_val) { RETVAL_STRING(ret_val, 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic)); RETVAL_FALSE; } clean: if (mimetype_emu) { magic_close(magic); } /* Restore options */ if (options) { FINFO_SET_OPTION(magic, finfo->options) } return; } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(finfo_open) { long options = MAGIC_NONE; char *file = NULL; int file_len = 0; struct php_fileinfo *finfo; FILEINFO_DECLARE_INIT_OBJECT(object) char resolved_path[MAXPATHLEN]; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lp", &options, &file, &file_len) == FAILURE) { FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (object) { struct finfo_object *finfo_obj = (struct finfo_object*)zend_object_store_get_object(object TSRMLS_CC); if (finfo_obj->ptr) { magic_close(finfo_obj->ptr->magic); efree(finfo_obj->ptr); finfo_obj->ptr = NULL; } } if (file_len == 0) { file = NULL; } else if (file && *file) { /* user specified file, perform open_basedir checks */ #if PHP_API_VERSION < 20100412 if ((PG(safe_mode) && (!php_checkuid(file, NULL, CHECKUID_CHECK_FILE_AND_DIR))) || php_check_open_basedir(file TSRMLS_CC)) { #else if (php_check_open_basedir(file TSRMLS_CC)) { #endif FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (!expand_filepath_with_mode(file, resolved_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } file = resolved_path; } finfo = emalloc(sizeof(struct php_fileinfo)); finfo->options = options; finfo->magic = magic_open(options); if (finfo->magic == NULL) { efree(finfo); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid mode '%ld'.", options); FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (magic_load(finfo->magic, file) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database at '%s'.", file); magic_close(finfo->magic); efree(finfo); FILEINFO_DESTROY_OBJECT(object); RETURN_FALSE; } if (object) { FILEINFO_REGISTER_OBJECT(object, finfo); } else { ZEND_REGISTER_RESOURCE(return_value, finfo, le_fileinfo); } } /* }}} */ /* {{{ proto resource finfo_close(resource finfo) Close fileinfo resource. */ PHP_FUNCTION(finfo_close) { struct php_fileinfo *finfo; zval *zfinfo; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zfinfo) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); zend_list_delete(Z_RESVAL_P(zfinfo)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool finfo_set_flags(resource finfo, int options) Set libmagic configuration options. */ PHP_FUNCTION(finfo_set_flags) { long options; struct php_fileinfo *finfo; zval *zfinfo; FILEINFO_DECLARE_INIT_OBJECT(object) if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &options) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zfinfo, &options) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); } FINFO_SET_OPTION(finfo->magic, options) finfo->options = options; RETURN_TRUE; } /* }}} */ #define FILEINFO_MODE_BUFFER 0 #define FILEINFO_MODE_STREAM 1 #define FILEINFO_MODE_FILE 2 static void _php_finfo_get_type(INTERNAL_FUNCTION_PARAMETERS, int mode, int mimetype_emu) /* {{{ */ { long options = 0; char *ret_val = NULL, *buffer = NULL; int buffer_len; struct php_fileinfo *finfo = NULL; zval *zfinfo, *zcontext = NULL; zval *what; char mime_directory[] = "directory"; struct magic_set *magic = NULL; FILEINFO_DECLARE_INIT_OBJECT(object) if (mimetype_emu) { /* mime_content_type(..) emulation */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &what) == FAILURE) { return; } switch (Z_TYPE_P(what)) { case IS_STRING: buffer = Z_STRVAL_P(what); buffer_len = Z_STRLEN_P(what); mode = FILEINFO_MODE_FILE; break; case IS_RESOURCE: mode = FILEINFO_MODE_STREAM; break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); RETURN_FALSE; } magic = magic_open(MAGIC_MIME_TYPE); if (magic_load(magic, NULL) == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to load magic database."); goto common; } } else if (object) { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lr", &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } FILEINFO_FROM_OBJECT(finfo, object); magic = finfo->magic; } else { if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lr", &zfinfo, &buffer, &buffer_len, &options, &zcontext) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(finfo, struct php_fileinfo *, &zfinfo, -1, "file_info", le_fileinfo); magic = finfo->magic; } /* Set options for the current file/buffer. */ if (options) { FINFO_SET_OPTION(magic, options) } switch (mode) { case FILEINFO_MODE_BUFFER: { ret_val = (char *) magic_buffer(magic, buffer, buffer_len); break; } case FILEINFO_MODE_STREAM: { php_stream *stream; off_t streampos; php_stream_from_zval_no_verify(stream, &what); if (!stream) { goto common; } streampos = php_stream_tell(stream); /* remember stream position for restoration */ php_stream_seek(stream, 0, SEEK_SET); ret_val = (char *) magic_stream(magic, stream); php_stream_seek(stream, streampos, SEEK_SET); break; } case FILEINFO_MODE_FILE: { /* determine if the file is a local file or remote URL */ char *tmp2; php_stream_wrapper *wrap; php_stream_statbuf ssb; if (buffer == NULL || !*buffer) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename or path"); RETVAL_FALSE; goto clean; } if (CHECK_NULL_PATH(buffer, buffer_len)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid path"); RETVAL_FALSE; goto clean; } wrap = php_stream_locate_url_wrapper(buffer, &tmp2, 0 TSRMLS_CC); if (php_stream_stat_path_ex(buffer, 0, &ssb, context) == SUCCESS) { if (ssb.sb.st_mode & S_IFDIR) { ret_val = mime_directory; goto common; } } #endif #if PHP_API_VERSION < 20100412 stream = php_stream_open_wrapper_ex(buffer, "rb", ENFORCE_SAFE_MODE | REPORT_ERRORS, NULL, context); #else stream = php_stream_open_wrapper_ex(buffer, "rb", REPORT_ERRORS, NULL, context); #endif if (!stream) { RETVAL_FALSE; goto clean; } if (php_stream_stat(stream, &ssb) == SUCCESS) { if (ssb.sb.st_mode & S_IFDIR) { ret_val = mime_directory; } else { ret_val = (char *)magic_stream(magic, stream); } } php_stream_close(stream); } break; } default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only process string or stream arguments"); } common: if (ret_val) { RETVAL_STRING(ret_val, 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed identify data %d:%s", magic_errno(magic), magic_error(magic)); RETVAL_FALSE; } clean: if (mimetype_emu) { magic_close(magic); } /* Restore options */ if (options) { FINFO_SET_OPTION(magic, finfo->options) } return; }
165,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RemoveProcessIdFromGlobalMap(int32_t process_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); GetProcessIdToFilterMap()->erase(process_id); } Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362
void RemoveProcessIdFromGlobalMap(int32_t process_id) {
173,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int swp_handler(struct pt_regs *regs, unsigned int instr) { unsigned int address, destreg, data, type; unsigned int res = 0; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, regs->ARM_pc); if (current->pid != previous_pid) { pr_debug("\"%s\" (%ld) uses deprecated SWP{B} instruction\n", current->comm, (unsigned long)current->pid); previous_pid = current->pid; } address = regs->uregs[EXTRACT_REG_NUM(instr, RN_OFFSET)]; data = regs->uregs[EXTRACT_REG_NUM(instr, RT2_OFFSET)]; destreg = EXTRACT_REG_NUM(instr, RT_OFFSET); type = instr & TYPE_SWPB; pr_debug("addr in r%d->0x%08x, dest is r%d, source in r%d->0x%08x)\n", EXTRACT_REG_NUM(instr, RN_OFFSET), address, destreg, EXTRACT_REG_NUM(instr, RT2_OFFSET), data); /* Check access in reasonable access range for both SWP and SWPB */ if (!access_ok(VERIFY_WRITE, (address & ~3), 4)) { pr_debug("SWP{B} emulation: access to %p not allowed!\n", (void *)address); res = -EFAULT; } else { res = emulate_swpX(address, &data, type); } if (res == 0) { /* * On successful emulation, revert the adjustment to the PC * made in kernel/traps.c in order to resume execution at the * instruction following the SWP{B}. */ regs->ARM_pc += 4; regs->uregs[destreg] = data; } else if (res == -EFAULT) { /* * Memory errors do not mean emulation failed. * Set up signal info to return SEGV, then return OK */ set_segfault(regs, address); } return 0; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int swp_handler(struct pt_regs *regs, unsigned int instr) { unsigned int address, destreg, data, type; unsigned int res = 0; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, regs->ARM_pc); if (current->pid != previous_pid) { pr_debug("\"%s\" (%ld) uses deprecated SWP{B} instruction\n", current->comm, (unsigned long)current->pid); previous_pid = current->pid; } address = regs->uregs[EXTRACT_REG_NUM(instr, RN_OFFSET)]; data = regs->uregs[EXTRACT_REG_NUM(instr, RT2_OFFSET)]; destreg = EXTRACT_REG_NUM(instr, RT_OFFSET); type = instr & TYPE_SWPB; pr_debug("addr in r%d->0x%08x, dest is r%d, source in r%d->0x%08x)\n", EXTRACT_REG_NUM(instr, RN_OFFSET), address, destreg, EXTRACT_REG_NUM(instr, RT2_OFFSET), data); /* Check access in reasonable access range for both SWP and SWPB */ if (!access_ok(VERIFY_WRITE, (address & ~3), 4)) { pr_debug("SWP{B} emulation: access to %p not allowed!\n", (void *)address); res = -EFAULT; } else { res = emulate_swpX(address, &data, type); } if (res == 0) { /* * On successful emulation, revert the adjustment to the PC * made in kernel/traps.c in order to resume execution at the * instruction following the SWP{B}. */ regs->ARM_pc += 4; regs->uregs[destreg] = data; } else if (res == -EFAULT) { /* * Memory errors do not mean emulation failed. * Set up signal info to return SEGV, then return OK */ set_segfault(regs, address); } return 0; }
165,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EncoderTest::InitializeConfig() { const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0); ASSERT_EQ(VPX_CODEC_OK, res); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void EncoderTest::InitializeConfig() { const vpx_codec_err_t res = codec_->DefaultEncoderConfig(&cfg_, 0); dec_cfg_ = vpx_codec_dec_cfg_t(); ASSERT_EQ(VPX_CODEC_OK, res); }
174,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); } Commit Message: CWE ID: CWE-20
static void get_socket_name(SingleInstData* data, char* buf, int len) { const char* dpy = g_getenv("DISPLAY"); char* host = NULL; int dpynum; if(dpy) { const char* p = strrchr(dpy, ':'); host = g_strndup(dpy, (p - dpy)); dpynum = atoi(p + 1); } else dpynum = 0; #if GLIB_CHECK_VERSION(2, 28, 0) g_snprintf(buf, len, "%s/%s-socket-%s-%d", g_get_user_runtime_dir(), data->prog_name, host ? host : "", dpynum); #else g_snprintf(buf, len, "%s/.%s-socket-%s-%d-%s", g_get_tmp_dir(), data->prog_name, host ? host : "", dpynum, g_get_user_name()); #endif }
164,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __perf_event_overflow(struct perf_event *event, int nmi, int throttle, struct perf_sample_data *data, struct pt_regs *regs) { int events = atomic_read(&event->event_limit); struct hw_perf_event *hwc = &event->hw; int ret = 0; /* * Non-sampling counters might still use the PMI to fold short * hardware counters, ignore those. */ if (unlikely(!is_sampling_event(event))) return 0; if (unlikely(hwc->interrupts >= max_samples_per_tick)) { if (throttle) { hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); ret = 1; } } else hwc->interrupts++; if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period); } /* * XXX event_limit might not quite work as expected on inherited * events */ event->pending_kill = POLL_IN; if (events && atomic_dec_and_test(&event->event_limit)) { ret = 1; event->pending_kill = POLL_HUP; if (nmi) { event->pending_disable = 1; irq_work_queue(&event->pending); } else perf_event_disable(event); } if (event->overflow_handler) event->overflow_handler(event, nmi, data, regs); else perf_event_output(event, nmi, data, regs); if (event->fasync && event->pending_kill) { if (nmi) { event->pending_wakeup = 1; irq_work_queue(&event->pending); } else perf_event_wakeup(event); } return ret; } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static int __perf_event_overflow(struct perf_event *event, int nmi, static int __perf_event_overflow(struct perf_event *event, int throttle, struct perf_sample_data *data, struct pt_regs *regs) { int events = atomic_read(&event->event_limit); struct hw_perf_event *hwc = &event->hw; int ret = 0; /* * Non-sampling counters might still use the PMI to fold short * hardware counters, ignore those. */ if (unlikely(!is_sampling_event(event))) return 0; if (unlikely(hwc->interrupts >= max_samples_per_tick)) { if (throttle) { hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); ret = 1; } } else hwc->interrupts++; if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period); } /* * XXX event_limit might not quite work as expected on inherited * events */ event->pending_kill = POLL_IN; if (events && atomic_dec_and_test(&event->event_limit)) { ret = 1; event->pending_kill = POLL_HUP; event->pending_disable = 1; irq_work_queue(&event->pending); } if (event->overflow_handler) event->overflow_handler(event, data, regs); else perf_event_output(event, data, regs); if (event->fasync && event->pending_kill) { event->pending_wakeup = 1; irq_work_queue(&event->pending); } return ret; }
165,826
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_transform_png_set_expand_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); }
173,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeOSStopInputMethodProcess(InputMethodStatusConnection* connection) { g_return_val_if_fail(connection, false); return connection->StopInputMethodProcess(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChromeOSStopInputMethodProcess(InputMethodStatusConnection* connection) {
170,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel, const struct iw_csdescr *out_csdescr) { int i,j; int z; int k; int retval=0; iw_tmpsample tmpsamp; iw_tmpsample alphasamp = 0.0; iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples int using_errdiffdither = 0; int output_channel; int is_alpha_channel; int bkgd_has_transparency; double tmpbkgdalpha=0.0; int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample struct iw_resize_settings *rs = NULL; int ditherfamily, dithersubtype; struct iw_channelinfo_intermed *int_ci; struct iw_channelinfo_out *out_ci; iw_tmpsample *in_pix = NULL; iw_tmpsample *out_pix = NULL; int num_in_pix; int num_out_pix; num_in_pix = ctx->intermed_canvas_width; num_out_pix = ctx->img2.width; int_ci = &ctx->intermed_ci[intermed_channel]; output_channel = int_ci->corresponding_output_channel; out_ci = &ctx->img2_ci[output_channel]; is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA); bkgd_has_transparency = iw_bkgd_has_transparency(ctx); inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample)); in_pix = inpix_tofree; outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample)); if(!outpix_tofree) goto done; out_pix = outpix_tofree; if(ctx->nearest_color_table && !is_alpha_channel && out_ci->ditherfamily==IW_DITHERFAMILY_NONE && out_ci->color_count==0) { out_ci->use_nearest_color_table = 1; } else { out_ci->use_nearest_color_table = 0; } ditherfamily = out_ci->ditherfamily; dithersubtype = out_ci->dithersubtype; if(ditherfamily==IW_DITHERFAMILY_RANDOM) { if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA) { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed); } else { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype); } } if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) { using_errdiffdither = 1; for(i=0;i<ctx->img2.width;i++) { for(k=0;k<IW_DITHER_MAXROWS;k++) { ctx->dither_errors[k][i] = 0.0; } } } rs=&ctx->resize_settings[IW_DIMENSION_H]; if(!rs->rrctx) { rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype, num_in_pix, num_out_pix); if(!rs->rrctx) goto done; } for(j=0;j<ctx->intermed_canvas_height;j++) { if(is_alpha_channel) { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i]; } } else { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i]; } } iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix); if(ctx->intclamp) clamp_output_samples(ctx,out_pix,num_out_pix); if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) { for(i=0;i<num_out_pix;i++) { ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i]; } } if(output_channel == -1) { goto here; } for(z=0;z<ctx->img2.width;z++) { if(using_errdiffdither && (j%2)) i=ctx->img2.width-1-z; else i=z; tmpsamp = out_pix[i]; if(ctx->bkgd_checkerboard) { alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) != (((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2); } if(bkgd_has_transparency) { tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha; } if(int_ci->need_unassoc_alpha_processing) { alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i]; if(alphasamp!=0.0) { tmpsamp /= alphasamp; } if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) { double bkcolor; bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin; if(bkgd_has_transparency) { tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp); } else { tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp); } } } else if(is_alpha_channel && bkgd_has_transparency) { tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp); } if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr); else put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr); } if(using_errdiffdither) { for(i=0;i<ctx->img2.width;i++) { for(k=0;k<IW_DITHER_MAXROWS-1;k++) { ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i]; } ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0; } } here: ; } retval=1; done: if(rs && rs->disable_rrctx_cache && rs->rrctx) { iwpvt_resize_rows_done(rs->rrctx); rs->rrctx = NULL; } if(inpix_tofree) iw_free(ctx,inpix_tofree); if(outpix_tofree) iw_free(ctx,outpix_tofree); return retval; } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787
static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel, const struct iw_csdescr *out_csdescr) { int i,j; int z; int k; int retval=0; iw_tmpsample tmpsamp; iw_tmpsample alphasamp = 0.0; iw_tmpsample *inpix_tofree = NULL; // Used if we need a separate temp buffer for input samples iw_tmpsample *outpix_tofree = NULL; // Used if we need a separate temp buffer for output samples int using_errdiffdither = 0; int output_channel; int is_alpha_channel; int bkgd_has_transparency; double tmpbkgdalpha=0.0; int alt_bkgd = 0; // Nonzero if we should use bkgd2 for this sample struct iw_resize_settings *rs = NULL; int ditherfamily, dithersubtype; struct iw_channelinfo_intermed *int_ci; struct iw_channelinfo_out *out_ci; iw_tmpsample *in_pix = NULL; iw_tmpsample *out_pix = NULL; int num_in_pix; int num_out_pix; struct iw_channelinfo_out default_ci_out; num_in_pix = ctx->intermed_canvas_width; num_out_pix = ctx->img2.width; int_ci = &ctx->intermed_ci[intermed_channel]; output_channel = int_ci->corresponding_output_channel; if(output_channel>=0) { out_ci = &ctx->img2_ci[output_channel]; } else { // If there is no output channelinfo struct, create a temporary one to // use. // TODO: This is admittedly ugly, but we use these settings for a few // things even when there is no corresponding output channel, and I // don't remember exactly why. iw_zeromem(&default_ci_out, sizeof(struct iw_channelinfo_out)); default_ci_out.channeltype = IW_CHANNELTYPE_NONALPHA; out_ci = &default_ci_out; } is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA); bkgd_has_transparency = iw_bkgd_has_transparency(ctx); inpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_in_pix * sizeof(iw_tmpsample)); in_pix = inpix_tofree; outpix_tofree = (iw_tmpsample*)iw_malloc(ctx, num_out_pix * sizeof(iw_tmpsample)); if(!outpix_tofree) goto done; out_pix = outpix_tofree; if(ctx->nearest_color_table && !is_alpha_channel && out_ci->ditherfamily==IW_DITHERFAMILY_NONE && out_ci->color_count==0) { out_ci->use_nearest_color_table = 1; } else { out_ci->use_nearest_color_table = 0; } ditherfamily = out_ci->ditherfamily; dithersubtype = out_ci->dithersubtype; if(ditherfamily==IW_DITHERFAMILY_RANDOM) { if(dithersubtype==IW_DITHERSUBTYPE_SAMEPATTERN && out_ci->channeltype!=IW_CHANNELTYPE_ALPHA) { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed); } else { iwpvt_prng_set_random_seed(ctx->prng,ctx->random_seed+out_ci->channeltype); } } if(output_channel>=0 && out_ci->ditherfamily==IW_DITHERFAMILY_ERRDIFF) { using_errdiffdither = 1; for(i=0;i<ctx->img2.width;i++) { for(k=0;k<IW_DITHER_MAXROWS;k++) { ctx->dither_errors[k][i] = 0.0; } } } rs=&ctx->resize_settings[IW_DIMENSION_H]; if(!rs->rrctx) { rs->rrctx = iwpvt_resize_rows_init(ctx,rs,int_ci->channeltype, num_in_pix, num_out_pix); if(!rs->rrctx) goto done; } for(j=0;j<ctx->intermed_canvas_height;j++) { if(is_alpha_channel) { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate_alpha32[((size_t)j)*ctx->intermed_canvas_width+i]; } } else { for(i=0;i<num_in_pix;i++) { inpix_tofree[i] = ctx->intermediate32[((size_t)j)*ctx->intermed_canvas_width+i]; } } iwpvt_resize_row_main(rs->rrctx,in_pix,out_pix); if(ctx->intclamp) clamp_output_samples(ctx,out_pix,num_out_pix); if(is_alpha_channel && outpix_tofree && ctx->final_alpha32) { for(i=0;i<num_out_pix;i++) { ctx->final_alpha32[((size_t)j)*ctx->img2.width+i] = (iw_float32)outpix_tofree[i]; } } if(output_channel == -1) { goto here; } for(z=0;z<ctx->img2.width;z++) { if(using_errdiffdither && (j%2)) i=ctx->img2.width-1-z; else i=z; tmpsamp = out_pix[i]; if(ctx->bkgd_checkerboard) { alt_bkgd = (((ctx->bkgd_check_origin[IW_DIMENSION_H]+i)/ctx->bkgd_check_size)%2) != (((ctx->bkgd_check_origin[IW_DIMENSION_V]+j)/ctx->bkgd_check_size)%2); } if(bkgd_has_transparency) { tmpbkgdalpha = alt_bkgd ? ctx->bkgd2alpha : ctx->bkgd1alpha; } if(int_ci->need_unassoc_alpha_processing) { alphasamp = ctx->final_alpha32[((size_t)j)*ctx->img2.width + i]; if(alphasamp!=0.0) { tmpsamp /= alphasamp; } if(ctx->apply_bkgd && ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_LATE) { double bkcolor; bkcolor = alt_bkgd ? out_ci->bkgd2_color_lin : out_ci->bkgd1_color_lin; if(bkgd_has_transparency) { tmpsamp = tmpsamp*alphasamp + bkcolor*tmpbkgdalpha*(1.0-alphasamp); } else { tmpsamp = tmpsamp*alphasamp + bkcolor*(1.0-alphasamp); } } } else if(is_alpha_channel && bkgd_has_transparency) { tmpsamp = tmpsamp + tmpbkgdalpha*(1.0-tmpsamp); } if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) put_sample_convert_from_linear_flt(ctx,tmpsamp,i,j,output_channel,out_csdescr); else put_sample_convert_from_linear(ctx,tmpsamp,i,j,output_channel,out_csdescr); } if(using_errdiffdither) { for(i=0;i<ctx->img2.width;i++) { for(k=0;k<IW_DITHER_MAXROWS-1;k++) { ctx->dither_errors[k][i] = ctx->dither_errors[k+1][i]; } ctx->dither_errors[IW_DITHER_MAXROWS-1][i] = 0.0; } } here: ; } retval=1; done: if(rs && rs->disable_rrctx_cache && rs->rrctx) { iwpvt_resize_rows_done(rs->rrctx); rs->rrctx = NULL; } if(inpix_tofree) iw_free(ctx,inpix_tofree); if(outpix_tofree) iw_free(ctx,outpix_tofree); return retval; }
168,118
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int itacns_add_data_files(sc_pkcs15_card_t *p15card) { const size_t array_size = sizeof(itacns_data_files)/sizeof(itacns_data_files[0]); unsigned int i; int rv; sc_pkcs15_data_t *p15_personaldata = NULL; sc_pkcs15_data_info_t dinfo; struct sc_pkcs15_object *objs[32]; struct sc_pkcs15_data_info *cinfo; for(i=0; i < array_size; i++) { sc_path_t path; sc_pkcs15_data_info_t data; sc_pkcs15_object_t obj; if (itacns_data_files[i].cie_only && p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2) continue; sc_format_path(itacns_data_files[i].path, &path); memset(&data, 0, sizeof(data)); memset(&obj, 0, sizeof(obj)); strlcpy(data.app_label, itacns_data_files[i].label, sizeof(data.app_label)); strlcpy(obj.label, itacns_data_files[i].label, sizeof(obj.label)); data.path = path; rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data); SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv, "Could not add data file"); } /* * If we got this far, we can read the Personal Data file and glean * the user's full name. Thus we can use it to put together a * user-friendlier card name. */ memset(&dinfo, 0, sizeof(dinfo)); strcpy(dinfo.app_label, "EF_DatiPersonali"); /* Find EF_DatiPersonali */ rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32); if(rv < 0) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Data enumeration failed"); return SC_SUCCESS; } for(i=0; i<32; i++) { cinfo = (struct sc_pkcs15_data_info *) objs[i]->data; if(!strcmp("EF_DatiPersonali", objs[i]->label)) break; } if(i>=32) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not find EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata); if (rv) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not read EF_DatiPersonali: " "keeping generic card name"); } { char fullname[160]; if(get_name_from_EF_DatiPersonali(p15_personaldata->data, fullname, sizeof(fullname))) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not parse EF_DatiPersonali: " "keeping generic card name"); sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } set_string(&p15card->tokeninfo->label, fullname); } sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } 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
static int itacns_add_data_files(sc_pkcs15_card_t *p15card) { const size_t array_size = sizeof(itacns_data_files)/sizeof(itacns_data_files[0]); unsigned int i; int rv; sc_pkcs15_data_t *p15_personaldata = NULL; sc_pkcs15_data_info_t dinfo; struct sc_pkcs15_object *objs[32]; struct sc_pkcs15_data_info *cinfo; for(i=0; i < array_size; i++) { sc_path_t path; sc_pkcs15_data_info_t data; sc_pkcs15_object_t obj; if (itacns_data_files[i].cie_only && p15card->card->type != SC_CARD_TYPE_ITACNS_CIE_V2) continue; sc_format_path(itacns_data_files[i].path, &path); memset(&data, 0, sizeof(data)); memset(&obj, 0, sizeof(obj)); strlcpy(data.app_label, itacns_data_files[i].label, sizeof(data.app_label)); strlcpy(obj.label, itacns_data_files[i].label, sizeof(obj.label)); data.path = path; rv = sc_pkcs15emu_add_data_object(p15card, &obj, &data); SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, rv, "Could not add data file"); } /* * If we got this far, we can read the Personal Data file and glean * the user's full name. Thus we can use it to put together a * user-friendlier card name. */ memset(&dinfo, 0, sizeof(dinfo)); strcpy(dinfo.app_label, "EF_DatiPersonali"); /* Find EF_DatiPersonali */ rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_DATA_OBJECT, objs, 32); if(rv < 0) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Data enumeration failed"); return SC_SUCCESS; } for(i=0; i<32; i++) { cinfo = (struct sc_pkcs15_data_info *) objs[i]->data; if(!strcmp("EF_DatiPersonali", objs[i]->label)) break; } if(i>=32) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not find EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } rv = sc_pkcs15_read_data_object(p15card, cinfo, &p15_personaldata); if (rv) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not read EF_DatiPersonali: " "keeping generic card name"); return SC_SUCCESS; } { char fullname[160]; if(get_name_from_EF_DatiPersonali(p15_personaldata->data, fullname, sizeof(fullname))) { sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, "Could not parse EF_DatiPersonali: " "keeping generic card name"); sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; } set_string(&p15card->tokeninfo->label, fullname); } sc_pkcs15_free_data_object(p15_personaldata); return SC_SUCCESS; }
169,066
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: videobuf_vm_open(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; dprintk(2,"vm_open %p [count=%d,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count++; } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
videobuf_vm_open(struct vm_area_struct *vma) { struct videobuf_mapping *map = vma->vm_private_data; dprintk(2,"vm_open %p [count=%u,vma=%08lx-%08lx]\n",map, map->count,vma->vm_start,vma->vm_end); map->count++; }
168,919