instruction
stringclasses
1 value
input
stringlengths
222
112k
output
stringlengths
21
113k
__index_level_0__
int64
15
30k
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.
Code: WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst) { void (*cb) (const SSL *ssl, int type, int val) = NULL; #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) { WORK_STATE ret; ret = dtls_wait_for_dry(s); if (ret != WORK_FINISHED_CONTINUE) return ret; } #endif /* clean a few things up */ ssl3_cleanup_key_block(s); if (!SSL_IS_DTLS(s)) { /* * We don't do this in DTLS because we may still need the init_buf * in case there are any unexpected retransmits */ BUF_MEM_free(s->init_buf); s->init_buf = NULL; } ssl_free_wbio_buffer(s); s->init_num = 0; if (!s->server || s->renegotiate == 2) { /* skipped if we just sent a HelloRequest */ s->renegotiate = 0; s->new_session = 0; if (s->server) { ssl_update_cache(s, SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; s->handshake_func = ossl_statem_accept; } else { ssl_update_cache(s, SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; s->handshake_func = ossl_statem_connect; s->ctx->stats.sess_connect_good++; } if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_DONE, 1); if (SSL_IS_DTLS(s)) { /* done with handshaking */ s->d1->handshake_read_seq = 0; s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; } } } Commit Message: CWE ID: CWE-399
WORK_STATE tls_finish_handshake(SSL *s, WORK_STATE wst) { void (*cb) (const SSL *ssl, int type, int val) = NULL; #ifndef OPENSSL_NO_SCTP if (SSL_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(s))) { WORK_STATE ret; ret = dtls_wait_for_dry(s); if (ret != WORK_FINISHED_CONTINUE) return ret; } #endif /* clean a few things up */ ssl3_cleanup_key_block(s); if (!SSL_IS_DTLS(s)) { /* * We don't do this in DTLS because we may still need the init_buf * in case there are any unexpected retransmits */ BUF_MEM_free(s->init_buf); s->init_buf = NULL; } ssl_free_wbio_buffer(s); s->init_num = 0; if (!s->server || s->renegotiate == 2) { /* skipped if we just sent a HelloRequest */ s->renegotiate = 0; s->new_session = 0; if (s->server) { ssl_update_cache(s, SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; s->handshake_func = ossl_statem_accept; } else { ssl_update_cache(s, SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; s->handshake_func = ossl_statem_connect; s->ctx->stats.sess_connect_good++; } if (s->info_callback != NULL) cb = s->info_callback; else if (s->ctx->info_callback != NULL) cb = s->ctx->info_callback; if (cb != NULL) cb(s, SSL_CB_HANDSHAKE_DONE, 1); if (SSL_IS_DTLS(s)) { /* done with handshaking */ s->d1->handshake_read_seq = 0; s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; dtls1_clear_received_buffer(s); } } }
24,513
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.
Code: ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); v8::Context::Scope scope(v8Context); RefPtr<Frame> protect(m_frame); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); } Commit Message: Call didAccessInitialDocument when javascript: URLs are used. BUG=265221 TEST=See bug for repro. Review URL: https://chromiumcodereview.appspot.com/22572004 git-svn-id: svn://svn.chromium.org/blink/trunk@155790 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); RefPtr<Frame> protect(m_frame); if (m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) m_frame->loader()->didAccessInitialDocument(); v8::Context::Scope scope(v8Context); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); }
28,306
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.
Code: int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { H264Picture::Vector::const_reverse_iterator rit; int i; for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; } Commit Message: vaapi vda: Delete owned objects on worker thread in Cleanup() This CL adds a SEQUENCE_CHECKER to Vaapi*Accelerator classes, and posts the destruction of those objects to the appropriate thread on Cleanup(). Also makes {H264,VP8,VP9}Picture RefCountedThreadSafe, see miu@ comment in https://chromium-review.googlesource.com/c/chromium/src/+/794091#message-a64bed985cfaf8a19499a517bb110a7ce581dc0f TEST=play back VP9/VP8/H264 w/ simplechrome on soraka, Release build unstripped, let video play for a few seconds then navigate back; no crashes. Unittests as before: video_decode_accelerator_unittest --test_video_data=test-25fps.vp9:320:240:250:250:35:150:12 video_decode_accelerator_unittest --test_video_data=test-25fps.vp8:320:240:250:250:35:150:11 video_decode_accelerator_unittest --test_video_data=test-25fps.h264:320:240:250:258:35:150:1 Bug: 789160 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;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: I7d96aaf89c92bf46f00c8b8b36798e057a842ed2 Reviewed-on: https://chromium-review.googlesource.com/794091 Reviewed-by: Pawel Osciak <[email protected]> Commit-Queue: Miguel Casas <[email protected]> Cr-Commit-Position: refs/heads/master@{#523372} CWE ID: CWE-362
int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); H264Picture::Vector::const_reverse_iterator rit; int i; for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; }
13,440
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.
Code: jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op) { /* ensure image exists first */ if (page->image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined"); return 0; } /* grow the page to accomodate a new stripe if necessary */ if (page->striped) { int new_height = y + image->height + page->end_row; if (page->image->height < new_height) { jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height); jbig2_image_resize(ctx, page->image, page->image->width, new_height); } } jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op); return 0; } Commit Message: CWE ID: CWE-119
jbig2_page_add_result(Jbig2Ctx *ctx, Jbig2Page *page, Jbig2Image *image, int x, int y, Jbig2ComposeOp op) { /* ensure image exists first */ if (page->image == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "page info possibly missing, no image defined"); return 0; } /* grow the page to accomodate a new stripe if necessary */ if (page->striped) { uint32_t new_height = y + image->height + page->end_row; if (page->image->height < new_height) { jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "growing page buffer to %d rows " "to accomodate new stripe", new_height); jbig2_image_resize(ctx, page->image, page->image->width, new_height); } } jbig2_image_compose(ctx, page->image, image, x, y + page->end_row, op); return 0; }
8,884
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.
Code: static int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, showflag(key, 'I', KEY_FLAG_INSTANTIATED), showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), showflag(key, 'N', KEY_FLAG_NEGATIVE), showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; } 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 int proc_keys_show(struct seq_file *m, void *v) { struct rb_node *_p = v; struct key *key = rb_entry(_p, struct key, serial_node); struct timespec now; unsigned long timo; key_ref_t key_ref, skey_ref; char xbuf[16]; short state; int rc; struct keyring_search_context ctx = { .index_key.type = key->type, .index_key.description = key->description, .cred = m->file->f_cred, .match_data.cmp = lookup_user_key_possessed, .match_data.raw_data = key, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_NO_STATE_CHECK, }; key_ref = make_key_ref(key, 0); /* determine if the key is possessed by this process (a test we can * skip if the key does not indicate the possessor can view it */ if (key->perm & KEY_POS_VIEW) { skey_ref = search_my_process_keyrings(&ctx); if (!IS_ERR(skey_ref)) { key_ref_put(skey_ref); key_ref = make_key_ref(key, 1); } } /* check whether the current task is allowed to view the key */ rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW); if (rc < 0) return 0; now = current_kernel_time(); rcu_read_lock(); /* come up with a suitable timeout value */ if (key->expiry == 0) { memcpy(xbuf, "perm", 5); } else if (now.tv_sec >= key->expiry) { memcpy(xbuf, "expd", 5); } else { timo = key->expiry - now.tv_sec; if (timo < 60) sprintf(xbuf, "%lus", timo); else if (timo < 60*60) sprintf(xbuf, "%lum", timo / 60); else if (timo < 60*60*24) sprintf(xbuf, "%luh", timo / (60*60)); else if (timo < 60*60*24*7) sprintf(xbuf, "%lud", timo / (60*60*24)); else sprintf(xbuf, "%luw", timo / (60*60*24*7)); } state = key_read_state(key); #define showflag(KEY, LETTER, FLAG) \ (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", key->serial, state != KEY_IS_UNINSTANTIATED ? 'I' : '-', showflag(key, 'R', KEY_FLAG_REVOKED), showflag(key, 'D', KEY_FLAG_DEAD), showflag(key, 'Q', KEY_FLAG_IN_QUOTA), showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), state < 0 ? 'N' : '-', showflag(key, 'i', KEY_FLAG_INVALIDATED), refcount_read(&key->usage), xbuf, key->perm, from_kuid_munged(seq_user_ns(m), key->uid), from_kgid_munged(seq_user_ns(m), key->gid), key->type->name); #undef showflag if (key->type->describe) key->type->describe(key, m); seq_putc(m, '\n'); rcu_read_unlock(); return 0; }
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.
Code: InputImeEventRouter* InputImeEventRouterFactory::GetRouter(Profile* profile) { if (!profile) return nullptr; InputImeEventRouter* router = router_map_[profile]; if (!router) { router = new InputImeEventRouter(profile); router_map_[profile] = router; } return router; } Commit Message: Fix the regression caused by http://crrev.com/c/1288350. Bug: 900124,856135 Change-Id: Ie11ad406bd1ea383dc2a83cc8661076309154865 Reviewed-on: https://chromium-review.googlesource.com/c/1317010 Reviewed-by: Lan Wei <[email protected]> Commit-Queue: Shu Chen <[email protected]> Cr-Commit-Position: refs/heads/master@{#605282} CWE ID: CWE-416
InputImeEventRouter* InputImeEventRouterFactory::GetRouter(Profile* profile) { if (!profile) return nullptr; // The |router_map_| is keyed by the original profile. // Refers to the comments in |RemoveProfile| method for the reason. profile = profile->GetOriginalProfile(); InputImeEventRouter* router = router_map_[profile]; if (!router) { // The router must attach to the profile from which the extension can // receive events. If |profile| has an off-the-record profile, attach the // off-the-record profile. e.g. In guest mode, the extension is running with // the incognito profile instead of its original profile. router = new InputImeEventRouter(profile->HasOffTheRecordProfile() ? profile->GetOffTheRecordProfile() : profile); router_map_[profile] = router; } return router; }
9,797
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.
Code: void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path, const GetFileFromCacheParams& params, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GDataFileError error = util::GDataToGDataFileError(status); scoped_ptr<GDataEntry> fresh_entry; if (error == GDATA_FILE_OK) { scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (doc_entry.get()) { fresh_entry.reset( GDataEntry::FromDocumentEntry(NULL, doc_entry.get(), directory_service_.get())); } if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) { LOG(ERROR) << "Got invalid entry from server for " << params.resource_id; error = GDATA_FILE_ERROR_FAILED; } } if (error != GDATA_FILE_OK) { if (!params.get_file_callback.is_null()) { params.get_file_callback.Run(error, cache_file_path, params.mime_type, REGULAR_FILE); } return; } GURL content_url = fresh_entry->content_url(); int64 file_size = fresh_entry->file_info().size; DCHECK_EQ(params.resource_id, fresh_entry->resource_id()); scoped_ptr<GDataFile> fresh_entry_as_file( fresh_entry.release()->AsGDataFile()); directory_service_->RefreshFile(fresh_entry_as_file.Pass()); bool* has_enough_space = new bool(false); util::PostBlockingPoolSequencedTaskAndReply( FROM_HERE, blocking_task_runner_, base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor, base::Unretained(cache_), file_size, has_enough_space), base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace, ui_weak_ptr_, params, content_url, cache_file_path, base::Owned(has_enough_space))); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path, const GetFileFromCacheParams& params, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); GDataFileError error = util::GDataToGDataFileError(status); scoped_ptr<GDataEntry> fresh_entry; if (error == GDATA_FILE_OK) { scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (doc_entry.get()) { fresh_entry.reset(directory_service_->FromDocumentEntry(doc_entry.get())); } if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) { LOG(ERROR) << "Got invalid entry from server for " << params.resource_id; error = GDATA_FILE_ERROR_FAILED; } } if (error != GDATA_FILE_OK) { if (!params.get_file_callback.is_null()) { params.get_file_callback.Run(error, cache_file_path, params.mime_type, REGULAR_FILE); } return; } GURL content_url = fresh_entry->content_url(); int64 file_size = fresh_entry->file_info().size; DCHECK_EQ(params.resource_id, fresh_entry->resource_id()); scoped_ptr<GDataFile> fresh_entry_as_file( fresh_entry.release()->AsGDataFile()); directory_service_->RefreshFile(fresh_entry_as_file.Pass()); bool* has_enough_space = new bool(false); util::PostBlockingPoolSequencedTaskAndReply( FROM_HERE, blocking_task_runner_, base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor, base::Unretained(cache_), file_size, has_enough_space), base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace, ui_weak_ptr_, params, content_url, cache_file_path, base::Owned(has_enough_space))); }
7,326
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.
Code: struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata, const u8 *addr, gfp_t gfp) { struct ieee80211_local *local = sdata->local; struct sta_info *sta; struct timespec uptime; struct ieee80211_tx_latency_bin_ranges *tx_latency; int i; sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp); if (!sta) return NULL; rcu_read_lock(); tx_latency = rcu_dereference(local->tx_latency); /* init stations Tx latency statistics && TID bins */ if (tx_latency) { sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS * sizeof(struct ieee80211_tx_latency_stat), GFP_ATOMIC); if (!sta->tx_lat) { rcu_read_unlock(); goto free; } if (tx_latency->n_ranges) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* size of bins is size of the ranges +1 */ sta->tx_lat[i].bin_count = tx_latency->n_ranges + 1; sta->tx_lat[i].bins = kcalloc(sta->tx_lat[i].bin_count, sizeof(u32), GFP_ATOMIC); if (!sta->tx_lat[i].bins) { rcu_read_unlock(); goto free; } } } } rcu_read_unlock(); spin_lock_init(&sta->lock); INIT_WORK(&sta->drv_unblock_wk, sta_unblock); INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work); mutex_init(&sta->ampdu_mlme.mtx); #ifdef CONFIG_MAC80211_MESH if (ieee80211_vif_is_mesh(&sdata->vif) && !sdata->u.mesh.user_mpm) init_timer(&sta->plink_timer); sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE; #endif memcpy(sta->sta.addr, addr, ETH_ALEN); sta->local = local; sta->sdata = sdata; sta->last_rx = jiffies; sta->sta_state = IEEE80211_STA_NONE; do_posix_clock_monotonic_gettime(&uptime); sta->last_connected = uptime.tv_sec; ewma_init(&sta->avg_signal, 1024, 8); for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++) ewma_init(&sta->chain_signal_avg[i], 1024, 8); if (sta_prepare_rate_control(local, sta, gfp)) goto free; for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* * timer_to_tid must be initialized with identity mapping * to enable session_timer's data differentiation. See * sta_rx_agg_session_timer_expired for usage. */ sta->timer_to_tid[i] = i; } for (i = 0; i < IEEE80211_NUM_ACS; i++) { skb_queue_head_init(&sta->ps_tx_buf[i]); skb_queue_head_init(&sta->tx_filtered[i]); } for (i = 0; i < IEEE80211_NUM_TIDS; i++) sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX); sta->sta.smps_mode = IEEE80211_SMPS_OFF; if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { struct ieee80211_supported_band *sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >> IEEE80211_HT_CAP_SM_PS_SHIFT; /* * Assume that hostapd advertises our caps in the beacon and * this is the known_smps_mode for a station that just assciated */ switch (smps) { case WLAN_HT_SMPS_CONTROL_DISABLED: sta->known_smps_mode = IEEE80211_SMPS_OFF; break; case WLAN_HT_SMPS_CONTROL_STATIC: sta->known_smps_mode = IEEE80211_SMPS_STATIC; break; case WLAN_HT_SMPS_CONTROL_DYNAMIC: sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC; break; default: WARN_ON(1); } } sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr); return sta; free: if (sta->tx_lat) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) kfree(sta->tx_lat[i].bins); kfree(sta->tx_lat); } kfree(sta); return NULL; } Commit Message: mac80211: fix AP powersave TX vs. wakeup race There is a race between the TX path and the STA wakeup: while a station is sleeping, mac80211 buffers frames until it wakes up, then the frames are transmitted. However, the RX and TX path are concurrent, so the packet indicating wakeup can be processed while a packet is being transmitted. This can lead to a situation where the buffered frames list is emptied on the one side, while a frame is being added on the other side, as the station is still seen as sleeping in the TX path. As a result, the newly added frame will not be send anytime soon. It might be sent much later (and out of order) when the station goes to sleep and wakes up the next time. Additionally, it can lead to the crash below. Fix all this by synchronising both paths with a new lock. Both path are not fastpath since they handle PS situations. In a later patch we'll remove the extra skb queue locks to reduce locking overhead. BUG: unable to handle kernel NULL pointer dereference at 000000b0 IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211] *pde = 00000000 Oops: 0000 [#1] SMP DEBUG_PAGEALLOC EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1 EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211] EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000 ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0 DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068 CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0 DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000 DR6: ffff0ff0 DR7: 00000400 Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000) iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9 Stack: e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0 ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210 ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002 Call Trace: [<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211] [<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211] [<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211] [<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211] [<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211] [<c149ef70>] dev_hard_start_xmit+0x450/0x950 [<c14b9aa9>] sch_direct_xmit+0xa9/0x250 [<c14b9c9b>] __qdisc_run+0x4b/0x150 [<c149f732>] dev_queue_xmit+0x2c2/0xca0 Cc: [email protected] Reported-by: Yaara Rozenblum <[email protected]> Signed-off-by: Emmanuel Grumbach <[email protected]> Reviewed-by: Stanislaw Gruszka <[email protected]> [reword commit log, use a separate lock] Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-362
struct sta_info *sta_info_alloc(struct ieee80211_sub_if_data *sdata, const u8 *addr, gfp_t gfp) { struct ieee80211_local *local = sdata->local; struct sta_info *sta; struct timespec uptime; struct ieee80211_tx_latency_bin_ranges *tx_latency; int i; sta = kzalloc(sizeof(*sta) + local->hw.sta_data_size, gfp); if (!sta) return NULL; rcu_read_lock(); tx_latency = rcu_dereference(local->tx_latency); /* init stations Tx latency statistics && TID bins */ if (tx_latency) { sta->tx_lat = kzalloc(IEEE80211_NUM_TIDS * sizeof(struct ieee80211_tx_latency_stat), GFP_ATOMIC); if (!sta->tx_lat) { rcu_read_unlock(); goto free; } if (tx_latency->n_ranges) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* size of bins is size of the ranges +1 */ sta->tx_lat[i].bin_count = tx_latency->n_ranges + 1; sta->tx_lat[i].bins = kcalloc(sta->tx_lat[i].bin_count, sizeof(u32), GFP_ATOMIC); if (!sta->tx_lat[i].bins) { rcu_read_unlock(); goto free; } } } } rcu_read_unlock(); spin_lock_init(&sta->lock); spin_lock_init(&sta->ps_lock); INIT_WORK(&sta->drv_unblock_wk, sta_unblock); INIT_WORK(&sta->ampdu_mlme.work, ieee80211_ba_session_work); mutex_init(&sta->ampdu_mlme.mtx); #ifdef CONFIG_MAC80211_MESH if (ieee80211_vif_is_mesh(&sdata->vif) && !sdata->u.mesh.user_mpm) init_timer(&sta->plink_timer); sta->nonpeer_pm = NL80211_MESH_POWER_ACTIVE; #endif memcpy(sta->sta.addr, addr, ETH_ALEN); sta->local = local; sta->sdata = sdata; sta->last_rx = jiffies; sta->sta_state = IEEE80211_STA_NONE; do_posix_clock_monotonic_gettime(&uptime); sta->last_connected = uptime.tv_sec; ewma_init(&sta->avg_signal, 1024, 8); for (i = 0; i < ARRAY_SIZE(sta->chain_signal_avg); i++) ewma_init(&sta->chain_signal_avg[i], 1024, 8); if (sta_prepare_rate_control(local, sta, gfp)) goto free; for (i = 0; i < IEEE80211_NUM_TIDS; i++) { /* * timer_to_tid must be initialized with identity mapping * to enable session_timer's data differentiation. See * sta_rx_agg_session_timer_expired for usage. */ sta->timer_to_tid[i] = i; } for (i = 0; i < IEEE80211_NUM_ACS; i++) { skb_queue_head_init(&sta->ps_tx_buf[i]); skb_queue_head_init(&sta->tx_filtered[i]); } for (i = 0; i < IEEE80211_NUM_TIDS; i++) sta->last_seq_ctrl[i] = cpu_to_le16(USHRT_MAX); sta->sta.smps_mode = IEEE80211_SMPS_OFF; if (sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { struct ieee80211_supported_band *sband = local->hw.wiphy->bands[ieee80211_get_sdata_band(sdata)]; u8 smps = (sband->ht_cap.cap & IEEE80211_HT_CAP_SM_PS) >> IEEE80211_HT_CAP_SM_PS_SHIFT; /* * Assume that hostapd advertises our caps in the beacon and * this is the known_smps_mode for a station that just assciated */ switch (smps) { case WLAN_HT_SMPS_CONTROL_DISABLED: sta->known_smps_mode = IEEE80211_SMPS_OFF; break; case WLAN_HT_SMPS_CONTROL_STATIC: sta->known_smps_mode = IEEE80211_SMPS_STATIC; break; case WLAN_HT_SMPS_CONTROL_DYNAMIC: sta->known_smps_mode = IEEE80211_SMPS_DYNAMIC; break; default: WARN_ON(1); } } sta_dbg(sdata, "Allocated STA %pM\n", sta->sta.addr); return sta; free: if (sta->tx_lat) { for (i = 0; i < IEEE80211_NUM_TIDS; i++) kfree(sta->tx_lat[i].bins); kfree(sta->tx_lat); } kfree(sta); return NULL; }
8,600
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.
Code: ExtensionsGuestViewMessageFilter::MaybeCreateThrottle( NavigationHandle* handle) { DCHECK(content::MimeHandlerViewMode::UsesCrossProcessFrame()); if (!handle->GetParentFrame()) { return nullptr; } int32_t parent_process_id = handle->GetParentFrame()->GetProcess()->GetID(); auto& map = *GetProcessIdToFilterMap(); if (!base::ContainsKey(map, parent_process_id) || !map[parent_process_id]) { return nullptr; } for (auto& pair : map[parent_process_id]->frame_navigation_helpers_) { if (!pair.second->ShouldCancelAndIgnore(handle)) continue; return std::make_unique<CancelAndIgnoreNavigationForPluginFrameThrottle>( handle); } return nullptr; } 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
ExtensionsGuestViewMessageFilter::MaybeCreateThrottle(
3,412
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.
Code: static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < 256) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = 250 - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > 250) newIndex = 250; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-17
static int udf_translate_to_linux(uint8_t *newName, uint8_t *udfName, static int udf_translate_to_linux(uint8_t *newName, int newLen, uint8_t *udfName, int udfLen, uint8_t *fidName, int fidNameLen) { int index, newIndex = 0, needsCRC = 0; int extIndex = 0, newExtIndex = 0, hasExt = 0; unsigned short valueCRC; uint8_t curr; if (udfName[0] == '.' && (udfLen == 1 || (udfLen == 2 && udfName[1] == '.'))) { needsCRC = 1; newIndex = udfLen; memcpy(newName, udfName, udfLen); } else { for (index = 0; index < udfLen; index++) { curr = udfName[index]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (index + 1 < udfLen && (udfName[index + 1] == '/' || udfName[index + 1] == 0)) index++; } if (curr == EXT_MARK && (udfLen - index - 1) <= EXT_SIZE) { if (udfLen == index + 1) hasExt = 0; else { hasExt = 1; extIndex = index; newExtIndex = newIndex; } } if (newIndex < newLen) newName[newIndex++] = curr; else needsCRC = 1; } } if (needsCRC) { uint8_t ext[EXT_SIZE]; int localExtIndex = 0; if (hasExt) { int maxFilenameLen; for (index = 0; index < EXT_SIZE && extIndex + index + 1 < udfLen; index++) { curr = udfName[extIndex + index + 1]; if (curr == '/' || curr == 0) { needsCRC = 1; curr = ILLEGAL_CHAR_MARK; while (extIndex + index + 2 < udfLen && (index + 1 < EXT_SIZE && (udfName[extIndex + index + 2] == '/' || udfName[extIndex + index + 2] == 0))) index++; } ext[localExtIndex++] = curr; } maxFilenameLen = newLen - CRC_LEN - localExtIndex; if (newIndex > maxFilenameLen) newIndex = maxFilenameLen; else newIndex = newExtIndex; } else if (newIndex > newLen - CRC_LEN) newIndex = newLen - CRC_LEN; newName[newIndex++] = CRC_MARK; valueCRC = crc_itu_t(0, fidName, fidNameLen); newName[newIndex++] = hex_asc_upper_hi(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_lo(valueCRC >> 8); newName[newIndex++] = hex_asc_upper_hi(valueCRC); newName[newIndex++] = hex_asc_upper_lo(valueCRC); if (hasExt) { newName[newIndex++] = EXT_MARK; for (index = 0; index < localExtIndex; index++) newName[newIndex++] = ext[index]; } } return newIndex; }
1,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.
Code: void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FilePath& virtual_path, const FilePath& platform_path) { FilePath::StringType extension = virtual_path.Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (shareable_file && !ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); } Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files We also need to check the read permission and call GrantReadFile() for sandboxed files for CreateSnapshotFile(). BUG=162114 TEST=manual Review URL: https://codereview.chromium.org/11280231 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void FileAPIMessageFilter::RegisterFileAsBlob(const GURL& blob_url, const FileSystemURL& url, const FilePath& platform_path) { FilePath::StringType extension = url.path().Extension(); if (!extension.empty()) extension = extension.substr(1); // Strip leading ".". scoped_refptr<webkit_blob::ShareableFileReference> shareable_file = webkit_blob::ShareableFileReference::Get(platform_path); if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanReadFile( process_id_, platform_path)) { // If the underlying file system implementation is returning a new // (likely temporary) snapshot file or the file is for sandboxed // filesystems it's ok to grant permission here. // (Note that we have also already checked if the renderer has the // read permission for this file in OnCreateSnapshotFile.) DCHECK(shareable_file || fileapi::SandboxMountPointProvider::CanHandleType(url.type())); ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile( process_id_, platform_path); if (shareable_file) { // This will revoke all permissions for the file when the last ref // of the file is dropped (assuming it's ok). shareable_file->AddFinalReleaseCallback( base::Bind(&RevokeFilePermission, process_id_)); } } std::string mime_type; net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); BlobData::Item item; item.SetToFilePathRange(platform_path, 0, -1, base::Time()); BlobStorageController* controller = blob_storage_context_->controller(); controller->StartBuildingBlob(blob_url); controller->AppendBlobDataItem(blob_url, item); controller->FinishBuildingBlob(blob_url, mime_type); blob_urls_.insert(blob_url.spec()); }
1,399
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.
Code: void AutofillPopupBaseView::AddExtraInitParams( views::Widget::InitParams* params) { params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <[email protected]> Reviewed-by: Vasilii Sukhanov <[email protected]> Reviewed-by: Fabio Tirelo <[email protected]> Reviewed-by: Tommy Martino <[email protected]> Commit-Queue: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillPopupBaseView::AddExtraInitParams(
25,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.
Code: static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = compound_head(pgd_page(orig)); if (!page_cache_add_speculative(head, refs)) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = try_get_compound_head(pgd_page(orig), refs); if (!head) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; }
27,450
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.
Code: NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams(Browser* a_browser, TabContentsWrapper* a_target_contents) : target_contents(a_target_contents), source_contents(NULL), disposition(CURRENT_TAB), transition(content::PAGE_TRANSITION_LINK), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
13,402
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.
Code: static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; msg->msg_namelen = 0; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; }
2,071
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.
Code: bool Extension::InitFromValue(const DictionaryValue& source, int flags, std::string* error) { URLPattern::ParseOption parse_strictness = (flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT : URLPattern::PARSE_LENIENT); if (source.HasKey(keys::kPublicKey)) { std::string public_key_bytes; if (!source.GetString(keys::kPublicKey, &public_key_) || !ParsePEMKeyBytes(public_key_, &public_key_bytes) || !GenerateId(public_key_bytes, &id_)) { *error = errors::kInvalidKey; return false; } } else if (flags & REQUIRE_KEY) { *error = errors::kInvalidKey; return false; } else { id_ = Extension::GenerateIdForPath(path()); if (id_.empty()) { NOTREACHED() << "Could not create ID from path."; return false; } } manifest_value_.reset(source.DeepCopy()); extension_url_ = Extension::GetBaseURLFromExtensionId(id()); std::string version_str; if (!source.GetString(keys::kVersion, &version_str)) { *error = errors::kInvalidVersion; return false; } version_.reset(Version::GetVersionFromString(version_str)); if (!version_.get() || version_->components().size() > 4) { *error = errors::kInvalidVersion; return false; } string16 localized_name; if (!source.GetString(keys::kName, &localized_name)) { *error = errors::kInvalidName; return false; } base::i18n::AdjustStringForLocaleDirection(&localized_name); name_ = UTF16ToUTF8(localized_name); if (source.HasKey(keys::kDescription)) { if (!source.GetString(keys::kDescription, &description_)) { *error = errors::kInvalidDescription; return false; } } if (source.HasKey(keys::kHomepageURL)) { std::string tmp; if (!source.GetString(keys::kHomepageURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, ""); return false; } homepage_url_ = GURL(tmp); if (!homepage_url_.is_valid()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, tmp); return false; } } if (source.HasKey(keys::kUpdateURL)) { std::string tmp; if (!source.GetString(keys::kUpdateURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, ""); return false; } update_url_ = GURL(tmp); if (!update_url_.is_valid() || update_url_.has_ref()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, tmp); return false; } } if (source.HasKey(keys::kMinimumChromeVersion)) { std::string minimum_version_string; if (!source.GetString(keys::kMinimumChromeVersion, &minimum_version_string)) { *error = errors::kInvalidMinimumChromeVersion; return false; } scoped_ptr<Version> minimum_version( Version::GetVersionFromString(minimum_version_string)); if (!minimum_version.get()) { *error = errors::kInvalidMinimumChromeVersion; return false; } chrome::VersionInfo current_version_info; if (!current_version_info.is_valid()) { NOTREACHED(); return false; } scoped_ptr<Version> current_version( Version::GetVersionFromString(current_version_info.Version())); if (!current_version.get()) { DCHECK(false); return false; } if (current_version->CompareTo(*minimum_version) < 0) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kChromeVersionTooLow, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), minimum_version_string); return false; } } source.GetBoolean(keys::kConvertedFromUserScript, &converted_from_user_script_); if (source.HasKey(keys::kIcons)) { DictionaryValue* icons_value = NULL; if (!source.GetDictionary(keys::kIcons, &icons_value)) { *error = errors::kInvalidIcons; return false; } for (size_t i = 0; i < arraysize(kIconSizes); ++i) { std::string key = base::IntToString(kIconSizes[i]); if (icons_value->HasKey(key)) { std::string icon_path; if (!icons_value->GetString(key, &icon_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } if (!icon_path.empty() && icon_path[0] == '/') icon_path = icon_path.substr(1); if (icon_path.empty()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } icons_.Add(kIconSizes[i], icon_path); } } } is_theme_ = false; if (source.HasKey(keys::kTheme)) { if (ContainsNonThemeKeys(source)) { *error = errors::kThemesCannotContainExtensions; return false; } DictionaryValue* theme_value = NULL; if (!source.GetDictionary(keys::kTheme, &theme_value)) { *error = errors::kInvalidTheme; return false; } is_theme_ = true; DictionaryValue* images_value = NULL; if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) { for (DictionaryValue::key_iterator iter = images_value->begin_keys(); iter != images_value->end_keys(); ++iter) { std::string val; if (!images_value->GetString(*iter, &val)) { *error = errors::kInvalidThemeImages; return false; } } theme_images_.reset(images_value->DeepCopy()); } DictionaryValue* colors_value = NULL; if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) { for (DictionaryValue::key_iterator iter = colors_value->begin_keys(); iter != colors_value->end_keys(); ++iter) { ListValue* color_list = NULL; double alpha = 0.0; int color = 0; if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) || ((color_list->GetSize() != 3) && ((color_list->GetSize() != 4) || !color_list->GetDouble(3, &alpha))) || !color_list->GetInteger(0, &color) || !color_list->GetInteger(1, &color) || !color_list->GetInteger(2, &color)) { *error = errors::kInvalidThemeColors; return false; } } theme_colors_.reset(colors_value->DeepCopy()); } DictionaryValue* tints_value = NULL; if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) { for (DictionaryValue::key_iterator iter = tints_value->begin_keys(); iter != tints_value->end_keys(); ++iter) { ListValue* tint_list = NULL; double v = 0.0; if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) || tint_list->GetSize() != 3 || !tint_list->GetDouble(0, &v) || !tint_list->GetDouble(1, &v) || !tint_list->GetDouble(2, &v)) { *error = errors::kInvalidThemeTints; return false; } } theme_tints_.reset(tints_value->DeepCopy()); } DictionaryValue* display_properties_value = NULL; if (theme_value->GetDictionary(keys::kThemeDisplayProperties, &display_properties_value)) { theme_display_properties_.reset( display_properties_value->DeepCopy()); } return true; } if (source.HasKey(keys::kPlugins)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPlugins, &list_value)) { *error = errors::kInvalidPlugins; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* plugin_value = NULL; std::string path_str; bool is_public = false; if (!list_value->GetDictionary(i, &plugin_value)) { *error = errors::kInvalidPlugins; return false; } if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPath, base::IntToString(i)); return false; } if (plugin_value->HasKey(keys::kPluginsPublic)) { if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPublic, base::IntToString(i)); return false; } } #if !defined(OS_CHROMEOS) plugins_.push_back(PluginInfo()); plugins_.back().path = path().AppendASCII(path_str); plugins_.back().is_public = is_public; #endif } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kNaClModules)) { ListValue* list_value = NULL; if (!source.GetList(keys::kNaClModules, &list_value)) { *error = errors::kInvalidNaClModules; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* module_value = NULL; std::string path_str; std::string mime_type; if (!list_value->GetDictionary(i, &module_value)) { *error = errors::kInvalidNaClModules; return false; } if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesPath, base::IntToString(i)); return false; } if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesMIMEType, base::IntToString(i)); return false; } nacl_modules_.push_back(NaClModuleInfo()); nacl_modules_.back().url = GetResourceURL(path_str); nacl_modules_.back().mime_type = mime_type; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kToolstrips)) { ListValue* list_value = NULL; if (!source.GetList(keys::kToolstrips, &list_value)) { *error = errors::kInvalidToolstrips; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { GURL toolstrip; DictionaryValue* toolstrip_value = NULL; std::string toolstrip_path; if (list_value->GetString(i, &toolstrip_path)) { toolstrip = GetResourceURL(toolstrip_path); } else if (list_value->GetDictionary(i, &toolstrip_value)) { if (!toolstrip_value->GetString(keys::kToolstripPath, &toolstrip_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrip = GetResourceURL(toolstrip_path); } else { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrips_.push_back(toolstrip); } } if (source.HasKey(keys::kContentScripts)) { ListValue* list_value; if (!source.GetList(keys::kContentScripts, &list_value)) { *error = errors::kInvalidContentScriptsList; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* content_script = NULL; if (!list_value->GetDictionary(i, &content_script)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidContentScript, base::IntToString(i)); return false; } UserScript script; if (!LoadUserScriptHelper(content_script, i, flags, error, &script)) return false; // Failed to parse script context definition. script.set_extension_id(id()); if (converted_from_user_script_) { script.set_emulate_greasemonkey(true); script.set_match_all_frames(true); // Greasemonkey matches all frames. } content_scripts_.push_back(script); } } DictionaryValue* page_action_value = NULL; if (source.HasKey(keys::kPageActions)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPageActions, &list_value)) { *error = errors::kInvalidPageActionsList; return false; } size_t list_value_length = list_value->GetSize(); if (list_value_length == 0u) { } else if (list_value_length == 1u) { if (!list_value->GetDictionary(0, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } else { // list_value_length > 1u. *error = errors::kInvalidPageActionsListSize; return false; } } else if (source.HasKey(keys::kPageAction)) { if (!source.GetDictionary(keys::kPageAction, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } if (page_action_value) { page_action_.reset( LoadExtensionActionHelper(page_action_value, error)); if (!page_action_.get()) return false; // Failed to parse page action definition. } if (source.HasKey(keys::kBrowserAction)) { DictionaryValue* browser_action_value = NULL; if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) { *error = errors::kInvalidBrowserAction; return false; } browser_action_.reset( LoadExtensionActionHelper(browser_action_value, error)); if (!browser_action_.get()) return false; // Failed to parse browser action definition. } if (source.HasKey(keys::kFileBrowserHandlers)) { ListValue* file_browser_handlers_value = NULL; if (!source.GetList(keys::kFileBrowserHandlers, &file_browser_handlers_value)) { *error = errors::kInvalidFileBrowserHandler; return false; } file_browser_handlers_.reset( LoadFileBrowserHandlers(file_browser_handlers_value, error)); if (!file_browser_handlers_.get()) return false; // Failed to parse file browser actions definition. } if (!LoadIsApp(manifest_value_.get(), error) || !LoadExtent(manifest_value_.get(), keys::kWebURLs, &extent_, errors::kInvalidWebURLs, errors::kInvalidWebURL, parse_strictness, error) || !EnsureNotHybridApp(manifest_value_.get(), error) || !LoadLaunchURL(manifest_value_.get(), error) || !LoadLaunchContainer(manifest_value_.get(), error) || !LoadAppIsolation(manifest_value_.get(), error)) { return false; } if (source.HasKey(keys::kOptionsPage)) { std::string options_str; if (!source.GetString(keys::kOptionsPage, &options_str)) { *error = errors::kInvalidOptionsPage; return false; } if (is_hosted_app()) { GURL options_url(options_str); if (!options_url.is_valid() || !(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) { *error = errors::kInvalidOptionsPageInHostedApp; return false; } options_url_ = options_url; } else { GURL absolute(options_str); if (absolute.is_valid()) { *error = errors::kInvalidOptionsPageExpectUrlInPackage; return false; } options_url_ = GetResourceURL(options_str); if (!options_url_.is_valid()) { *error = errors::kInvalidOptionsPage; return false; } } } if (source.HasKey(keys::kPermissions)) { ListValue* permissions = NULL; if (!source.GetList(keys::kPermissions, &permissions)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissions, ""); return false; } for (size_t i = 0; i < permissions->GetSize(); ++i) { std::string permission_str; if (!permissions->GetString(i, &permission_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermission, base::IntToString(i)); return false; } if (!IsComponentOnlyPermission(permission_str) #ifndef NDEBUG && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposePrivateExtensionApi) #endif ) { continue; } if (permission_str == kOldUnlimitedStoragePermission) permission_str = kUnlimitedStoragePermission; if (web_extent().is_empty() || location() == Extension::COMPONENT) { if (IsAPIPermission(permission_str)) { if (permission_str == Extension::kExperimentalPermission && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && location() != Extension::COMPONENT) { *error = errors::kExperimentalFlagRequired; return false; } api_permissions_.insert(permission_str); continue; } } else { if (IsHostedAppPermission(permission_str)) { api_permissions_.insert(permission_str); continue; } } URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ? URLPattern::SCHEME_ALL : kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = pattern.Parse(permission_str, parse_strictness); if (parse_result == URLPattern::PARSE_SUCCESS) { if (!CanSpecifyHostPermission(pattern)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissionScheme, base::IntToString(i)); return false; } pattern.SetPath("/*"); if (pattern.MatchesScheme(chrome::kFileScheme) && !CanExecuteScriptEverywhere()) { wants_file_access_ = true; if (!(flags & ALLOW_FILE_ACCESS)) pattern.set_valid_schemes( pattern.valid_schemes() & ~URLPattern::SCHEME_FILE); } host_permissions_.push_back(pattern); } } } if (source.HasKey(keys::kBackground)) { std::string background_str; if (!source.GetString(keys::kBackground, &background_str)) { *error = errors::kInvalidBackground; return false; } if (is_hosted_app()) { if (api_permissions_.find(kBackgroundPermission) == api_permissions_.end()) { *error = errors::kBackgroundPermissionNeeded; return false; } GURL bg_page(background_str); if (!bg_page.is_valid()) { *error = errors::kInvalidBackgroundInHostedApp; return false; } if (!(bg_page.SchemeIs("https") || (CommandLine::ForCurrentProcess()->HasSwitch( switches::kAllowHTTPBackgroundPage) && bg_page.SchemeIs("http")))) { *error = errors::kInvalidBackgroundInHostedApp; return false; } background_url_ = bg_page; } else { background_url_ = GetResourceURL(background_str); } } if (source.HasKey(keys::kDefaultLocale)) { if (!source.GetString(keys::kDefaultLocale, &default_locale_) || !l10n_util::IsValidLocaleSyntax(default_locale_)) { *error = errors::kInvalidDefaultLocale; return false; } } if (source.HasKey(keys::kChromeURLOverrides)) { DictionaryValue* overrides = NULL; if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) { *error = errors::kInvalidChromeURLOverrides; return false; } for (DictionaryValue::key_iterator iter = overrides->begin_keys(); iter != overrides->end_keys(); ++iter) { std::string page = *iter; std::string val; if ((page != chrome::kChromeUINewTabHost && #if defined(TOUCH_UI) page != chrome::kChromeUIKeyboardHost && #endif #if defined(OS_CHROMEOS) page != chrome::kChromeUIActivationMessageHost && #endif page != chrome::kChromeUIBookmarksHost && page != chrome::kChromeUIHistoryHost) || !overrides->GetStringWithoutPathExpansion(*iter, &val)) { *error = errors::kInvalidChromeURLOverrides; return false; } chrome_url_overrides_[page] = GetResourceURL(val); } if (overrides->size() > 1) { *error = errors::kMultipleOverrides; return false; } } if (source.HasKey(keys::kOmnibox)) { if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) || omnibox_keyword_.empty()) { *error = errors::kInvalidOmniboxKeyword; return false; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kContentSecurityPolicy)) { std::string content_security_policy; if (!source.GetString(keys::kContentSecurityPolicy, &content_security_policy)) { *error = errors::kInvalidContentSecurityPolicy; return false; } const char kBadCSPCharacters[] = {'\r', '\n', '\0'}; if (content_security_policy.find_first_of(kBadCSPCharacters, 0, arraysize(kBadCSPCharacters)) != std::string::npos) { *error = errors::kInvalidContentSecurityPolicy; return false; } content_security_policy_ = content_security_policy; } if (source.HasKey(keys::kDevToolsPage)) { std::string devtools_str; if (!source.GetString(keys::kDevToolsPage, &devtools_str)) { *error = errors::kInvalidDevToolsPage; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kDevToolsExperimental; return false; } devtools_url_ = GetResourceURL(devtools_str); } if (source.HasKey(keys::kSidebar)) { DictionaryValue* sidebar_value = NULL; if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) { *error = errors::kInvalidSidebar; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kSidebarExperimental; return false; } sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error)); if (!sidebar_defaults_.get()) return false; // Failed to parse sidebar definition. } if (source.HasKey(keys::kTts)) { DictionaryValue* tts_dict = NULL; if (!source.GetDictionary(keys::kTts, &tts_dict)) { *error = errors::kInvalidTts; return false; } if (tts_dict->HasKey(keys::kTtsVoices)) { ListValue* tts_voices = NULL; if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) { *error = errors::kInvalidTtsVoices; return false; } for (size_t i = 0; i < tts_voices->GetSize(); i++) { DictionaryValue* one_tts_voice = NULL; if (!tts_voices->GetDictionary(i, &one_tts_voice)) { *error = errors::kInvalidTtsVoices; return false; } TtsVoice voice_data; if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) { if (!one_tts_voice->GetString( keys::kTtsVoicesVoiceName, &voice_data.voice_name)) { *error = errors::kInvalidTtsVoicesVoiceName; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) { if (!one_tts_voice->GetString( keys::kTtsVoicesLocale, &voice_data.locale) || !l10n_util::IsValidLocaleSyntax(voice_data.locale)) { *error = errors::kInvalidTtsVoicesLocale; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) { if (!one_tts_voice->GetString( keys::kTtsVoicesGender, &voice_data.gender) || (voice_data.gender != keys::kTtsGenderMale && voice_data.gender != keys::kTtsGenderFemale)) { *error = errors::kInvalidTtsVoicesGender; return false; } } tts_voices_.push_back(voice_data); } } } incognito_split_mode_ = is_app(); if (source.HasKey(keys::kIncognito)) { std::string value; if (!source.GetString(keys::kIncognito, &value)) { *error = errors::kInvalidIncognitoBehavior; return false; } if (value == values::kIncognitoSpanning) { incognito_split_mode_ = false; } else if (value == values::kIncognitoSplit) { incognito_split_mode_ = true; } else { *error = errors::kInvalidIncognitoBehavior; return false; } } if (HasMultipleUISurfaces()) { *error = errors::kOneUISurfaceOnly; return false; } InitEffectiveHostPermissions(); DCHECK(source.Equals(manifest_value_.get())); return true; } Commit Message: Prevent extensions from defining homepages with schemes other than valid web extents. BUG=84402 TEST=ExtensionManifestTest.ParseHomepageURLs Review URL: http://codereview.chromium.org/7089014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87722 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool Extension::InitFromValue(const DictionaryValue& source, int flags, std::string* error) { URLPattern::ParseOption parse_strictness = (flags & STRICT_ERROR_CHECKS ? URLPattern::PARSE_STRICT : URLPattern::PARSE_LENIENT); if (source.HasKey(keys::kPublicKey)) { std::string public_key_bytes; if (!source.GetString(keys::kPublicKey, &public_key_) || !ParsePEMKeyBytes(public_key_, &public_key_bytes) || !GenerateId(public_key_bytes, &id_)) { *error = errors::kInvalidKey; return false; } } else if (flags & REQUIRE_KEY) { *error = errors::kInvalidKey; return false; } else { id_ = Extension::GenerateIdForPath(path()); if (id_.empty()) { NOTREACHED() << "Could not create ID from path."; return false; } } manifest_value_.reset(source.DeepCopy()); extension_url_ = Extension::GetBaseURLFromExtensionId(id()); std::string version_str; if (!source.GetString(keys::kVersion, &version_str)) { *error = errors::kInvalidVersion; return false; } version_.reset(Version::GetVersionFromString(version_str)); if (!version_.get() || version_->components().size() > 4) { *error = errors::kInvalidVersion; return false; } string16 localized_name; if (!source.GetString(keys::kName, &localized_name)) { *error = errors::kInvalidName; return false; } base::i18n::AdjustStringForLocaleDirection(&localized_name); name_ = UTF16ToUTF8(localized_name); if (source.HasKey(keys::kDescription)) { if (!source.GetString(keys::kDescription, &description_)) { *error = errors::kInvalidDescription; return false; } } if (source.HasKey(keys::kHomepageURL)) { std::string tmp; if (!source.GetString(keys::kHomepageURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, ""); return false; } homepage_url_ = GURL(tmp); if (!homepage_url_.is_valid() || (!homepage_url_.SchemeIs("http") && !homepage_url_.SchemeIs("https"))) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidHomepageURL, tmp); return false; } } if (source.HasKey(keys::kUpdateURL)) { std::string tmp; if (!source.GetString(keys::kUpdateURL, &tmp)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, ""); return false; } update_url_ = GURL(tmp); if (!update_url_.is_valid() || update_url_.has_ref()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidUpdateURL, tmp); return false; } } if (source.HasKey(keys::kMinimumChromeVersion)) { std::string minimum_version_string; if (!source.GetString(keys::kMinimumChromeVersion, &minimum_version_string)) { *error = errors::kInvalidMinimumChromeVersion; return false; } scoped_ptr<Version> minimum_version( Version::GetVersionFromString(minimum_version_string)); if (!minimum_version.get()) { *error = errors::kInvalidMinimumChromeVersion; return false; } chrome::VersionInfo current_version_info; if (!current_version_info.is_valid()) { NOTREACHED(); return false; } scoped_ptr<Version> current_version( Version::GetVersionFromString(current_version_info.Version())); if (!current_version.get()) { DCHECK(false); return false; } if (current_version->CompareTo(*minimum_version) < 0) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kChromeVersionTooLow, l10n_util::GetStringUTF8(IDS_PRODUCT_NAME), minimum_version_string); return false; } } source.GetBoolean(keys::kConvertedFromUserScript, &converted_from_user_script_); if (source.HasKey(keys::kIcons)) { DictionaryValue* icons_value = NULL; if (!source.GetDictionary(keys::kIcons, &icons_value)) { *error = errors::kInvalidIcons; return false; } for (size_t i = 0; i < arraysize(kIconSizes); ++i) { std::string key = base::IntToString(kIconSizes[i]); if (icons_value->HasKey(key)) { std::string icon_path; if (!icons_value->GetString(key, &icon_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } if (!icon_path.empty() && icon_path[0] == '/') icon_path = icon_path.substr(1); if (icon_path.empty()) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidIconPath, key); return false; } icons_.Add(kIconSizes[i], icon_path); } } } is_theme_ = false; if (source.HasKey(keys::kTheme)) { if (ContainsNonThemeKeys(source)) { *error = errors::kThemesCannotContainExtensions; return false; } DictionaryValue* theme_value = NULL; if (!source.GetDictionary(keys::kTheme, &theme_value)) { *error = errors::kInvalidTheme; return false; } is_theme_ = true; DictionaryValue* images_value = NULL; if (theme_value->GetDictionary(keys::kThemeImages, &images_value)) { for (DictionaryValue::key_iterator iter = images_value->begin_keys(); iter != images_value->end_keys(); ++iter) { std::string val; if (!images_value->GetString(*iter, &val)) { *error = errors::kInvalidThemeImages; return false; } } theme_images_.reset(images_value->DeepCopy()); } DictionaryValue* colors_value = NULL; if (theme_value->GetDictionary(keys::kThemeColors, &colors_value)) { for (DictionaryValue::key_iterator iter = colors_value->begin_keys(); iter != colors_value->end_keys(); ++iter) { ListValue* color_list = NULL; double alpha = 0.0; int color = 0; if (!colors_value->GetListWithoutPathExpansion(*iter, &color_list) || ((color_list->GetSize() != 3) && ((color_list->GetSize() != 4) || !color_list->GetDouble(3, &alpha))) || !color_list->GetInteger(0, &color) || !color_list->GetInteger(1, &color) || !color_list->GetInteger(2, &color)) { *error = errors::kInvalidThemeColors; return false; } } theme_colors_.reset(colors_value->DeepCopy()); } DictionaryValue* tints_value = NULL; if (theme_value->GetDictionary(keys::kThemeTints, &tints_value)) { for (DictionaryValue::key_iterator iter = tints_value->begin_keys(); iter != tints_value->end_keys(); ++iter) { ListValue* tint_list = NULL; double v = 0.0; if (!tints_value->GetListWithoutPathExpansion(*iter, &tint_list) || tint_list->GetSize() != 3 || !tint_list->GetDouble(0, &v) || !tint_list->GetDouble(1, &v) || !tint_list->GetDouble(2, &v)) { *error = errors::kInvalidThemeTints; return false; } } theme_tints_.reset(tints_value->DeepCopy()); } DictionaryValue* display_properties_value = NULL; if (theme_value->GetDictionary(keys::kThemeDisplayProperties, &display_properties_value)) { theme_display_properties_.reset( display_properties_value->DeepCopy()); } return true; } if (source.HasKey(keys::kPlugins)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPlugins, &list_value)) { *error = errors::kInvalidPlugins; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* plugin_value = NULL; std::string path_str; bool is_public = false; if (!list_value->GetDictionary(i, &plugin_value)) { *error = errors::kInvalidPlugins; return false; } if (!plugin_value->GetString(keys::kPluginsPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPath, base::IntToString(i)); return false; } if (plugin_value->HasKey(keys::kPluginsPublic)) { if (!plugin_value->GetBoolean(keys::kPluginsPublic, &is_public)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPluginsPublic, base::IntToString(i)); return false; } } #if !defined(OS_CHROMEOS) plugins_.push_back(PluginInfo()); plugins_.back().path = path().AppendASCII(path_str); plugins_.back().is_public = is_public; #endif } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kNaClModules)) { ListValue* list_value = NULL; if (!source.GetList(keys::kNaClModules, &list_value)) { *error = errors::kInvalidNaClModules; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* module_value = NULL; std::string path_str; std::string mime_type; if (!list_value->GetDictionary(i, &module_value)) { *error = errors::kInvalidNaClModules; return false; } if (!module_value->GetString(keys::kNaClModulesPath, &path_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesPath, base::IntToString(i)); return false; } if (!module_value->GetString(keys::kNaClModulesMIMEType, &mime_type)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidNaClModulesMIMEType, base::IntToString(i)); return false; } nacl_modules_.push_back(NaClModuleInfo()); nacl_modules_.back().url = GetResourceURL(path_str); nacl_modules_.back().mime_type = mime_type; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kToolstrips)) { ListValue* list_value = NULL; if (!source.GetList(keys::kToolstrips, &list_value)) { *error = errors::kInvalidToolstrips; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { GURL toolstrip; DictionaryValue* toolstrip_value = NULL; std::string toolstrip_path; if (list_value->GetString(i, &toolstrip_path)) { toolstrip = GetResourceURL(toolstrip_path); } else if (list_value->GetDictionary(i, &toolstrip_value)) { if (!toolstrip_value->GetString(keys::kToolstripPath, &toolstrip_path)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrip = GetResourceURL(toolstrip_path); } else { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidToolstrip, base::IntToString(i)); return false; } toolstrips_.push_back(toolstrip); } } if (source.HasKey(keys::kContentScripts)) { ListValue* list_value; if (!source.GetList(keys::kContentScripts, &list_value)) { *error = errors::kInvalidContentScriptsList; return false; } for (size_t i = 0; i < list_value->GetSize(); ++i) { DictionaryValue* content_script = NULL; if (!list_value->GetDictionary(i, &content_script)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidContentScript, base::IntToString(i)); return false; } UserScript script; if (!LoadUserScriptHelper(content_script, i, flags, error, &script)) return false; // Failed to parse script context definition. script.set_extension_id(id()); if (converted_from_user_script_) { script.set_emulate_greasemonkey(true); script.set_match_all_frames(true); // Greasemonkey matches all frames. } content_scripts_.push_back(script); } } DictionaryValue* page_action_value = NULL; if (source.HasKey(keys::kPageActions)) { ListValue* list_value = NULL; if (!source.GetList(keys::kPageActions, &list_value)) { *error = errors::kInvalidPageActionsList; return false; } size_t list_value_length = list_value->GetSize(); if (list_value_length == 0u) { } else if (list_value_length == 1u) { if (!list_value->GetDictionary(0, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } else { // list_value_length > 1u. *error = errors::kInvalidPageActionsListSize; return false; } } else if (source.HasKey(keys::kPageAction)) { if (!source.GetDictionary(keys::kPageAction, &page_action_value)) { *error = errors::kInvalidPageAction; return false; } } if (page_action_value) { page_action_.reset( LoadExtensionActionHelper(page_action_value, error)); if (!page_action_.get()) return false; // Failed to parse page action definition. } if (source.HasKey(keys::kBrowserAction)) { DictionaryValue* browser_action_value = NULL; if (!source.GetDictionary(keys::kBrowserAction, &browser_action_value)) { *error = errors::kInvalidBrowserAction; return false; } browser_action_.reset( LoadExtensionActionHelper(browser_action_value, error)); if (!browser_action_.get()) return false; // Failed to parse browser action definition. } if (source.HasKey(keys::kFileBrowserHandlers)) { ListValue* file_browser_handlers_value = NULL; if (!source.GetList(keys::kFileBrowserHandlers, &file_browser_handlers_value)) { *error = errors::kInvalidFileBrowserHandler; return false; } file_browser_handlers_.reset( LoadFileBrowserHandlers(file_browser_handlers_value, error)); if (!file_browser_handlers_.get()) return false; // Failed to parse file browser actions definition. } if (!LoadIsApp(manifest_value_.get(), error) || !LoadExtent(manifest_value_.get(), keys::kWebURLs, &extent_, errors::kInvalidWebURLs, errors::kInvalidWebURL, parse_strictness, error) || !EnsureNotHybridApp(manifest_value_.get(), error) || !LoadLaunchURL(manifest_value_.get(), error) || !LoadLaunchContainer(manifest_value_.get(), error) || !LoadAppIsolation(manifest_value_.get(), error)) { return false; } if (source.HasKey(keys::kOptionsPage)) { std::string options_str; if (!source.GetString(keys::kOptionsPage, &options_str)) { *error = errors::kInvalidOptionsPage; return false; } if (is_hosted_app()) { GURL options_url(options_str); if (!options_url.is_valid() || !(options_url.SchemeIs("http") || options_url.SchemeIs("https"))) { *error = errors::kInvalidOptionsPageInHostedApp; return false; } options_url_ = options_url; } else { GURL absolute(options_str); if (absolute.is_valid()) { *error = errors::kInvalidOptionsPageExpectUrlInPackage; return false; } options_url_ = GetResourceURL(options_str); if (!options_url_.is_valid()) { *error = errors::kInvalidOptionsPage; return false; } } } if (source.HasKey(keys::kPermissions)) { ListValue* permissions = NULL; if (!source.GetList(keys::kPermissions, &permissions)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissions, ""); return false; } for (size_t i = 0; i < permissions->GetSize(); ++i) { std::string permission_str; if (!permissions->GetString(i, &permission_str)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermission, base::IntToString(i)); return false; } if (!IsComponentOnlyPermission(permission_str) #ifndef NDEBUG && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kExposePrivateExtensionApi) #endif ) { continue; } if (permission_str == kOldUnlimitedStoragePermission) permission_str = kUnlimitedStoragePermission; if (web_extent().is_empty() || location() == Extension::COMPONENT) { if (IsAPIPermission(permission_str)) { if (permission_str == Extension::kExperimentalPermission && !CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && location() != Extension::COMPONENT) { *error = errors::kExperimentalFlagRequired; return false; } api_permissions_.insert(permission_str); continue; } } else { if (IsHostedAppPermission(permission_str)) { api_permissions_.insert(permission_str); continue; } } URLPattern pattern = URLPattern(CanExecuteScriptEverywhere() ? URLPattern::SCHEME_ALL : kValidHostPermissionSchemes); URLPattern::ParseResult parse_result = pattern.Parse(permission_str, parse_strictness); if (parse_result == URLPattern::PARSE_SUCCESS) { if (!CanSpecifyHostPermission(pattern)) { *error = ExtensionErrorUtils::FormatErrorMessage( errors::kInvalidPermissionScheme, base::IntToString(i)); return false; } pattern.SetPath("/*"); if (pattern.MatchesScheme(chrome::kFileScheme) && !CanExecuteScriptEverywhere()) { wants_file_access_ = true; if (!(flags & ALLOW_FILE_ACCESS)) pattern.set_valid_schemes( pattern.valid_schemes() & ~URLPattern::SCHEME_FILE); } host_permissions_.push_back(pattern); } } } if (source.HasKey(keys::kBackground)) { std::string background_str; if (!source.GetString(keys::kBackground, &background_str)) { *error = errors::kInvalidBackground; return false; } if (is_hosted_app()) { if (api_permissions_.find(kBackgroundPermission) == api_permissions_.end()) { *error = errors::kBackgroundPermissionNeeded; return false; } GURL bg_page(background_str); if (!bg_page.is_valid()) { *error = errors::kInvalidBackgroundInHostedApp; return false; } if (!(bg_page.SchemeIs("https") || (CommandLine::ForCurrentProcess()->HasSwitch( switches::kAllowHTTPBackgroundPage) && bg_page.SchemeIs("http")))) { *error = errors::kInvalidBackgroundInHostedApp; return false; } background_url_ = bg_page; } else { background_url_ = GetResourceURL(background_str); } } if (source.HasKey(keys::kDefaultLocale)) { if (!source.GetString(keys::kDefaultLocale, &default_locale_) || !l10n_util::IsValidLocaleSyntax(default_locale_)) { *error = errors::kInvalidDefaultLocale; return false; } } if (source.HasKey(keys::kChromeURLOverrides)) { DictionaryValue* overrides = NULL; if (!source.GetDictionary(keys::kChromeURLOverrides, &overrides)) { *error = errors::kInvalidChromeURLOverrides; return false; } for (DictionaryValue::key_iterator iter = overrides->begin_keys(); iter != overrides->end_keys(); ++iter) { std::string page = *iter; std::string val; if ((page != chrome::kChromeUINewTabHost && #if defined(TOUCH_UI) page != chrome::kChromeUIKeyboardHost && #endif #if defined(OS_CHROMEOS) page != chrome::kChromeUIActivationMessageHost && #endif page != chrome::kChromeUIBookmarksHost && page != chrome::kChromeUIHistoryHost) || !overrides->GetStringWithoutPathExpansion(*iter, &val)) { *error = errors::kInvalidChromeURLOverrides; return false; } chrome_url_overrides_[page] = GetResourceURL(val); } if (overrides->size() > 1) { *error = errors::kMultipleOverrides; return false; } } if (source.HasKey(keys::kOmnibox)) { if (!source.GetString(keys::kOmniboxKeyword, &omnibox_keyword_) || omnibox_keyword_.empty()) { *error = errors::kInvalidOmniboxKeyword; return false; } } if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableExperimentalExtensionApis) && source.HasKey(keys::kContentSecurityPolicy)) { std::string content_security_policy; if (!source.GetString(keys::kContentSecurityPolicy, &content_security_policy)) { *error = errors::kInvalidContentSecurityPolicy; return false; } const char kBadCSPCharacters[] = {'\r', '\n', '\0'}; if (content_security_policy.find_first_of(kBadCSPCharacters, 0, arraysize(kBadCSPCharacters)) != std::string::npos) { *error = errors::kInvalidContentSecurityPolicy; return false; } content_security_policy_ = content_security_policy; } if (source.HasKey(keys::kDevToolsPage)) { std::string devtools_str; if (!source.GetString(keys::kDevToolsPage, &devtools_str)) { *error = errors::kInvalidDevToolsPage; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kDevToolsExperimental; return false; } devtools_url_ = GetResourceURL(devtools_str); } if (source.HasKey(keys::kSidebar)) { DictionaryValue* sidebar_value = NULL; if (!source.GetDictionary(keys::kSidebar, &sidebar_value)) { *error = errors::kInvalidSidebar; return false; } if (!HasApiPermission(Extension::kExperimentalPermission)) { *error = errors::kSidebarExperimental; return false; } sidebar_defaults_.reset(LoadExtensionSidebarDefaults(sidebar_value, error)); if (!sidebar_defaults_.get()) return false; // Failed to parse sidebar definition. } if (source.HasKey(keys::kTts)) { DictionaryValue* tts_dict = NULL; if (!source.GetDictionary(keys::kTts, &tts_dict)) { *error = errors::kInvalidTts; return false; } if (tts_dict->HasKey(keys::kTtsVoices)) { ListValue* tts_voices = NULL; if (!tts_dict->GetList(keys::kTtsVoices, &tts_voices)) { *error = errors::kInvalidTtsVoices; return false; } for (size_t i = 0; i < tts_voices->GetSize(); i++) { DictionaryValue* one_tts_voice = NULL; if (!tts_voices->GetDictionary(i, &one_tts_voice)) { *error = errors::kInvalidTtsVoices; return false; } TtsVoice voice_data; if (one_tts_voice->HasKey(keys::kTtsVoicesVoiceName)) { if (!one_tts_voice->GetString( keys::kTtsVoicesVoiceName, &voice_data.voice_name)) { *error = errors::kInvalidTtsVoicesVoiceName; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesLocale)) { if (!one_tts_voice->GetString( keys::kTtsVoicesLocale, &voice_data.locale) || !l10n_util::IsValidLocaleSyntax(voice_data.locale)) { *error = errors::kInvalidTtsVoicesLocale; return false; } } if (one_tts_voice->HasKey(keys::kTtsVoicesGender)) { if (!one_tts_voice->GetString( keys::kTtsVoicesGender, &voice_data.gender) || (voice_data.gender != keys::kTtsGenderMale && voice_data.gender != keys::kTtsGenderFemale)) { *error = errors::kInvalidTtsVoicesGender; return false; } } tts_voices_.push_back(voice_data); } } } incognito_split_mode_ = is_app(); if (source.HasKey(keys::kIncognito)) { std::string value; if (!source.GetString(keys::kIncognito, &value)) { *error = errors::kInvalidIncognitoBehavior; return false; } if (value == values::kIncognitoSpanning) { incognito_split_mode_ = false; } else if (value == values::kIncognitoSplit) { incognito_split_mode_ = true; } else { *error = errors::kInvalidIncognitoBehavior; return false; } } if (HasMultipleUISurfaces()) { *error = errors::kOneUISurfaceOnly; return false; } InitEffectiveHostPermissions(); DCHECK(source.Equals(manifest_value_.get())); return true; }
15,491
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.
Code: fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree _U_) { fp_info *fpi; guint8 tfi, c_t; int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off; gboolean is_control_frame; umts_mac_info *macinf; rlc_info *rlcinf; guint8 fake_lchid=0; gint *cur_val=NULL; fpi = wmem_new0(wmem_file_scope(), fp_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi); fpi->iface_type = p_conv_data->iface_type; fpi->division = p_conv_data->division; fpi->release = 7; /* Set values greater then the checks performed */ fpi->release_year = 2006; fpi->release_month = 12; fpi->channel = p_conv_data->channel; fpi->dch_crc_present = p_conv_data->dch_crc_present; /*fpi->paging_indications;*/ fpi->link_type = FP_Link_Ethernet; #if 0 /*Only do this the first run, signals that we need to reset the RLC fragtable*/ if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) { fpi->reset_frag = p_conv_data->reset_frag; p_conv_data->reset_frag = FALSE; } #endif /* remember 'lower' UDP layer port information so we can later * differentiate 'lower' UDP layer from 'user data' UDP layer */ fpi->srcport = pinfo->srcport; fpi->destport = pinfo->destport; fpi->com_context_id = p_conv_data->com_context_id; if (pinfo->link_dir == P2P_DIR_UL) { fpi->is_uplink = TRUE; } else { fpi->is_uplink = FALSE; } is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; switch (fpi->channel) { case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */ fpi->hsdsch_entity = p_conv_data->hsdsch_entity; macinf = wmem_new0(wmem_file_scope(), umts_mac_info); fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id; macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/ macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id; /*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id]; if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) { for (i=0; i<MAX_NUM_HSDHSCH_MACDFLOW; i++) { /*Figure out if this channel is multiplexed (signaled from RRC)*/ if ((cur_val=(gint *)g_tree_lookup(hsdsch_muxed_flows, GINT_TO_POINTER((gint)p_conv_data->hrnti))) != NULL) { j = 1 << i; fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val; } else { fpi->hsdhsch_macfdlow_is_mux[i] = FALSE; } } } /* Make configurable ?(available in NBAP?) */ /* urnti[MAX_RLC_CHANS] */ /* switch (p_conv_data->rlc_mode) { case FP_RLC_TM: rlcinf->mode[0] = RLC_TM; break; case FP_RLC_UM: rlcinf->mode[0] = RLC_UM; break; case FP_RLC_AM: rlcinf->mode[0] = RLC_AM; break; case FP_RLC_MODE_UNKNOWN: default: rlcinf->mode[0] = RLC_UNKNOWN_MODE; break; }*/ /* rbid[MAX_RLC_CHANS] */ /* For RLC re-assembly to work we urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_EDCH: /*Most configuration is now done in the actual dissecting function*/ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); fpi->no_ddi_entries = p_conv_data->no_ddi_entries; for (i=0; i<fpi->no_ddi_entries; i++) { fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/ fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/ fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/ /*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/ /* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ } fpi->edch_type = p_conv_data->edch_type; /* macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->content[0] = MAC_CONTENT_PS_DTCH;*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* For RLC re-assembly to work we need a urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; /* rlcinf->mode[0] = RLC_AM;*/ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_PCH: fpi->paging_indications = p_conv_data->paging_indications; fpi->num_chans = p_conv_data->num_dch_in_flow; /* Set offset to point to first TFI */ if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to TFI */ offset = 3; break; case CHANNEL_DCH: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); offset = 2; /*To correctly read the tfi*/ fakes = 5; /* Reset fake counter. */ for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/ /*Iterate over the transport blocks*/ /*tfi = tvb_get_guint8(tvb, offset);*/ /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ tfi = tvb_get_bits8(tvb, 3+offset*8, 5); /*Figure out the number of tbs and size*/ num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi]; tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; /*TODO: This stuff has to be reworked!*/ /*Generates a fake logical channel id for non multiplexed channel*/ if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) ) { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); } tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/ /*Set configuration for individual blocks*/ for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) { /*Set transport channel id (useful for debugging)*/ macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan]; /*Transport Channel m31 and 24 might be multiplexed!*/ if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) { /****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/ /*If Trchid == 31 and only on TB, we have no multiplexing*/ if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ macinf->lchid[j+chan] = 1; macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/ } /*Indicate we don't have multiplexing.*/ else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*g_warning("settin this for %d", pinfo->num);*/ macinf->lchid[j+chan] = fake_lchid; macinf->fake_chid[j+chan] = TRUE; macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/ } /*We have multiplexing*/ else { macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /* Peek at C/T, different RLC params for different logical channels */ /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/ macinf->lchid[j+chan] = c_t+1; macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/ } } else { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/ macinf->content[j+chan] = lchId_type_table[fake_lchid]; rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid]; /*Generate virtual logical channel id*/ /************************/ /*TODO: Once proper lchid is always set, this has to be removed*/ macinf->fake_chid[j+chan] = TRUE; macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/ /************************/ } /*** Set rlc info ***/ rlcinf->urnti[j+chan] = p_conv_data->com_context_id; rlcinf->li_size[j+chan] = RLC_LI_7BITS; #if 0 /*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/ if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) { rlcinf->ciphered[j+chan] = TRUE; } else { rlcinf->ciphered[j+chan] = FALSE; } #endif rlcinf->ciphered[j+chan] = FALSE; rlcinf->deciphered[j+chan] = FALSE; rlcinf->rbid[j+chan] = macinf->lchid[j+chan]; /*Step over this TB and it's C/T flag.*/ tb_bit_off += tb_size+4; } offset++; } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; break; case CHANNEL_FACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* Set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->ctmux[0] = 1; macinf->content[0] = MAC_CONTENT_DCCH; p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* Set RLC data */ rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /* Make configurable ?(avaliable in NBAP?) */ /* For RLC re-assembly to work we need to fake urnti */ rlcinf->urnti[0] = fpi->channel; rlcinf->mode[0] = RLC_AM; /* rbid[MAX_RLC_CHANS] */ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_RACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); for ( chan = 0; chan < fpi->num_chans; chan++ ) { macinf->ctmux[chan] = 1; macinf->content[chan] = MAC_CONTENT_DCCH; rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/ } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_HSDSCH_COMMON: rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; default: expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown); return NULL; } /* Peek at the packet as the per packet info seems not to take the tfi into account */ for (i=0; i<fpi->num_chans; i++) { tfi = tvb_get_guint8(tvb, offset); /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ /*tfi = tvb_get_bits8(tvb, offset*8, 5);*/ if (pinfo->link_dir == P2P_DIR_UL) { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi]; } else { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi]; } offset++; } return fpi; } Commit Message: UMTS_FP: fix handling reserved C/T value The spec puts the reserved value at 0xf but our internal table has 'unknown' at 0; since all the other values seem to be offset-by-one, just take the modulus 0xf to avoid running off the end of the table. Bug: 12191 Change-Id: I83c8fb66797bbdee52a2246fb1eea6e37cbc7eb0 Reviewed-on: https://code.wireshark.org/review/15722 Reviewed-by: Evan Huus <[email protected]> Petri-Dish: Evan Huus <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Michael Mann <[email protected]> CWE ID: CWE-20
fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree _U_) { fp_info *fpi; guint8 tfi, c_t; int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off; gboolean is_control_frame; umts_mac_info *macinf; rlc_info *rlcinf; guint8 fake_lchid=0; gint *cur_val=NULL; fpi = wmem_new0(wmem_file_scope(), fp_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi); fpi->iface_type = p_conv_data->iface_type; fpi->division = p_conv_data->division; fpi->release = 7; /* Set values greater then the checks performed */ fpi->release_year = 2006; fpi->release_month = 12; fpi->channel = p_conv_data->channel; fpi->dch_crc_present = p_conv_data->dch_crc_present; /*fpi->paging_indications;*/ fpi->link_type = FP_Link_Ethernet; #if 0 /*Only do this the first run, signals that we need to reset the RLC fragtable*/ if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) { fpi->reset_frag = p_conv_data->reset_frag; p_conv_data->reset_frag = FALSE; } #endif /* remember 'lower' UDP layer port information so we can later * differentiate 'lower' UDP layer from 'user data' UDP layer */ fpi->srcport = pinfo->srcport; fpi->destport = pinfo->destport; fpi->com_context_id = p_conv_data->com_context_id; if (pinfo->link_dir == P2P_DIR_UL) { fpi->is_uplink = TRUE; } else { fpi->is_uplink = FALSE; } is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; switch (fpi->channel) { case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */ fpi->hsdsch_entity = p_conv_data->hsdsch_entity; macinf = wmem_new0(wmem_file_scope(), umts_mac_info); fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id; macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/ macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id; /*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id]; if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) { for (i=0; i<MAX_NUM_HSDHSCH_MACDFLOW; i++) { /*Figure out if this channel is multiplexed (signaled from RRC)*/ if ((cur_val=(gint *)g_tree_lookup(hsdsch_muxed_flows, GINT_TO_POINTER((gint)p_conv_data->hrnti))) != NULL) { j = 1 << i; fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val; } else { fpi->hsdhsch_macfdlow_is_mux[i] = FALSE; } } } /* Make configurable ?(available in NBAP?) */ /* urnti[MAX_RLC_CHANS] */ /* switch (p_conv_data->rlc_mode) { case FP_RLC_TM: rlcinf->mode[0] = RLC_TM; break; case FP_RLC_UM: rlcinf->mode[0] = RLC_UM; break; case FP_RLC_AM: rlcinf->mode[0] = RLC_AM; break; case FP_RLC_MODE_UNKNOWN: default: rlcinf->mode[0] = RLC_UNKNOWN_MODE; break; }*/ /* rbid[MAX_RLC_CHANS] */ /* For RLC re-assembly to work we urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_EDCH: /*Most configuration is now done in the actual dissecting function*/ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); fpi->no_ddi_entries = p_conv_data->no_ddi_entries; for (i=0; i<fpi->no_ddi_entries; i++) { fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/ fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/ fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/ /*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/ /* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ } fpi->edch_type = p_conv_data->edch_type; /* macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->content[0] = MAC_CONTENT_PS_DTCH;*/ p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* For RLC re-assembly to work we need a urnti signaled from NBAP */ rlcinf->urnti[0] = fpi->com_context_id; /* rlcinf->mode[0] = RLC_AM;*/ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); return fpi; case CHANNEL_PCH: fpi->paging_indications = p_conv_data->paging_indications; fpi->num_chans = p_conv_data->num_dch_in_flow; /* Set offset to point to first TFI */ if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to TFI */ offset = 3; break; case CHANNEL_DCH: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); offset = 2; /*To correctly read the tfi*/ fakes = 5; /* Reset fake counter. */ for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/ /*Iterate over the transport blocks*/ /*tfi = tvb_get_guint8(tvb, offset);*/ /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ tfi = tvb_get_bits8(tvb, 3+offset*8, 5); /*Figure out the number of tbs and size*/ num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi]; tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; /*TODO: This stuff has to be reworked!*/ /*Generates a fake logical channel id for non multiplexed channel*/ if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) ) { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); } tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/ /*Set configuration for individual blocks*/ for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) { /*Set transport channel id (useful for debugging)*/ macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan]; /*Transport Channel m31 and 24 might be multiplexed!*/ if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) { /****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/ /*If Trchid == 31 and only on TB, we have no multiplexing*/ if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ macinf->lchid[j+chan] = 1; macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/ } /*Indicate we don't have multiplexing.*/ else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) { macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*g_warning("settin this for %d", pinfo->num);*/ macinf->lchid[j+chan] = fake_lchid; macinf->fake_chid[j+chan] = TRUE; macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/ } /*We have multiplexing*/ else { macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /* Peek at C/T, different RLC params for different logical channels */ /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/ macinf->lchid[j+chan] = c_t; macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/ } } else { fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ /*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/ macinf->content[j+chan] = lchId_type_table[fake_lchid]; rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid]; /*Generate virtual logical channel id*/ /************************/ /*TODO: Once proper lchid is always set, this has to be removed*/ macinf->fake_chid[j+chan] = TRUE; macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/ /************************/ } /*** Set rlc info ***/ rlcinf->urnti[j+chan] = p_conv_data->com_context_id; rlcinf->li_size[j+chan] = RLC_LI_7BITS; #if 0 /*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/ if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) { rlcinf->ciphered[j+chan] = TRUE; } else { rlcinf->ciphered[j+chan] = FALSE; } #endif rlcinf->ciphered[j+chan] = FALSE; rlcinf->deciphered[j+chan] = FALSE; rlcinf->rbid[j+chan] = macinf->lchid[j+chan]; /*Step over this TB and it's C/T flag.*/ tb_bit_off += tb_size+4; } offset++; } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; break; case CHANNEL_FACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* Set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); macinf->ctmux[0] = 1; macinf->content[0] = MAC_CONTENT_DCCH; p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); /* Set RLC data */ rlcinf = wmem_new0(wmem_file_scope(), rlc_info); /* Make configurable ?(avaliable in NBAP?) */ /* For RLC re-assembly to work we need to fake urnti */ rlcinf->urnti[0] = fpi->channel; rlcinf->mode[0] = RLC_AM; /* rbid[MAX_RLC_CHANS] */ rlcinf->li_size[0] = RLC_LI_7BITS; rlcinf->ciphered[0] = FALSE; rlcinf->deciphered[0] = FALSE; p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_RACH_FDD: fpi->num_chans = p_conv_data->num_dch_in_flow; if (is_control_frame) { /* control frame, we're done */ return fpi; } /* Set offset to point to first TFI * the Number of TFI's = number of DCH's in the flow */ offset = 2; /* set MAC data */ macinf = wmem_new0(wmem_file_scope(), umts_mac_info); rlcinf = wmem_new0(wmem_file_scope(), rlc_info); for ( chan = 0; chan < fpi->num_chans; chan++ ) { macinf->ctmux[chan] = 1; macinf->content[chan] = MAC_CONTENT_DCCH; rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/ } p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; case CHANNEL_HSDSCH_COMMON: rlcinf = wmem_new0(wmem_file_scope(), rlc_info); macinf = wmem_new0(wmem_file_scope(), umts_mac_info); p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); break; default: expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown); return NULL; } /* Peek at the packet as the per packet info seems not to take the tfi into account */ for (i=0; i<fpi->num_chans; i++) { tfi = tvb_get_guint8(tvb, offset); /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ /*tfi = tvb_get_bits8(tvb, offset*8, 5);*/ if (pinfo->link_dir == P2P_DIR_UL) { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi]; } else { fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi]; } offset++; } return fpi; }
12,982
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.
Code: void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset) { if (!box().isMarquee()) { if (m_scrollDimensionsDirty) computeScrollDimensions(); } if (scrollOffset() == toIntSize(newScrollOffset)) return; setScrollOffset(toIntSize(newScrollOffset)); LocalFrame* frame = box().frame(); ASSERT(frame); RefPtr<FrameView> frameView = box().frameView(); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScrollLayer", "data", InspectorScrollLayerEvent::data(&box())); InspectorInstrumentation::willScrollLayer(&box()); const RenderLayerModelObject* paintInvalidationContainer = box().containerForPaintInvalidation(); if (!frameView->isInPerformLayout()) { layer()->clipper().clearClipRectsIncludingDescendants(); box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(paintInvalidationContainer)); frameView->updateAnnotatedRegions(); frameView->updateWidgetPositions(); RELEASE_ASSERT(frameView->renderView()); updateCompositingLayersAfterScroll(); } frame->selection().setCaretRectNeedsUpdate(); FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->renderer()->previousPaintInvalidationRect()); quadForFakeMouseMoveEvent = paintInvalidationContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent); frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent); bool requiresPaintInvalidation = true; if (!box().isMarquee() && box().view()->compositor()->inCompositingMode()) { DisableCompositingQueryAsserts disabler; bool onlyScrolledCompositedLayers = scrollsOverflow() && !layer()->hasVisibleNonLayerContent() && !layer()->hasNonCompositedChild() && !layer()->hasBlockSelectionGapBounds() && box().style()->backgroundLayers().attachment() != LocalBackgroundAttachment; if (usesCompositedScrolling() || onlyScrolledCompositedLayers) requiresPaintInvalidation = false; } if (requiresPaintInvalidation) { if (box().frameView()->isInPerformLayout()) box().setShouldDoFullPaintInvalidation(true); else box().invalidatePaintUsingContainer(paintInvalidationContainer, layer()->renderer()->previousPaintInvalidationRect(), InvalidationScroll); } if (box().node()) box().node()->document().enqueueScrollEventForNode(box().node()); if (AXObjectCache* cache = box().document().existingAXObjectCache()) cache->handleScrollPositionChanged(&box()); InspectorInstrumentation::didScrollLayer(&box()); } Commit Message: Defer call to updateWidgetPositions() outside of RenderLayerScrollableArea. updateWidgetPositions() can destroy the render tree, so it should never be called from inside RenderLayerScrollableArea. Leaving it there allows for the potential of use-after-free bugs. BUG=402407 [email protected] Review URL: https://codereview.chromium.org/490473003 git-svn-id: svn://svn.chromium.org/blink/trunk@180681 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416
void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset) { if (!box().isMarquee()) { if (m_scrollDimensionsDirty) computeScrollDimensions(); } if (scrollOffset() == toIntSize(newScrollOffset)) return; setScrollOffset(toIntSize(newScrollOffset)); LocalFrame* frame = box().frame(); ASSERT(frame); RefPtr<FrameView> frameView = box().frameView(); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "ScrollLayer", "data", InspectorScrollLayerEvent::data(&box())); InspectorInstrumentation::willScrollLayer(&box()); const RenderLayerModelObject* paintInvalidationContainer = box().containerForPaintInvalidation(); if (!frameView->isInPerformLayout()) { layer()->clipper().clearClipRectsIncludingDescendants(); box().setPreviousPaintInvalidationRect(box().boundsRectForPaintInvalidation(paintInvalidationContainer)); frameView->updateAnnotatedRegions(); frameView->setNeedsUpdateWidgetPositions(); updateCompositingLayersAfterScroll(); } frame->selection().setCaretRectNeedsUpdate(); FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->renderer()->previousPaintInvalidationRect()); quadForFakeMouseMoveEvent = paintInvalidationContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent); frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent); bool requiresPaintInvalidation = true; if (!box().isMarquee() && box().view()->compositor()->inCompositingMode()) { DisableCompositingQueryAsserts disabler; bool onlyScrolledCompositedLayers = scrollsOverflow() && !layer()->hasVisibleNonLayerContent() && !layer()->hasNonCompositedChild() && !layer()->hasBlockSelectionGapBounds() && box().style()->backgroundLayers().attachment() != LocalBackgroundAttachment; if (usesCompositedScrolling() || onlyScrolledCompositedLayers) requiresPaintInvalidation = false; } if (requiresPaintInvalidation) { if (box().frameView()->isInPerformLayout()) box().setShouldDoFullPaintInvalidation(true); else box().invalidatePaintUsingContainer(paintInvalidationContainer, layer()->renderer()->previousPaintInvalidationRect(), InvalidationScroll); } if (box().node()) box().node()->document().enqueueScrollEventForNode(box().node()); if (AXObjectCache* cache = box().document().existingAXObjectCache()) cache->handleScrollPositionChanged(&box()); InspectorInstrumentation::didScrollLayer(&box()); }
21,001
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.
Code: void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { LOG(INFO) << "IBus connection is ready."; } } 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
void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { VLOG(1) << "IBus connection is ready."; } }
22,282
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.
Code: static int usb_enumerate_device_otg(struct usb_device *udev) { int err = 0; #ifdef CONFIG_USB_OTG /* * OTG-aware devices on OTG-capable root hubs may be able to use SRP, * to wake us after we've powered off VBUS; and HNP, switching roles * "host" to "peripheral". The OTG descriptor helps figure this out. */ if (!udev->bus->is_b_host && udev->config && udev->parent == udev->bus->root_hub) { struct usb_otg_descriptor *desc = NULL; struct usb_bus *bus = udev->bus; unsigned port1 = udev->portnum; /* descriptor may appear anywhere in config */ err = __usb_get_extra_descriptor(udev->rawdescriptors[0], le16_to_cpu(udev->config[0].desc.wTotalLength), USB_DT_OTG, (void **) &desc); if (err || !(desc->bmAttributes & USB_OTG_HNP)) return 0; dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n", (port1 == bus->otg_port) ? "" : "non-"); /* enable HNP before suspend, it's simpler */ if (port1 == bus->otg_port) { bus->b_hnp_enable = 1; err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_B_HNP_ENABLE, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) { /* * OTG MESSAGE: report errors here, * customize to match your product. */ dev_err(&udev->dev, "can't set HNP mode: %d\n", err); bus->b_hnp_enable = 0; } } else if (desc->bLength == sizeof (struct usb_otg_descriptor)) { /* Set a_alt_hnp_support for legacy otg device */ err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_A_ALT_HNP_SUPPORT, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) dev_err(&udev->dev, "set a_alt_hnp_support failed: %d\n", err); } } #endif return err; } Commit Message: USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400
static int usb_enumerate_device_otg(struct usb_device *udev) { int err = 0; #ifdef CONFIG_USB_OTG /* * OTG-aware devices on OTG-capable root hubs may be able to use SRP, * to wake us after we've powered off VBUS; and HNP, switching roles * "host" to "peripheral". The OTG descriptor helps figure this out. */ if (!udev->bus->is_b_host && udev->config && udev->parent == udev->bus->root_hub) { struct usb_otg_descriptor *desc = NULL; struct usb_bus *bus = udev->bus; unsigned port1 = udev->portnum; /* descriptor may appear anywhere in config */ err = __usb_get_extra_descriptor(udev->rawdescriptors[0], le16_to_cpu(udev->config[0].desc.wTotalLength), USB_DT_OTG, (void **) &desc, sizeof(*desc)); if (err || !(desc->bmAttributes & USB_OTG_HNP)) return 0; dev_info(&udev->dev, "Dual-Role OTG device on %sHNP port\n", (port1 == bus->otg_port) ? "" : "non-"); /* enable HNP before suspend, it's simpler */ if (port1 == bus->otg_port) { bus->b_hnp_enable = 1; err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_B_HNP_ENABLE, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) { /* * OTG MESSAGE: report errors here, * customize to match your product. */ dev_err(&udev->dev, "can't set HNP mode: %d\n", err); bus->b_hnp_enable = 0; } } else if (desc->bLength == sizeof (struct usb_otg_descriptor)) { /* Set a_alt_hnp_support for legacy otg device */ err = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), USB_REQ_SET_FEATURE, 0, USB_DEVICE_A_ALT_HNP_SUPPORT, 0, NULL, 0, USB_CTRL_SET_TIMEOUT); if (err < 0) dev_err(&udev->dev, "set a_alt_hnp_support failed: %d\n", err); } } #endif return err; }
12,061
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.
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)); }
17,907
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.
Code: void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; if (isMainThread()) { DOMData::removeObjectsFromWrapperMap<Node>(&store, store.domNodeMap()); DOMData::removeObjectsFromWrapperMap<Node>(&store, store.activeDomNodeMap()); } DOMData::removeObjectsFromWrapperMap<void>(&store, store.domObjectMap()); } Commit Message: [V8] ASSERT that removeAllDOMObjects() is called only on worker threads https://bugs.webkit.org/show_bug.cgi?id=100046 Reviewed by Eric Seidel. This function is called only on worker threads. We should ASSERT that fact and remove the dead code that tries to handle the main thread case. * bindings/v8/V8DOMMap.cpp: (WebCore::removeAllDOMObjects): git-svn-id: svn://svn.chromium.org/blink/trunk@132156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void removeAllDOMObjects() { DOMDataStore& store = DOMData::getCurrentStore(); v8::HandleScope scope; ASSERT(!isMainThread()); // Note: We skip the Node wrapper maps because they exist only on the main thread. DOMData::removeObjectsFromWrapperMap<void>(&store, store.domObjectMap()); }
445
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.
Code: SSLErrorHandler::SSLErrorHandler(base::WeakPtr<Delegate> delegate, const content::GlobalRequestID& id, ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id) : manager_(NULL), request_id_(id), delegate_(delegate), render_process_id_(render_process_id), render_view_id_(render_view_id), request_url_(url), resource_type_(resource_type), request_has_been_notified_(false) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(delegate); AddRef(); } Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T> This change refines r137676. BUG=122654 TEST=browser_test Review URL: https://chromiumcodereview.appspot.com/10332233 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
SSLErrorHandler::SSLErrorHandler(base::WeakPtr<Delegate> delegate, SSLErrorHandler::SSLErrorHandler(const base::WeakPtr<Delegate>& delegate, const content::GlobalRequestID& id, ResourceType::Type resource_type, const GURL& url, int render_process_id, int render_view_id) : manager_(NULL), request_id_(id), delegate_(delegate), render_process_id_(render_process_id), render_view_id_(render_view_id), request_url_(url), resource_type_(resource_type), request_has_been_notified_(false) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(delegate); AddRef(); }
3,296
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.
Code: int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if (p + j > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if (p + 1 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if (p + cookie_len > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if (p + 2 > d + n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((p + i + 1) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, "client [%2d of %2d]:%s\n", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((p + i) > (d + n)) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; } Commit Message: CWE ID: CWE-190
int ssl3_get_client_hello(SSL *s) { int i, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1, cookie_valid = 0; unsigned int cookie_len; long n; unsigned long id; unsigned char *p, *d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp = NULL; #endif STACK_OF(SSL_CIPHER) *ciphers = NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* * We do this so that we will respond with our native type. If we are * TLSv1 and we get SSLv3, we will respond with TLSv1, This down * switching should be handled by a different method. If we are SSLv3, we * will respond with SSLv3, even if prompted with TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A) { s->state = SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet = 1; n = s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return ((int)n); s->first_packet = 0; d = p = (unsigned char *)s->init_msg; /* * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte * for session id length */ if (n < 2 + SSL3_RANDOM_SIZE + 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * use version from inside client hello, not from record header (may * differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version = (((int)p[0]) << 8) | (int)p[1]; p += 2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version >> 8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* * similar to ssl3_get_record, send alert using remote version * number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* * If we require cookies and this ClientHello doesn't contain one, just * return since we do not want to allocate any memory yet. So check * cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); if (SSL3_RANDOM_SIZE + session_length + 1 >= (d + n) - p) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE); p += SSL3_RANDOM_SIZE; /* get the session-id */ j = *(p++); if ((d + n) - p < j) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } if ((j < 0) || (j > SSL_MAX_SSL_SESSION_ID_LENGTH)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } s->hit = 0; /* * Versions before 0.9.7 always allow clients to resume sessions in * renegotiation. 0.9.7 and later allow this by default, but optionally * ignore resumption requests with flag * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this * for security won't even compile against older library versions). * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to * request renegotiation but not a new session (s->new_session remains * unset): for servers, this essentially just means that the * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s, 1)) goto err; } else { i = ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous * session */ s->hit = 1; } else if (i == -1) goto err; else { /* i == 0 */ if (!ssl_get_new_session(s, 1)) goto err; } } p += j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ if ((d + n) - p < 1) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } cookie_len = *(p++); if ((d + n ) - p < cookie_len) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if (cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if (s->ctx->app_verify_cookie_cb != NULL) { if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } /* default verification */ else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } cookie_valid = 1; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } if ((d + n ) - p < 2) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p, i); if (i == 0) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } /* i bytes of cipher data + 1 byte for compression length later */ if ((d + n) - p < i + 1) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers)) == NULL) { goto err; } p += i; /* If it is a hit, check that the cipher is in the list */ if (s->hit) { j = 0; id = s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr, "client sent %d ciphers\n", sk_SSL_CIPHER_num(ciphers)); #endif for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) { c = sk_SSL_CIPHER_value(ciphers, i); #ifdef CIPHER_DEBUG fprintf(stderr, "client [%2d of %2d]:%s\n", i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j = 1; break; } } /* * Disabled because it can be used in a ciphersuite downgrade attack: * CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* * Special case as client bug workaround: the previously used * cipher may not be in the current list, the client instead * might be trying to continue using a cipher that before wasn't * chosen due to server preferences. We'll have to reject the * connection if the cipher is not enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* * we need to have the cipher in the cipher list if we are asked * to reuse it */ al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i = *(p++); if ((d + n) - p < i) { /* not enough data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q = p; #endif for (j = 0; j < i; j++) { if (p[j] == 0) break; } p += i; if (j >= i) { /* no compress */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions */ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s, &p, d + n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT); goto err; } } /* * Check if we want to use external pre-shared secret for this handshake * for not reused session only. We need to generate server_random before * calling tls_session_secret_cb in order to allow SessionTicket * processing to use it in key derivation. */ { unsigned char *pos; pos = s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher = NULL; s->session->master_key_length = sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit = 1; s->session->ciphers = ciphers; s->session->verify_result = X509_V_OK; ciphers = NULL; /* check if some cipher was preferred by call back */ pref_cipher = pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s-> session->ciphers, SSL_get_ciphers (s)); if (pref_cipher == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher = pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* * Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression = NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (s->options & SSL_OP_NO_COMPRESSION) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); if (comp_id == comp->id) { s->s3->tmp.new_compression = comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al = SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods) { /* See if we have a match */ int m, nn, o, v, done = 0; nn = sk_SSL_COMP_num(s->ctx->comp_methods); for (m = 0; m < nn; m++) { comp = sk_SSL_COMP_value(s->ctx->comp_methods, m); v = comp->id; for (o = 0; o < i; o++) { if (v == q[o]) { done = 1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression = comp; else comp = NULL; } #else /* * If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth = 0; #else s->session->compress_meth = (comp == NULL) ? 0 : comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = ciphers; if (ciphers == NULL) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto f_err; } ciphers = NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate = SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al = SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher = c; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc = NULL; SSL_CIPHER *ec = NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk = s->session->ciphers; for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { c = sk_SSL_CIPHER_value(sk, i); if (c->algorithm_enc & SSL_eNULL) nc = c; if (SSL_C_IS_EXPORT(c)) ec = c; } if (nc != NULL) s->s3->tmp.new_cipher = nc; else if (ec != NULL) s->s3->tmp.new_cipher = ec; else s->s3->tmp.new_cipher = s->session->cipher; } else #endif s->s3->tmp.new_cipher = s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->tmp.new_cipher - the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } ret = cookie_valid ? 2 : 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret; }
27,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.
Code: struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; /* The assumption is that we are safe to process the chunks * at this time. */ if ((chunk = queue->in_progress)) { /* There is a packet that we have been working on. * Any post processing work to do before we move on? */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } else { /* Nothing to do. Next chunk in the packet, please. */ ch = (sctp_chunkhdr_t *) chunk->chunk_end; /* Force chunk->skb->data to chunk->chunk_end. */ skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data); /* Verify that we have at least chunk headers * worth of buffer left. */ if (skb_headlen(chunk->skb) < sizeof(sctp_chunkhdr_t)) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } } } /* Do we need to take the next packet out of the queue to process? */ if (!chunk) { struct list_head *entry; /* Is the queue empty? */ if (list_empty(&queue->in_chunk_list)) return NULL; entry = queue->in_chunk_list.next; chunk = queue->in_progress = list_entry(entry, struct sctp_chunk, list); list_del_init(entry); /* This is the first chunk in the packet. */ chunk->singleton = 1; ch = (sctp_chunkhdr_t *) chunk->skb->data; chunk->data_accepted = 0; } chunk->chunk_hdr = ch; chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); /* In the unlikely case of an IP reassembly, the skb could be * non-linear. If so, update chunk_end so that it doesn't go past * the skb->tail. */ if (unlikely(skb_is_nonlinear(chunk->skb))) { if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) chunk->chunk_end = skb_tail_pointer(chunk->skb); } skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t)); chunk->subh.v = NULL; /* Subheader is no longer valid. */ if (chunk->chunk_end < skb_tail_pointer(chunk->skb)) { /* This is not a singleton */ chunk->singleton = 0; } else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) { /* RFC 2960, Section 6.10 Bundling * * Partial chunks MUST NOT be placed in an SCTP packet. * If the receiver detects a partial chunk, it MUST drop * the chunk. * * Since the end of the chunk is past the end of our buffer * (which contains the whole packet, we can freely discard * the whole packet. */ sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; return NULL; } else { /* We are at the end of the packet, so mark the chunk * in case we need to send a SACK. */ chunk->end_of_packet = 1; } pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n", chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)), ntohs(chunk->chunk_hdr->length), chunk->skb->len); return chunk; } Commit Message: net: sctp: fix remote memory pressure from excessive queueing This scenario is not limited to ASCONF, just taken as one example triggering the issue. When receiving ASCONF probes in the form of ... -------------- INIT[ASCONF; ASCONF_ACK] -------------> <----------- INIT-ACK[ASCONF; ASCONF_ACK] ------------ -------------------- COOKIE-ECHO --------------------> <-------------------- COOKIE-ACK --------------------- ---- ASCONF_a; [ASCONF_b; ...; ASCONF_n;] JUNK ------> [...] ---- ASCONF_m; [ASCONF_o; ...; ASCONF_z;] JUNK ------> ... where ASCONF_a, ASCONF_b, ..., ASCONF_z are good-formed ASCONFs and have increasing serial numbers, we process such ASCONF chunk(s) marked with !end_of_packet and !singleton, since we have not yet reached the SCTP packet end. SCTP does only do verification on a chunk by chunk basis, as an SCTP packet is nothing more than just a container of a stream of chunks which it eats up one by one. We could run into the case that we receive a packet with a malformed tail, above marked as trailing JUNK. All previous chunks are here goodformed, so the stack will eat up all previous chunks up to this point. In case JUNK does not fit into a chunk header and there are no more other chunks in the input queue, or in case JUNK contains a garbage chunk header, but the encoded chunk length would exceed the skb tail, or we came here from an entirely different scenario and the chunk has pdiscard=1 mark (without having had a flush point), it will happen, that we will excessively queue up the association's output queue (a correct final chunk may then turn it into a response flood when flushing the queue ;)): I ran a simple script with incremental ASCONF serial numbers and could see the server side consuming excessive amount of RAM [before/after: up to 2GB and more]. The issue at heart is that the chunk train basically ends with !end_of_packet and !singleton markers and since commit 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") therefore preventing an output queue flush point in sctp_do_sm() -> sctp_cmd_interpreter() on the input chunk (chunk = event_arg) even though local_cork is set, but its precedence has changed since then. In the normal case, the last chunk with end_of_packet=1 would trigger the queue flush to accommodate possible outgoing bundling. In the input queue, sctp_inq_pop() seems to do the right thing in terms of discarding invalid chunks. So, above JUNK will not enter the state machine and instead be released and exit the sctp_assoc_bh_rcv() chunk processing loop. It's simply the flush point being missing at loop exit. Adding a try-flush approach on the output queue might not work as the underlying infrastructure might be long gone at this point due to the side-effect interpreter run. One possibility, albeit a bit of a kludge, would be to defer invalid chunk freeing into the state machine in order to possibly trigger packet discards and thus indirectly a queue flush on error. It would surely be better to discard chunks as in the current, perhaps better controlled environment, but going back and forth, it's simply architecturally not possible. I tried various trailing JUNK attack cases and it seems to look good now. Joint work with Vlad Yasevich. Fixes: 2e3216cd54b1 ("sctp: Follow security requirement of responding with 1 packet") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; /* The assumption is that we are safe to process the chunks * at this time. */ if ((chunk = queue->in_progress)) { /* There is a packet that we have been working on. * Any post processing work to do before we move on? */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } else { /* Nothing to do. Next chunk in the packet, please. */ ch = (sctp_chunkhdr_t *) chunk->chunk_end; /* Force chunk->skb->data to chunk->chunk_end. */ skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data); /* We are guaranteed to pull a SCTP header. */ } } /* Do we need to take the next packet out of the queue to process? */ if (!chunk) { struct list_head *entry; /* Is the queue empty? */ if (list_empty(&queue->in_chunk_list)) return NULL; entry = queue->in_chunk_list.next; chunk = queue->in_progress = list_entry(entry, struct sctp_chunk, list); list_del_init(entry); /* This is the first chunk in the packet. */ chunk->singleton = 1; ch = (sctp_chunkhdr_t *) chunk->skb->data; chunk->data_accepted = 0; } chunk->chunk_hdr = ch; chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); /* In the unlikely case of an IP reassembly, the skb could be * non-linear. If so, update chunk_end so that it doesn't go past * the skb->tail. */ if (unlikely(skb_is_nonlinear(chunk->skb))) { if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) chunk->chunk_end = skb_tail_pointer(chunk->skb); } skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t)); chunk->subh.v = NULL; /* Subheader is no longer valid. */ if (chunk->chunk_end + sizeof(sctp_chunkhdr_t) < skb_tail_pointer(chunk->skb)) { /* This is not a singleton */ chunk->singleton = 0; } else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) { /* Discard inside state machine. */ chunk->pdiscard = 1; chunk->chunk_end = skb_tail_pointer(chunk->skb); } else { /* We are at the end of the packet, so mark the chunk * in case we need to send a SACK. */ chunk->end_of_packet = 1; } pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n", chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)), ntohs(chunk->chunk_hdr->length), chunk->skb->len); return chunk; }
11,625
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.
Code: void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; EAS_PCM *pInputBuffer; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I32 numSamples; #if (NUM_OUTPUT_CHANNELS == 2) EAS_I32 gainLeft, gainRight; #endif /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pMixBuffer = pWTIntFrame->pMixBuffer; pInputBuffer = pWTIntFrame->pAudioBuffer; /*lint -e{703} <avoid multiply for performance>*/ gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; /*lint -e{703} <avoid multiply for performance>*/ gain = pWTIntFrame->prevGain << 16; #if (NUM_OUTPUT_CHANNELS == 2) gainLeft = pWTVoice->gainLeft; gainRight = pWTVoice->gainRight; #endif while (numSamples--) { /* incremental gain step to prevent zipper noise */ tmp0 = *pInputBuffer++; gain += gainIncrement; /*lint -e{704} <avoid divide>*/ tmp2 = gain >> 16; /* scale sample by gain */ tmp2 *= tmp0; /* stereo output */ #if (NUM_OUTPUT_CHANNELS == 2) /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> 14; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* left channel */ tmp0 = tmp2 * gainLeft; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* right channel */ tmp0 = tmp2 * gainRight; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* mono output */ #else /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1); tmp1 += tmp2; *pMixBuffer++ = tmp1; #endif } } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119
void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; EAS_PCM *pInputBuffer; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I32 numSamples; #if (NUM_OUTPUT_CHANNELS == 2) EAS_I32 gainLeft, gainRight; #endif /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); android_errorWriteLog(0x534e4554, "26366256"); return; } pMixBuffer = pWTIntFrame->pMixBuffer; pInputBuffer = pWTIntFrame->pAudioBuffer; /*lint -e{703} <avoid multiply for performance>*/ gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; /*lint -e{703} <avoid multiply for performance>*/ gain = pWTIntFrame->prevGain << 16; #if (NUM_OUTPUT_CHANNELS == 2) gainLeft = pWTVoice->gainLeft; gainRight = pWTVoice->gainRight; #endif while (numSamples--) { /* incremental gain step to prevent zipper noise */ tmp0 = *pInputBuffer++; gain += gainIncrement; /*lint -e{704} <avoid divide>*/ tmp2 = gain >> 16; /* scale sample by gain */ tmp2 *= tmp0; /* stereo output */ #if (NUM_OUTPUT_CHANNELS == 2) /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> 14; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* left channel */ tmp0 = tmp2 * gainLeft; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* right channel */ tmp0 = tmp2 * gainRight; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* mono output */ #else /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1); tmp1 += tmp2; *pMixBuffer++ = tmp1; #endif } }
15,440
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.
Code: bool ResourceDispatcherHostImpl::AcceptAuthRequest( ResourceLoader* loader, net::AuthChallengeInfo* auth_info) { if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info)) return false; if (!auth_info->is_proxy) { HttpAuthResourceType resource_type = HttpAuthResourceTypeOf(loader->request()); UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource", resource_type, HTTP_AUTH_RESOURCE_LAST); if (resource_type == HTTP_AUTH_RESOURCE_BLOCKED_CROSS) return false; } return true; } Commit Message: Revert cross-origin auth prompt blocking. BUG=174129 Review URL: https://chromiumcodereview.appspot.com/12183030 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ResourceDispatcherHostImpl::AcceptAuthRequest( ResourceLoader* loader, net::AuthChallengeInfo* auth_info) { if (delegate_ && !delegate_->AcceptAuthRequest(loader->request(), auth_info)) return false; if (!auth_info->is_proxy) { HttpAuthResourceType resource_type = HttpAuthResourceTypeOf(loader->request()); UMA_HISTOGRAM_ENUMERATION("Net.HttpAuthResource", resource_type, HTTP_AUTH_RESOURCE_LAST); // TODO(tsepez): Return false on HTTP_AUTH_RESOURCE_BLOCKED_CROSS. // The code once did this, but was changed due to http://crbug.com/174129. // http://crbug.com/174179 has been filed to track this issue. } return true; }
8,908
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.
Code: long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } return 0; }
20,051
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.
Code: int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; /* map/unmap the pages in iommu page table */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_free; } else kvm_iommu_unmap_pages(kvm, &old); r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_free: kvm_free_physmem_slot(&new, &old); out: return r; } Commit Message: KVM: Fix iommu map/unmap to handle memory slot moves The iommu integration into memory slots expects memory slots to be added or removed and doesn't handle the move case. We can unmap slots from the iommu after we mark them invalid and map them before installing the final memslot array. Also re-order the kmemdup vs map so we don't leave iommu mappings if we get ENOMEM. Reviewed-by: Gleb Natapov <[email protected]> Signed-off-by: Alex Williamson <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
int __kvm_set_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, int user_alloc) { int r; gfn_t base_gfn; unsigned long npages; struct kvm_memory_slot *memslot, *slot; struct kvm_memory_slot old, new; struct kvm_memslots *slots, *old_memslots; r = check_memory_region_flags(mem); if (r) goto out; r = -EINVAL; /* General sanity checks */ if (mem->memory_size & (PAGE_SIZE - 1)) goto out; if (mem->guest_phys_addr & (PAGE_SIZE - 1)) goto out; /* We can read the guest memory with __xxx_user() later on. */ if (user_alloc && ((mem->userspace_addr & (PAGE_SIZE - 1)) || !access_ok(VERIFY_WRITE, (void __user *)(unsigned long)mem->userspace_addr, mem->memory_size))) goto out; if (mem->slot >= KVM_MEM_SLOTS_NUM) goto out; if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) goto out; memslot = id_to_memslot(kvm->memslots, mem->slot); base_gfn = mem->guest_phys_addr >> PAGE_SHIFT; npages = mem->memory_size >> PAGE_SHIFT; r = -EINVAL; if (npages > KVM_MEM_MAX_NR_PAGES) goto out; if (!npages) mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES; new = old = *memslot; new.id = mem->slot; new.base_gfn = base_gfn; new.npages = npages; new.flags = mem->flags; /* * Disallow changing a memory slot's size or changing anything about * zero sized slots that doesn't involve making them non-zero. */ r = -EINVAL; if (npages && old.npages && npages != old.npages) goto out_free; if (!npages && !old.npages) goto out_free; /* Check for overlaps */ r = -EEXIST; kvm_for_each_memslot(slot, kvm->memslots) { if (slot->id >= KVM_MEMORY_SLOTS || slot == memslot) continue; if (!((base_gfn + npages <= slot->base_gfn) || (base_gfn >= slot->base_gfn + slot->npages))) goto out_free; } /* Free page dirty bitmap if unneeded */ if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES)) new.dirty_bitmap = NULL; r = -ENOMEM; /* * Allocate if a slot is being created. If modifying a slot, * the userspace_addr cannot change. */ if (!old.npages) { new.user_alloc = user_alloc; new.userspace_addr = mem->userspace_addr; if (kvm_arch_create_memslot(&new, npages)) goto out_free; } else if (npages && mem->userspace_addr != old.userspace_addr) { r = -EINVAL; goto out_free; } /* Allocate page dirty bitmap if needed */ if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) { if (kvm_create_dirty_bitmap(&new) < 0) goto out_free; /* destroy any largepage mappings for dirty tracking */ } if (!npages || base_gfn != old.base_gfn) { struct kvm_memory_slot *slot; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; slot = id_to_memslot(slots, mem->slot); slot->flags |= KVM_MEMSLOT_INVALID; update_memslots(slots, NULL); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); /* slot was deleted or moved, clear iommu mapping */ kvm_iommu_unmap_pages(kvm, &old); /* From this point no new shadow pages pointing to a deleted, * or moved, memslot will be created. * * validation of sp->gfn happens in: * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) * - kvm_is_visible_gfn (mmu_check_roots) */ kvm_arch_flush_shadow_memslot(kvm, slot); kfree(old_memslots); } r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc); if (r) goto out_free; r = -ENOMEM; slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots), GFP_KERNEL); if (!slots) goto out_free; /* map new memory slot into the iommu */ if (npages) { r = kvm_iommu_map_pages(kvm, &new); if (r) goto out_slots; } /* actual memory is freed via old in kvm_free_physmem_slot below */ if (!npages) { new.dirty_bitmap = NULL; memset(&new.arch, 0, sizeof(new.arch)); } update_memslots(slots, &new); old_memslots = kvm->memslots; rcu_assign_pointer(kvm->memslots, slots); synchronize_srcu_expedited(&kvm->srcu); kvm_arch_commit_memory_region(kvm, mem, old, user_alloc); kvm_free_physmem_slot(&old, &new); kfree(old_memslots); return 0; out_slots: kfree(slots); out_free: kvm_free_physmem_slot(&new, &old); out: return r; }
25,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.
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; }
1,716
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.
Code: compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb) { png_uint_32 x; for (x=0; x<width; ++x) { png_byte bval = ppb[x]; png_byte aval = ppa[x]; if (bval > bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; y<height; ++y, rowa += stridea, rowb += strideb) { png_const_bytep ppa, ppb; png_uint_32 x; for (x=0, ppa=rowa, ppb=rowb; x<width; ++x) { png_const_bytep psa, psb; if (formata & PNG_FORMAT_FLAG_COLORMAP) psa = (png_const_bytep)a->colormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
compare_two_images(Image *a, Image *b, int via_linear, png_const_colorp background) { ptrdiff_t stridea = a->stride; ptrdiff_t strideb = b->stride; png_const_bytep rowa = a->buffer+16; png_const_bytep rowb = b->buffer+16; const png_uint_32 width = a->image.width; const png_uint_32 height = a->image.height; const png_uint_32 formata = a->image.format; const png_uint_32 formatb = b->image.format; const unsigned int a_sample = PNG_IMAGE_SAMPLE_SIZE(formata); const unsigned int b_sample = PNG_IMAGE_SAMPLE_SIZE(formatb); int alpha_added, alpha_removed; int bchannels; int btoa[4]; png_uint_32 y; Transform tr; /* This should never happen: */ if (width != b->image.width || height != b->image.height) return logerror(a, a->file_name, ": width x height changed: ", b->file_name); /* Set up the background and the transform */ transform_from_formats(&tr, a, b, background, via_linear); /* Find the first row and inter-row space. */ if (!(formata & PNG_FORMAT_FLAG_COLORMAP) && (formata & PNG_FORMAT_FLAG_LINEAR)) stridea *= 2; if (!(formatb & PNG_FORMAT_FLAG_COLORMAP) && (formatb & PNG_FORMAT_FLAG_LINEAR)) strideb *= 2; if (stridea < 0) rowa += (height-1) * (-stridea); if (strideb < 0) rowb += (height-1) * (-strideb); /* First shortcut the two colormap case by comparing the image data; if it * matches then we expect the colormaps to match, although this is not * absolutely necessary for an image match. If the colormaps fail to match * then there is a problem in libpng. */ if (formata & formatb & PNG_FORMAT_FLAG_COLORMAP) { /* Only check colormap entries that actually exist; */ png_const_bytep ppa, ppb; int match; png_byte in_use[256], amax = 0, bmax = 0; memset(in_use, 0, sizeof in_use); ppa = rowa; ppb = rowb; /* Do this the slow way to accumulate the 'in_use' flags, don't break out * of the loop until the end; this validates the color-mapped data to * ensure all pixels are valid color-map indexes. */ for (y=0, match=1; y<height && match; ++y, ppa += stridea, ppb += strideb) { png_uint_32 x; for (x=0; x<width; ++x) { png_byte bval = ppb[x]; png_byte aval = ppa[x]; if (bval > bmax) bmax = bval; if (bval != aval) match = 0; in_use[aval] = 1; if (aval > amax) amax = aval; } } /* If the buffers match then the colormaps must too. */ if (match) { /* Do the color-maps match, entry by entry? Only check the 'in_use' * entries. An error here should be logged as a color-map error. */ png_const_bytep a_cmap = (png_const_bytep)a->colormap; png_const_bytep b_cmap = (png_const_bytep)b->colormap; int result = 1; /* match by default */ /* This is used in logpixel to get the error message correct. */ tr.is_palette = 1; for (y=0; y<256; ++y, a_cmap += a_sample, b_cmap += b_sample) if (in_use[y]) { /* The colormap entries should be valid, but because libpng doesn't * do any checking at present the original image may contain invalid * pixel values. These cause an error here (at present) unless * accumulating errors in which case the program just ignores them. */ if (y >= a->image.colormap_entries) { if ((a->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)a->image.colormap_entries); logerror(a, a->file_name, ": bad pixel index: ", pindex); } result = 0; } else if (y >= b->image.colormap_entries) { if ((b->opts & ACCUMULATE) == 0) { char pindex[9]; sprintf(pindex, "%lu[%lu]", (unsigned long)y, (unsigned long)b->image.colormap_entries); logerror(b, b->file_name, ": bad pixel index: ", pindex); } result = 0; } /* All the mismatches are logged here; there can only be 256! */ else if (!cmppixel(&tr, a_cmap, b_cmap, 0, y)) result = 0; } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; result = 1; /* force a continue */ } return result; } /* else the image buffers don't match pixel-wise so compare sample values * instead, but first validate that the pixel indexes are in range (but * only if not accumulating, when the error is ignored.) */ else if ((a->opts & ACCUMULATE) == 0) { /* Check the original image first, * TODO: deal with input images with bad pixel values? */ if (amax >= a->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", amax, (unsigned long)a->image.colormap_entries); return logerror(a, a->file_name, ": bad pixel index: ", pindex); } else if (bmax >= b->image.colormap_entries) { char pindex[9]; sprintf(pindex, "%d[%lu]", bmax, (unsigned long)b->image.colormap_entries); return logerror(b, b->file_name, ": bad pixel index: ", pindex); } } } /* We can directly compare pixel values without the need to use the read * or transform support (i.e. a memory compare) if: * * 1) The bit depth has not changed. * 2) RGB to grayscale has not been done (the reverse is ok; we just compare * the three RGB values to the original grayscale.) * 3) An alpha channel has not been removed from an 8-bit format, or the * 8-bit alpha value of the pixel was 255 (opaque). * * If an alpha channel has been *added* then it must have the relevant opaque * value (255 or 65535). * * The fist two the tests (in the order given above) (using the boolean * equivalence !a && !b == !(a || b)) */ if (!(((formata ^ formatb) & PNG_FORMAT_FLAG_LINEAR) | (formata & (formatb ^ PNG_FORMAT_FLAG_COLOR) & PNG_FORMAT_FLAG_COLOR))) { /* Was an alpha channel changed? */ const png_uint_32 alpha_changed = (formata ^ formatb) & PNG_FORMAT_FLAG_ALPHA; /* Was an alpha channel removed? (The third test.) If so the direct * comparison is only possible if the input alpha is opaque. */ alpha_removed = (formata & alpha_changed) != 0; /* Was an alpha channel added? */ alpha_added = (formatb & alpha_changed) != 0; /* The channels may have been moved between input and output, this finds * out how, recording the result in the btoa array, which says where in * 'a' to find each channel of 'b'. If alpha was added then btoa[alpha] * ends up as 4 (and is not used.) */ { int i; png_byte aloc[4]; png_byte bloc[4]; /* The following are used only if the formats match, except that * 'bchannels' is a flag for matching formats. btoa[x] says, for each * channel in b, where to find the corresponding value in a, for the * bchannels. achannels may be different for a gray to rgb transform * (a will be 1 or 2, b will be 3 or 4 channels.) */ (void)component_loc(aloc, formata); bchannels = component_loc(bloc, formatb); /* Hence the btoa array. */ for (i=0; i<4; ++i) if (bloc[i] < 4) btoa[bloc[i]] = aloc[i]; /* may be '4' for alpha */ if (alpha_added) alpha_added = bloc[0]; /* location of alpha channel in image b */ else alpha_added = 4; /* Won't match an image b channel */ if (alpha_removed) alpha_removed = aloc[0]; /* location of alpha channel in image a */ else alpha_removed = 4; } } else { /* Direct compare is not possible, cancel out all the corresponding local * variables. */ bchannels = 0; alpha_removed = alpha_added = 4; btoa[3] = btoa[2] = btoa[1] = btoa[0] = 4; /* 4 == not present */ } for (y=0; y<height; ++y, rowa += stridea, rowb += strideb) { png_const_bytep ppa, ppb; png_uint_32 x; for (x=0, ppa=rowa, ppb=rowb; x<width; ++x) { png_const_bytep psa, psb; if (formata & PNG_FORMAT_FLAG_COLORMAP) psa = (png_const_bytep)a->colormap + a_sample * *ppa++; else psa = ppa, ppa += a_sample; if (formatb & PNG_FORMAT_FLAG_COLORMAP) psb = (png_const_bytep)b->colormap + b_sample * *ppb++; else psb = ppb, ppb += b_sample; /* Do the fast test if possible. */ if (bchannels) { /* Check each 'b' channel against either the corresponding 'a' * channel or the opaque alpha value, as appropriate. If * alpha_removed value is set (not 4) then also do this only if the * 'a' alpha channel (alpha_removed) is opaque; only relevant for * the 8-bit case. */ if (formatb & PNG_FORMAT_FLAG_LINEAR) /* 16-bit checks */ { png_const_uint_16p pua = aligncastconst(png_const_uint_16p, psa); png_const_uint_16p pub = aligncastconst(png_const_uint_16p, psb); switch (bchannels) { case 4: if (pua[btoa[3]] != pub[3]) break; case 3: if (pua[btoa[2]] != pub[2]) break; case 2: if (pua[btoa[1]] != pub[1]) break; case 1: if (pua[btoa[0]] != pub[0]) break; if (alpha_added != 4 && pub[alpha_added] != 65535) break; continue; /* x loop */ default: break; /* impossible */ } } else if (alpha_removed == 4 || psa[alpha_removed] == 255) { switch (bchannels) { case 4: if (psa[btoa[3]] != psb[3]) break; case 3: if (psa[btoa[2]] != psb[2]) break; case 2: if (psa[btoa[1]] != psb[1]) break; case 1: if (psa[btoa[0]] != psb[0]) break; if (alpha_added != 4 && psb[alpha_added] != 255) break; continue; /* x loop */ default: break; /* impossible */ } } } /* If we get to here the fast match failed; do the slow match for this * pixel. */ if (!cmppixel(&tr, psa, psb, x, y) && (a->opts & KEEP_GOING) == 0) return 0; /* error case */ } } /* If reqested copy the error values back from the Transform. */ if (a->opts & ACCUMULATE) { tr.error_ptr[0] = tr.error[0]; tr.error_ptr[1] = tr.error[1]; tr.error_ptr[2] = tr.error[2]; tr.error_ptr[3] = tr.error[3]; } return 1; }
23,133
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.
Code: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long rem; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; u32 rem; value->tv_sec = div_u64_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; }
14,569
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.
Code: static v8::Handle<v8::Value> overloadedMethod6Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod6"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<DOMStringList>, listArg, v8ValueToWebCoreDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(listArg); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> overloadedMethod6Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod6"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(RefPtr<DOMStringList>, listArg, v8ValueToWebCoreDOMStringList(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(listArg); return v8::Handle<v8::Value>(); }
2,097
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.
Code: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required, std::string* experiment_id) : field_types_(field_types), upload_required_(upload_required), experiment_id_(experiment_id) { DCHECK(upload_required_); DCHECK(experiment_id_); }
14,428
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.
Code: row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; /* The remaining bits are in the top of the byte, the mask is the bits to * retain. */ mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth, int littleendian) { memcpy(toBuffer, fromBuffer, bitWidth >> 3); if ((bitWidth & 7) != 0) { unsigned int mask; toBuffer += bitWidth >> 3; fromBuffer += bitWidth >> 3; if (littleendian) mask = 0xff << (bitWidth & 7); else mask = 0xff >> (bitWidth & 7); *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); } }
18,255
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.
Code: base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response(std::move(protocol_versions), it->second.GetBytestring()); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22
base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response( std::move(protocol_versions), base::make_span<kAaguidLength>(it->second.GetBytestring())); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); }
26,751
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.
Code: virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAgentManagerClient( scoped_ptr<BluetoothAgentManagerClient>( new FakeBluetoothAgentManagerClient)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); }
14,954
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.
Code: ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_) { PCNetState *s = qemu_get_nic_opaque(nc); int is_padr = 0, is_bcast = 0, is_ladr = 0; uint8_t buf1[60]; int remaining; int crc_err = 0; int size = size_; if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size || (CSR_LOOP(s) && !s->looptest)) { return -1; } #ifdef PCNET_DEBUG printf("pcnet_receive size=%d\n", size); #endif /* if too small buffer, then expand it */ if (size < MIN_BUF_SIZE) { memcpy(buf1, buf, size); memset(buf1 + size, 0, MIN_BUF_SIZE - size); buf = buf1; size = MIN_BUF_SIZE; } if (CSR_PROM(s) || (is_padr=padr_match(s, buf, size)) || (is_bcast=padr_bcast(s, buf, size)) || (is_ladr=ladr_match(s, buf, size))) { pcnet_rdte_poll(s); if (!(CSR_CRST(s) & 0x8000) && s->rdra) { struct pcnet_RMD rmd; int rcvrc = CSR_RCVRC(s)-1,i; hwaddr nrda; for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) { if (rcvrc <= 1) rcvrc = CSR_RCVRL(s); nrda = s->rdra + (CSR_RCVRL(s) - rcvrc) * (BCR_SWSTYLE(s) ? 16 : 8 ); RMDLOAD(&rmd, nrda); if (GET_FIELD(rmd.status, RMDS, OWN)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n", rcvrc, CSR_RCVRC(s)); #endif CSR_RCVRC(s) = rcvrc; pcnet_rdte_poll(s); break; } } } if (!(CSR_CRST(s) & 0x8000)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s)); #endif s->csr[0] |= 0x1000; /* Set MISS flag */ CSR_MISSC(s)++; } else { uint8_t *src = s->buffer; hwaddr crda = CSR_CRDA(s); struct pcnet_RMD rmd; int pktcount = 0; if (!s->looptest) { memcpy(src, buf, size); /* no need to compute the CRC */ src[size] = 0; uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); *(uint32_t *)p = htonl(fcs); size += 4; } else { uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); crc_err = (*(uint32_t *)p != htonl(fcs)); } #ifdef PCNET_DEBUG_MATCH PRINT_PKTHDR(buf); #endif RMDLOAD(&rmd, PHYSADDR(s,crda)); /*if (!CSR_LAPPEN(s))*/ SET_FIELD(&rmd.status, RMDS, STP, 1); #define PCNET_RECV_STORE() do { \ int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \ hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \ s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \ src += count; remaining -= count; \ SET_FIELD(&rmd.status, RMDS, OWN, 0); \ RMDSTORE(&rmd, PHYSADDR(s,crda)); \ pktcount++; \ } while (0) remaining = size; PCNET_RECV_STORE(); if ((remaining > 0) && CSR_NRDA(s)) { hwaddr nrda = CSR_NRDA(s); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif if ((remaining > 0) && (nrda=CSR_NNRD(s))) { RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); } } } } #undef PCNET_RECV_STORE RMDLOAD(&rmd, PHYSADDR(s,crda)); if (remaining == 0) { SET_FIELD(&rmd.msg_length, RMDM, MCNT, size); SET_FIELD(&rmd.status, RMDS, ENP, 1); SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr); SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr); SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast); if (crc_err) { SET_FIELD(&rmd.status, RMDS, CRC, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } } else { SET_FIELD(&rmd.status, RMDS, OFLO, 1); SET_FIELD(&rmd.status, RMDS, BUFF, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } RMDSTORE(&rmd, PHYSADDR(s,crda)); s->csr[0] |= 0x0400; #ifdef PCNET_DEBUG printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n", CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount); #endif #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif while (pktcount--) { if (CSR_RCVRC(s) <= 1) CSR_RCVRC(s) = CSR_RCVRL(s); else CSR_RCVRC(s)--; } pcnet_rdte_poll(s); } } pcnet_poll(s); pcnet_update_irq(s); return size_; } Commit Message: CWE ID: CWE-119
ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_) { PCNetState *s = qemu_get_nic_opaque(nc); int is_padr = 0, is_bcast = 0, is_ladr = 0; uint8_t buf1[60]; int remaining; int crc_err = 0; int size = size_; if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size || (CSR_LOOP(s) && !s->looptest)) { return -1; } #ifdef PCNET_DEBUG printf("pcnet_receive size=%d\n", size); #endif /* if too small buffer, then expand it */ if (size < MIN_BUF_SIZE) { memcpy(buf1, buf, size); memset(buf1 + size, 0, MIN_BUF_SIZE - size); buf = buf1; size = MIN_BUF_SIZE; } if (CSR_PROM(s) || (is_padr=padr_match(s, buf, size)) || (is_bcast=padr_bcast(s, buf, size)) || (is_ladr=ladr_match(s, buf, size))) { pcnet_rdte_poll(s); if (!(CSR_CRST(s) & 0x8000) && s->rdra) { struct pcnet_RMD rmd; int rcvrc = CSR_RCVRC(s)-1,i; hwaddr nrda; for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) { if (rcvrc <= 1) rcvrc = CSR_RCVRL(s); nrda = s->rdra + (CSR_RCVRL(s) - rcvrc) * (BCR_SWSTYLE(s) ? 16 : 8 ); RMDLOAD(&rmd, nrda); if (GET_FIELD(rmd.status, RMDS, OWN)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n", rcvrc, CSR_RCVRC(s)); #endif CSR_RCVRC(s) = rcvrc; pcnet_rdte_poll(s); break; } } } if (!(CSR_CRST(s) & 0x8000)) { #ifdef PCNET_DEBUG_RMD printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s)); #endif s->csr[0] |= 0x1000; /* Set MISS flag */ CSR_MISSC(s)++; } else { uint8_t *src = s->buffer; hwaddr crda = CSR_CRDA(s); struct pcnet_RMD rmd; int pktcount = 0; if (!s->looptest) { if (size > 4092) { #ifdef PCNET_DEBUG_RMD fprintf(stderr, "pcnet: truncates rx packet.\n"); #endif size = 4092; } memcpy(src, buf, size); /* no need to compute the CRC */ src[size] = 0; uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); *(uint32_t *)p = htonl(fcs); size += 4; } else { uint32_t fcs = ~0; uint8_t *p = src; while (p != &src[size]) CRC(fcs, *p++); crc_err = (*(uint32_t *)p != htonl(fcs)); } #ifdef PCNET_DEBUG_MATCH PRINT_PKTHDR(buf); #endif RMDLOAD(&rmd, PHYSADDR(s,crda)); /*if (!CSR_LAPPEN(s))*/ SET_FIELD(&rmd.status, RMDS, STP, 1); #define PCNET_RECV_STORE() do { \ int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \ hwaddr rbadr = PHYSADDR(s, rmd.rbadr); \ s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \ src += count; remaining -= count; \ SET_FIELD(&rmd.status, RMDS, OWN, 0); \ RMDSTORE(&rmd, PHYSADDR(s,crda)); \ pktcount++; \ } while (0) remaining = size; PCNET_RECV_STORE(); if ((remaining > 0) && CSR_NRDA(s)) { hwaddr nrda = CSR_NRDA(s); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif if ((remaining > 0) && (nrda=CSR_NNRD(s))) { RMDLOAD(&rmd, PHYSADDR(s,nrda)); if (GET_FIELD(rmd.status, RMDS, OWN)) { crda = nrda; PCNET_RECV_STORE(); } } } } #undef PCNET_RECV_STORE RMDLOAD(&rmd, PHYSADDR(s,crda)); if (remaining == 0) { SET_FIELD(&rmd.msg_length, RMDM, MCNT, size); SET_FIELD(&rmd.status, RMDS, ENP, 1); SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr); SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr); SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast); if (crc_err) { SET_FIELD(&rmd.status, RMDS, CRC, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } } else { SET_FIELD(&rmd.status, RMDS, OFLO, 1); SET_FIELD(&rmd.status, RMDS, BUFF, 1); SET_FIELD(&rmd.status, RMDS, ERR, 1); } RMDSTORE(&rmd, PHYSADDR(s,crda)); s->csr[0] |= 0x0400; #ifdef PCNET_DEBUG printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n", CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount); #endif #ifdef PCNET_DEBUG_RMD PRINT_RMD(&rmd); #endif while (pktcount--) { if (CSR_RCVRC(s) <= 1) CSR_RCVRC(s) = CSR_RCVRL(s); else CSR_RCVRC(s)--; } pcnet_rdte_poll(s); } } pcnet_poll(s); pcnet_update_irq(s); return size_; }
26,426
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.
Code: foreach_nfs_shareopt(const char *shareopts, nfs_shareopt_callback_t callback, void *cookie) { char *shareopts_dup, *opt, *cur, *value; int was_nul, rc; if (shareopts == NULL) return (SA_OK); shareopts_dup = strdup(shareopts); if (shareopts_dup == NULL) return (SA_NO_MEMORY); opt = shareopts_dup; was_nul = 0; while (1) { cur = opt; while (*cur != ',' && *cur != '\0') cur++; if (*cur == '\0') was_nul = 1; *cur = '\0'; if (cur > opt) { value = strchr(opt, '='); if (value != NULL) { *value = '\0'; value++; } rc = callback(opt, value, cookie); if (rc != SA_OK) { free(shareopts_dup); return (rc); } } opt = cur + 1; if (was_nul) break; } free(shareopts_dup); return (0); } Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt() so that it can be (re)used in other parts of libshare. CWE ID: CWE-200
foreach_nfs_shareopt(const char *shareopts,
17,664
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.
Code: int do_fpu_inst(unsigned short inst, struct pt_regs *regs) { struct task_struct *tsk = current; struct sh_fpu_soft_struct *fpu = &(tsk->thread.xstate->softfpu); perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); if (!(task_thread_info(tsk)->status & TS_USEDFPU)) { /* initialize once. */ fpu_init(fpu); task_thread_info(tsk)->status |= TS_USEDFPU; } return fpu_emulate(inst, fpu, regs); } 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
int do_fpu_inst(unsigned short inst, struct pt_regs *regs) { struct task_struct *tsk = current; struct sh_fpu_soft_struct *fpu = &(tsk->thread.xstate->softfpu); perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); if (!(task_thread_info(tsk)->status & TS_USEDFPU)) { /* initialize once. */ fpu_init(fpu); task_thread_info(tsk)->status |= TS_USEDFPU; } return fpu_emulate(inst, fpu, regs); }
24,087
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.
Code: static void sas_unregister_devs_sas_addr(struct domain_device *parent, int phy_id, bool last) { struct expander_device *ex_dev = &parent->ex_dev; struct ex_phy *phy = &ex_dev->ex_phy[phy_id]; struct domain_device *child, *n, *found = NULL; if (last) { list_for_each_entry_safe(child, n, &ex_dev->children, siblings) { if (SAS_ADDR(child->sas_addr) == SAS_ADDR(phy->attached_sas_addr)) { set_bit(SAS_DEV_GONE, &child->state); if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) sas_unregister_ex_tree(parent->port, child); else sas_unregister_dev(parent->port, child); found = child; break; } } sas_disable_routing(parent, phy->attached_sas_addr); } memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); if (phy->port) { sas_port_delete_phy(phy->port, phy->phy); sas_device_set_phy(found, phy->port); if (phy->port->num_phys == 0) sas_port_delete(phy->port); phy->port = NULL; } } 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_unregister_devs_sas_addr(struct domain_device *parent, int phy_id, bool last) { struct expander_device *ex_dev = &parent->ex_dev; struct ex_phy *phy = &ex_dev->ex_phy[phy_id]; struct domain_device *child, *n, *found = NULL; if (last) { list_for_each_entry_safe(child, n, &ex_dev->children, siblings) { if (SAS_ADDR(child->sas_addr) == SAS_ADDR(phy->attached_sas_addr)) { set_bit(SAS_DEV_GONE, &child->state); if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) sas_unregister_ex_tree(parent->port, child); else sas_unregister_dev(parent->port, child); found = child; break; } } sas_disable_routing(parent, phy->attached_sas_addr); } memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); if (phy->port) { sas_port_delete_phy(phy->port, phy->phy); sas_device_set_phy(found, phy->port); if (phy->port->num_phys == 0) list_add_tail(&phy->port->del_list, &parent->port->sas_port_del_list); phy->port = NULL; } }
13,284
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.
Code: static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } Commit Message: packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; lock_sock(sk); /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: release_sock(sk); return err; }
18,624
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.
Code: kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) return code; code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; } Commit Message: Prevent KDC unset status assertion failures Assign status values if S4U2Self padata fails to decode, if an S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request uses an evidence ticket which does not match the canonicalized request server principal name. Reported by Samuel Cabrero. If a status value is not assigned during KDC processing, default to "UNKNOWN_REASON" rather than failing an assertion. This change will prevent future denial of service bugs due to similar mistakes, and will allow us to omit assigning status values for unlikely errors such as small memory allocation failures. CVE-2017-11368: In MIT krb5 1.7 and later, an authenticated attacker can cause an assertion failure in krb5kdc by sending an invalid S4U2Self or S4U2Proxy request. CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C ticket: 8599 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-617
kdc_process_for_user(kdc_realm_t *kdc_active_realm, krb5_pa_data *pa_data, krb5_keyblock *tgs_session, krb5_pa_s4u_x509_user **s4u_x509_user, const char **status) { krb5_error_code code; krb5_pa_for_user *for_user; krb5_data req_data; req_data.length = pa_data->length; req_data.data = (char *)pa_data->contents; code = decode_krb5_pa_for_user(&req_data, &for_user); if (code) { *status = "DECODE_PA_FOR_USER"; return code; } code = verify_for_user_checksum(kdc_context, tgs_session, for_user); if (code) { *status = "INVALID_S4U2SELF_CHECKSUM"; krb5_free_pa_for_user(kdc_context, for_user); return code; } *s4u_x509_user = calloc(1, sizeof(krb5_pa_s4u_x509_user)); if (*s4u_x509_user == NULL) { krb5_free_pa_for_user(kdc_context, for_user); return ENOMEM; } (*s4u_x509_user)->user_id.user = for_user->user; for_user->user = NULL; krb5_free_pa_for_user(kdc_context, for_user); return 0; }
8,744
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.
Code: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { if (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index]) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); mp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index]; return MP4buffer; } } } return NULL; }
21,156
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.
Code: static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); }
26,500
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.
Code: static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; } Commit Message: ServiceManager: Restore basic uid check Prevent apps from registering services without relying on selinux checks. Bug: 29431260 Change-Id: I38c6e8bc7f7cba1cbd3568e8fed1ae7ac2054a9b (cherry picked from commit 2b74d2c1d2a2c1bb6e9c420f7e9b339ba2a95179) CWE ID: CWE-264
static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid) { const char *perm = "add"; if (uid >= AID_APP) { return 0; /* Don't allow apps to register services */ } return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0; }
29,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.
Code: void ChromeMockRenderThread::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { DCHECK(params.page_number >= printing::FIRST_PAGE_INDEX); print_preview_pages_remaining_--; } 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::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { DCHECK_GE(params.page_number, printing::FIRST_PAGE_INDEX); print_preview_pages_remaining_--; }
15,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.
Code: void svc_rdma_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp, int status) { struct ib_send_wr err_wr; struct page *p; struct svc_rdma_op_ctxt *ctxt; enum rpcrdma_errcode err; __be32 *va; int length; int ret; ret = svc_rdma_repost_recv(xprt, GFP_KERNEL); if (ret) return; p = alloc_page(GFP_KERNEL); if (!p) return; va = page_address(p); /* XDR encode an error reply */ err = ERR_CHUNK; if (status == -EPROTONOSUPPORT) err = ERR_VERS; length = svc_rdma_xdr_encode_error(xprt, rmsgp, err, va); ctxt = svc_rdma_get_context(xprt); ctxt->direction = DMA_TO_DEVICE; ctxt->count = 1; ctxt->pages[0] = p; /* Prepare SGE for local address */ ctxt->sge[0].lkey = xprt->sc_pd->local_dma_lkey; ctxt->sge[0].length = length; ctxt->sge[0].addr = ib_dma_map_page(xprt->sc_cm_id->device, p, 0, length, DMA_TO_DEVICE); if (ib_dma_mapping_error(xprt->sc_cm_id->device, ctxt->sge[0].addr)) { dprintk("svcrdma: Error mapping buffer for protocol error\n"); svc_rdma_put_context(ctxt, 1); return; } svc_rdma_count_mappings(xprt, ctxt); /* Prepare SEND WR */ memset(&err_wr, 0, sizeof(err_wr)); ctxt->cqe.done = svc_rdma_wc_send; err_wr.wr_cqe = &ctxt->cqe; err_wr.sg_list = ctxt->sge; err_wr.num_sge = 1; err_wr.opcode = IB_WR_SEND; err_wr.send_flags = IB_SEND_SIGNALED; /* Post It */ ret = svc_rdma_send(xprt, &err_wr); if (ret) { dprintk("svcrdma: Error %d posting send for protocol error\n", ret); svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 1); } } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
void svc_rdma_send_error(struct svcxprt_rdma *xprt, struct rpcrdma_msg *rmsgp,
7,328
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.
Code: gss_process_context_token (minor_status, context_handle, token_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_process_context_token) { status = mech->gss_process_context_token( minor_status, ctx->internal_ctx_id, token_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415
gss_process_context_token (minor_status, context_handle, token_buffer) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if (token_buffer == GSS_C_NO_BUFFER) return (GSS_S_CALL_INACCESSIBLE_READ); if (GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_process_context_token) { status = mech->gss_process_context_token( minor_status, ctx->internal_ctx_id, token_buffer); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); }
5,952
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.
Code: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595 CWE ID: CWE-119
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(Cr_image,complex_images,Cr_image->rows,1L) #endif for (y=0; y < (ssize_t) Cr_image->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Cr_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Cr_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Cr_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Cr_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) Cr_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(Cr_image); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal((double) Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*((double) Ar[i]*Br[i]+(double) Ai[i]*Bi[i]); Ci[i]=gamma*((double) Ai[i]*Br[i]-(double) Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt((double) Ar[i]*Ar[i]+(double) Ai[i]*Ai[i]); Ci[i]=atan2((double) Ai[i],(double) Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*((double) Ar[i]*Br[i]-(double) Ai[i]*Bi[i]); Ci[i]=QuantumScale*((double) Ai[i]*Br[i]+(double) Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); }
4,275
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.
Code: PlatformTouchPoint::PlatformTouchPoint(const BlackBerry::Platform::TouchPoint& point) : m_id(point.m_id) , m_screenPos(point.m_screenPos) , m_pos(point.m_pos) { switch (point.m_state) { case BlackBerry::Platform::TouchPoint::TouchReleased: m_state = TouchReleased; break; case BlackBerry::Platform::TouchPoint::TouchMoved: m_state = TouchMoved; break; case BlackBerry::Platform::TouchPoint::TouchPressed: m_state = TouchPressed; break; case BlackBerry::Platform::TouchPoint::TouchStationary: m_state = TouchStationary; break; default: m_state = TouchStationary; // make sure m_state is initialized BLACKBERRY_ASSERT(false); break; } } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
PlatformTouchPoint::PlatformTouchPoint(const BlackBerry::Platform::TouchPoint& point) : m_id(point.id()) , m_screenPos(point.screenPosition()) // FIXME: We should be calculating a new viewport position from the current scroll // position and the documentContentPosition, in case we scrolled since the platform // event was created. , m_pos(point.documentViewportPosition()) { switch (point.state()) { case BlackBerry::Platform::TouchPoint::TouchReleased: m_state = TouchReleased; break; case BlackBerry::Platform::TouchPoint::TouchMoved: m_state = TouchMoved; break; case BlackBerry::Platform::TouchPoint::TouchPressed: m_state = TouchPressed; break; case BlackBerry::Platform::TouchPoint::TouchStationary: m_state = TouchStationary; break; default: m_state = TouchStationary; // make sure m_state is initialized BLACKBERRY_ASSERT(false); break; } }
1,431
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.
Code: void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) info->stats->requests_stats.emplace_back(job->url, need_preconnect); preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void PreconnectManager::FinishPreresolveJob(PreresolveJobId job_id, bool success) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); PreresolveJob* job = preresolve_jobs_.Lookup(job_id); DCHECK(job); bool need_preconnect = success && job->need_preconnect(); if (need_preconnect) { PreconnectUrl(job->url, job->num_sockets, job->allow_credentials, job->network_isolation_key); } PreresolveInfo* info = job->info; if (info) { info->stats->requests_stats.emplace_back(url::Origin::Create(job->url), need_preconnect); } preresolve_jobs_.Remove(job_id); --inflight_preresolves_count_; if (info) { DCHECK_LE(1u, info->inflight_count); --info->inflight_count; } if (info && info->is_done()) AllPreresolvesForUrlFinished(info); TryToLaunchPreresolveJobs(); }
25,511
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.
Code: void BrowserPpapiHostImpl::AddInstance( PP_Instance instance, const PepperRendererInstanceData& renderer_instance_data) { DCHECK(instance_map_.find(instance) == instance_map_.end()); instance_map_[instance] = base::MakeUnique<InstanceData>(renderer_instance_data); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void BrowserPpapiHostImpl::AddInstance( PP_Instance instance, const PepperRendererInstanceData& renderer_instance_data) { // NOTE: 'instance' may be coming from a compromised renderer process. We // take care here to make sure an attacker can't overwrite data for an // existing plugin instance. // See http://crbug.com/733548. if (instance_map_.find(instance) == instance_map_.end()) { instance_map_[instance] = base::MakeUnique<InstanceData>(renderer_instance_data); } else { NOTREACHED(); } }
24,598
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.
Code: void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); } Commit Message: CWE ID: CWE-320
void EC_GROUP_clear_free(EC_GROUP *group) { if (!group) return; if (group->meth->group_clear_finish != 0) group->meth->group_clear_finish(group); else if (group->meth->group_finish != 0) group->meth->group_finish(group); EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->generator != NULL) EC_EX_DATA_clear_free_all_data(&group->extra_data); if (group->mont_data) BN_MONT_CTX_free(group->mont_data); if (group->generator != NULL) EC_POINT_clear_free(group->generator); BN_clear_free(&group->order); OPENSSL_cleanse(group, sizeof *group); OPENSSL_free(group); }
26,305
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.
Code: bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); bool success = false; int timeout_ms = TestTimeouts::action_max_timeout_ms(); base::Time before_sending = base::Time::Now(); if (!SendAutomationJSONRequest( sender, request, timeout_ms, &reply, &success)) { int64 elapsed_ms = (base::Time::Now() - before_sending).InMilliseconds(); std::string command; request_dict.GetString("command", &command); if (elapsed_ms >= timeout_ms) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Request may have timed out. " "Elapsed time was %" PRId64 " ms. Request timeout was %d ms. " "Request details: (%s).", command.c_str(), elapsed_ms, timeout_ms, request.c_str()); } else { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), elapsed_ms, request.c_str()); } return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { std::string command; request_dict.GetString("command", &command); LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string command, error; request_dict.GetString("command", &command); dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool SendAutomationJSONRequest(AutomationMessageSender* sender, const DictionaryValue& request_dict, DictionaryValue* reply_dict, std::string* error_msg) { std::string request, reply; base::JSONWriter::Write(&request_dict, false, &request); std::string command; request_dict.GetString("command", &command); LOG(INFO) << "Sending '" << command << "' command."; base::Time before_sending = base::Time::Now(); bool success = false; if (!SendAutomationJSONRequestWithDefaultTimeout( sender, request, &reply, &success)) { *error_msg = base::StringPrintf( "Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. " "Request details: (%s).", command.c_str(), (base::Time::Now() - before_sending).InMilliseconds(), request.c_str()); return false; } scoped_ptr<Value> value(base::JSONReader::Read(reply, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { LOG(ERROR) << "JSON request did not return dict: " << command << "\n"; return false; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); if (!success) { std::string error; dict->GetString("error", &error); *error_msg = base::StringPrintf( "Internal Chrome error during '%s': (%s). Request details: (%s).", command.c_str(), error.c_str(), request.c_str()); LOG(ERROR) << "JSON request failed: " << command << "\n" << " with error: " << error; return false; } reply_dict->MergeDictionary(dict); return true; }
21,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.
Code: static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.optionsObject"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(Dictionary, oo, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); if (args.Length() > 0 && !oo.isUndefinedOrNull() && !oo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } if (args.Length() <= 1) { imp->optionsObject(oo); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(Dictionary, ooo, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); if (args.Length() > 1 && !ooo.isUndefinedOrNull() && !ooo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } imp->optionsObject(oo, ooo); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.optionsObject"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(Dictionary, oo, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)); if (args.Length() > 0 && !oo.isUndefinedOrNull() && !oo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } if (args.Length() <= 1) { imp->optionsObject(oo); return v8::Handle<v8::Value>(); } EXCEPTION_BLOCK(Dictionary, ooo, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)); if (args.Length() > 1 && !ooo.isUndefinedOrNull() && !ooo.isObject()) { return V8Proxy::throwTypeError("Not an object."); } imp->optionsObject(oo, ooo); return v8::Handle<v8::Value>(); }
29,230
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.
Code: bool IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { base::CStringTokenizer category_group_tokens( category_group_name, category_group_name + strlen(category_group_name), ","); while (category_group_tokens.GetNext()) { const std::string& category_group_token = category_group_tokens.token(); for (int i = 0; kEventArgsWhitelist[i][0] != NULL; ++i) { DCHECK(kEventArgsWhitelist[i][1]); if (base::MatchPattern(category_group_token.c_str(), kEventArgsWhitelist[i][0]) && base::MatchPattern(event_name, kEventArgsWhitelist[i][1])) { return true; } } } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, bool IsTraceArgumentNameWhitelisted(const char* const* granular_filter, const char* arg_name) { for (int i = 0; granular_filter[i] != nullptr; ++i) { if (base::MatchPattern(arg_name, granular_filter[i])) return true; } return false; } bool IsTraceEventArgsWhitelisted( const char* category_group_name, const char* event_name, base::trace_event::ArgumentNameFilterPredicate* arg_name_filter) { DCHECK(arg_name_filter); base::CStringTokenizer category_group_tokens( category_group_name, category_group_name + strlen(category_group_name), ","); while (category_group_tokens.GetNext()) { const std::string& category_group_token = category_group_tokens.token(); for (int i = 0; kEventArgsWhitelist[i].category_name != nullptr; ++i) { const WhitelistEntry& whitelist_entry = kEventArgsWhitelist[i]; DCHECK(whitelist_entry.event_name); if (base::MatchPattern(category_group_token.c_str(), whitelist_entry.category_name) && base::MatchPattern(event_name, whitelist_entry.event_name)) { if (whitelist_entry.arg_name_filter) { *arg_name_filter = base::Bind(&IsTraceArgumentNameWhitelisted, whitelist_entry.arg_name_filter); } return true; } } } return false; }
18,132
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.
Code: virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
virtual void SetUp() { FakeDBusThreadManager* fake_dbus_thread_manager = new FakeDBusThreadManager; fake_bluetooth_profile_manager_client_ = new FakeBluetoothProfileManagerClient; fake_dbus_thread_manager->SetBluetoothProfileManagerClient( scoped_ptr<BluetoothProfileManagerClient>( fake_bluetooth_profile_manager_client_)); fake_dbus_thread_manager->SetBluetoothAgentManagerClient( scoped_ptr<BluetoothAgentManagerClient>( new FakeBluetoothAgentManagerClient)); fake_dbus_thread_manager->SetBluetoothAdapterClient( scoped_ptr<BluetoothAdapterClient>(new FakeBluetoothAdapterClient)); fake_dbus_thread_manager->SetBluetoothDeviceClient( scoped_ptr<BluetoothDeviceClient>(new FakeBluetoothDeviceClient)); fake_dbus_thread_manager->SetBluetoothInputClient( scoped_ptr<BluetoothInputClient>(new FakeBluetoothInputClient)); DBusThreadManager::InitializeForTesting(fake_dbus_thread_manager); device::BluetoothAdapterFactory::GetAdapter( base::Bind(&BluetoothProfileChromeOSTest::AdapterCallback, base::Unretained(this))); ASSERT_TRUE(adapter_.get() != NULL); ASSERT_TRUE(adapter_->IsInitialized()); ASSERT_TRUE(adapter_->IsPresent()); adapter_->SetPowered( true, base::Bind(&base::DoNothing), base::Bind(&base::DoNothing)); ASSERT_TRUE(adapter_->IsPowered()); }
24,618
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.
Code: bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { return add_default_proxy_bypass_rules_; } Commit Message: Implicitly bypass localhost when proxying requests. This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox). Concretely: * localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy * link-local IP addresses implicitly bypass the proxy The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect). This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local). The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround. Bug: 413511, 899126, 901896 Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0 Reviewed-on: https://chromium-review.googlesource.com/c/1303626 Commit-Queue: Eric Roman <[email protected]> Reviewed-by: Dominick Ng <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Reviewed-by: Matt Menke <[email protected]> Reviewed-by: Sami Kyöstilä <[email protected]> Cr-Commit-Position: refs/heads/master@{#606112} CWE ID: CWE-20
bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const { void TestDataReductionProxyConfig::AddDefaultProxyBypassRules() { if (!add_default_proxy_bypass_rules_) { // Set bypass rules which allow proxying localhost. configurator_->SetBypassRules( net::ProxyBypassRules::GetRulesToSubtractImplicit()); } }
3,913
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.
Code: v8::Local<v8::Value> ModuleSystem::RequireForJsInner( v8::Local<v8::String> module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Object> global(context()->v8_context()->Global()); v8::Local<v8::Value> modules_value; if (!GetPrivate(global, kModulesField, &modules_value) || modules_value->IsUndefined()) { Warn(GetIsolate(), "Extension view no longer exists"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); v8::Local<v8::Value> exports; if (!GetProperty(v8_context, modules, module_name, &exports) || !exports->IsUndefined()) return handle_scope.Escape(exports); exports = LoadModule(*v8::String::Utf8Value(module_name)); SetProperty(v8_context, modules, module_name, exports); return handle_scope.Escape(exports); } Commit Message: [Extensions] Harden against bindings interception There's more we can do but this is a start. BUG=590275 BUG=590118 Review URL: https://codereview.chromium.org/1748943002 Cr-Commit-Position: refs/heads/master@{#378621} CWE ID: CWE-284
v8::Local<v8::Value> ModuleSystem::RequireForJsInner( v8::Local<v8::String> module_name) { v8::EscapableHandleScope handle_scope(GetIsolate()); v8::Local<v8::Context> v8_context = context()->v8_context(); v8::Context::Scope context_scope(v8_context); v8::Local<v8::Object> global(context()->v8_context()->Global()); v8::Local<v8::Value> modules_value; if (!GetPrivate(global, kModulesField, &modules_value) || modules_value->IsUndefined()) { Warn(GetIsolate(), "Extension view no longer exists"); return v8::Undefined(GetIsolate()); } v8::Local<v8::Object> modules(v8::Local<v8::Object>::Cast(modules_value)); v8::Local<v8::Value> exports; if (!GetPrivateProperty(v8_context, modules, module_name, &exports) || !exports->IsUndefined()) return handle_scope.Escape(exports); exports = LoadModule(*v8::String::Utf8Value(module_name)); SetPrivateProperty(v8_context, modules, module_name, exports); return handle_scope.Escape(exports); }
15,021
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.
Code: IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); } Commit Message: [IndexedDB] Fixing early destruction of connection during forceclose Patch is as small as possible for merging. Bug: 842990 Change-Id: I9968ffee1bf3279e61e1ec13e4d541f713caf12f Reviewed-on: https://chromium-review.googlesource.com/1062935 Commit-Queue: Daniel Murphy <[email protected]> Commit-Queue: Victor Costan <[email protected]> Reviewed-by: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#559383} CWE ID:
IndexedDBTransaction::IndexedDBTransaction( int64_t id, IndexedDBConnection* connection, const std::set<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode, IndexedDBBackingStore::Transaction* backing_store_transaction) : id_(id), object_store_ids_(object_store_ids), mode_(mode), connection_(connection->GetWeakPtr()), transaction_(backing_store_transaction), ptr_factory_(this) { IDB_ASYNC_TRACE_BEGIN("IndexedDBTransaction::lifetime", this); callbacks_ = connection_->callbacks(); database_ = connection_->database(); diagnostics_.tasks_scheduled = 0; diagnostics_.tasks_completed = 0; diagnostics_.creation_time = base::Time::Now(); }
15,082
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.
Code: ZSTD_compressSequences_internal(seqStore_t* seqStorePtr, ZSTD_entropyCTables_t const* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, ZSTD_CCtx_params const* cctxParams, void* dst, size_t dstCapacity, void* workspace, size_t wkspSize, const int bmi2) { const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN; ZSTD_strategy const strategy = cctxParams->cParams.strategy; U32 count[MaxSeq+1]; FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable; FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable; FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const seqDef* const sequences = seqStorePtr->sequencesStart; const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstCapacity; BYTE* op = ostart; size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart; BYTE* seqHead; BYTE* lastNCount = NULL; ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog))); /* Compress literals */ { const BYTE* const literals = seqStorePtr->litStart; size_t const litSize = seqStorePtr->lit - literals; int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0); size_t const cSize = ZSTD_compressLiterals( &prevEntropy->huf, &nextEntropy->huf, cctxParams->cParams.strategy, disableLiteralCompression, op, dstCapacity, literals, litSize, workspace, wkspSize, bmi2); if (ZSTD_isError(cSize)) return cSize; assert(cSize <= dstCapacity); op += cSize; } /* Sequences Header */ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall); if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3; if (nbSeq==0) { /* Copy the old tables over as if we repeated them */ memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse)); return op - ostart; } /* seqHead : flags for FSE encoding type */ seqHead = op++; /* convert length/distances into codes */ ZSTD_seqToCodes(seqStorePtr); /* build CTable for Literal Lengths */ { U32 max = MaxLL; size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building LL table"); nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode; LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode, count, max, mostFrequent, nbSeq, LLFSELog, prevEntropy->fse.litlengthCTable, LL_defaultNorm, LL_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(set_basic < set_compressed && set_rle < set_compressed); assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype, count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL, prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (LLtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for Offsets */ { U32 max = MaxOff; size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */ ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; DEBUGLOG(5, "Building OF table"); nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode; Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode, count, max, mostFrequent, nbSeq, OffFSELog, prevEntropy->fse.offcodeCTable, OF_defaultNorm, OF_defaultNormLog, defaultPolicy, strategy); assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype, count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff, prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (Offtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for MatchLengths */ { U32 max = MaxML; size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building ML table"); nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode; MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype, count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML, prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (MLtype == set_compressed) lastNCount = op; op += countSize; } } *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2)); { size_t const bitstreamSize = ZSTD_encodeSequences( op, oend - op, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets, bmi2); if (ZSTD_isError(bitstreamSize)) return bitstreamSize; op += bitstreamSize; /* zstd versions <= 1.3.4 mistakenly report corruption when * FSE_readNCount() recieves a buffer < 4 bytes. * Fixed by https://github.com/facebook/zstd/pull/1146. * This can happen when the last set_compressed table present is 2 * bytes and the bitstream is only one byte. * In this exceedingly rare case, we will simply emit an uncompressed * block, since it isn't worth optimizing. */ if (lastNCount && (op - lastNCount) < 4) { /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */ assert(op - lastNCount == 3); DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by " "emitting an uncompressed block."); return 0; } } return op - ostart; } Commit Message: fixed T36302429 CWE ID: CWE-362
ZSTD_compressSequences_internal(seqStore_t* seqStorePtr, ZSTD_entropyCTables_t const* prevEntropy, ZSTD_entropyCTables_t* nextEntropy, ZSTD_CCtx_params const* cctxParams, void* dst, size_t dstCapacity, void* workspace, size_t wkspSize, const int bmi2) { const int longOffsets = cctxParams->cParams.windowLog > STREAM_ACCUMULATOR_MIN; ZSTD_strategy const strategy = cctxParams->cParams.strategy; U32 count[MaxSeq+1]; FSE_CTable* CTable_LitLength = nextEntropy->fse.litlengthCTable; FSE_CTable* CTable_OffsetBits = nextEntropy->fse.offcodeCTable; FSE_CTable* CTable_MatchLength = nextEntropy->fse.matchlengthCTable; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const seqDef* const sequences = seqStorePtr->sequencesStart; const BYTE* const ofCodeTable = seqStorePtr->ofCode; const BYTE* const llCodeTable = seqStorePtr->llCode; const BYTE* const mlCodeTable = seqStorePtr->mlCode; BYTE* const ostart = (BYTE*)dst; BYTE* const oend = ostart + dstCapacity; BYTE* op = ostart; size_t const nbSeq = seqStorePtr->sequences - seqStorePtr->sequencesStart; BYTE* seqHead; BYTE* lastNCount = NULL; ZSTD_STATIC_ASSERT(HUF_WORKSPACE_SIZE >= (1<<MAX(MLFSELog,LLFSELog))); /* Compress literals */ { const BYTE* const literals = seqStorePtr->litStart; size_t const litSize = seqStorePtr->lit - literals; int const disableLiteralCompression = (cctxParams->cParams.strategy == ZSTD_fast) && (cctxParams->cParams.targetLength > 0); size_t const cSize = ZSTD_compressLiterals( &prevEntropy->huf, &nextEntropy->huf, cctxParams->cParams.strategy, disableLiteralCompression, op, dstCapacity, literals, litSize, workspace, wkspSize, bmi2); if (ZSTD_isError(cSize)) return cSize; assert(cSize <= dstCapacity); op += cSize; } /* Sequences Header */ if ((oend-op) < 3 /*max nbSeq Size*/ + 1 /*seqHead*/) return ERROR(dstSize_tooSmall); if (nbSeq < 0x7F) *op++ = (BYTE)nbSeq; else if (nbSeq < LONGNBSEQ) op[0] = (BYTE)((nbSeq>>8) + 0x80), op[1] = (BYTE)nbSeq, op+=2; else op[0]=0xFF, MEM_writeLE16(op+1, (U16)(nbSeq - LONGNBSEQ)), op+=3; if (nbSeq==0) { /* Copy the old tables over as if we repeated them */ memcpy(&nextEntropy->fse, &prevEntropy->fse, sizeof(prevEntropy->fse)); return op - ostart; } /* seqHead : flags for FSE encoding type */ seqHead = op++; /* convert length/distances into codes */ ZSTD_seqToCodes(seqStorePtr); /* build CTable for Literal Lengths */ { U32 max = MaxLL; size_t const mostFrequent = HIST_countFast_wksp(count, &max, llCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building LL table"); nextEntropy->fse.litlength_repeatMode = prevEntropy->fse.litlength_repeatMode; LLtype = ZSTD_selectEncodingType(&nextEntropy->fse.litlength_repeatMode, count, max, mostFrequent, nbSeq, LLFSELog, prevEntropy->fse.litlengthCTable, LL_defaultNorm, LL_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(set_basic < set_compressed && set_rle < set_compressed); assert(!(LLtype < set_compressed && nextEntropy->fse.litlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_LitLength, LLFSELog, (symbolEncodingType_e)LLtype, count, max, llCodeTable, nbSeq, LL_defaultNorm, LL_defaultNormLog, MaxLL, prevEntropy->fse.litlengthCTable, sizeof(prevEntropy->fse.litlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (LLtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for Offsets */ { U32 max = MaxOff; size_t const mostFrequent = HIST_countFast_wksp(count, &max, ofCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ /* We can only use the basic table if max <= DefaultMaxOff, otherwise the offsets are too large */ ZSTD_defaultPolicy_e const defaultPolicy = (max <= DefaultMaxOff) ? ZSTD_defaultAllowed : ZSTD_defaultDisallowed; DEBUGLOG(5, "Building OF table"); nextEntropy->fse.offcode_repeatMode = prevEntropy->fse.offcode_repeatMode; Offtype = ZSTD_selectEncodingType(&nextEntropy->fse.offcode_repeatMode, count, max, mostFrequent, nbSeq, OffFSELog, prevEntropy->fse.offcodeCTable, OF_defaultNorm, OF_defaultNormLog, defaultPolicy, strategy); assert(!(Offtype < set_compressed && nextEntropy->fse.offcode_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_OffsetBits, OffFSELog, (symbolEncodingType_e)Offtype, count, max, ofCodeTable, nbSeq, OF_defaultNorm, OF_defaultNormLog, DefaultMaxOff, prevEntropy->fse.offcodeCTable, sizeof(prevEntropy->fse.offcodeCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (Offtype == set_compressed) lastNCount = op; op += countSize; } } /* build CTable for MatchLengths */ { U32 max = MaxML; size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ DEBUGLOG(5, "Building ML table (remaining space : %i)", (int)(oend-op)); nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode; MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy); assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */ { size_t const countSize = ZSTD_buildCTable(op, oend - op, CTable_MatchLength, MLFSELog, (symbolEncodingType_e)MLtype, count, max, mlCodeTable, nbSeq, ML_defaultNorm, ML_defaultNormLog, MaxML, prevEntropy->fse.matchlengthCTable, sizeof(prevEntropy->fse.matchlengthCTable), workspace, wkspSize); if (ZSTD_isError(countSize)) return countSize; if (MLtype == set_compressed) lastNCount = op; op += countSize; } } *seqHead = (BYTE)((LLtype<<6) + (Offtype<<4) + (MLtype<<2)); { size_t const bitstreamSize = ZSTD_encodeSequences( op, oend - op, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets, bmi2); if (ZSTD_isError(bitstreamSize)) return bitstreamSize; op += bitstreamSize; /* zstd versions <= 1.3.4 mistakenly report corruption when * FSE_readNCount() recieves a buffer < 4 bytes. * Fixed by https://github.com/facebook/zstd/pull/1146. * This can happen when the last set_compressed table present is 2 * bytes and the bitstream is only one byte. * In this exceedingly rare case, we will simply emit an uncompressed * block, since it isn't worth optimizing. */ if (lastNCount && (op - lastNCount) < 4) { /* NCountSize >= 2 && bitstreamSize > 0 ==> lastCountSize == 3 */ assert(op - lastNCount == 3); DEBUGLOG(5, "Avoiding bug in zstd decoder in versions <= 1.3.4 by " "emitting an uncompressed block."); return 0; } } return op - ostart; }
3,737
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.
Code: PlatformSensorLinux::PlatformSensorLinux( mojom::SensorType type, mojo::ScopedSharedBufferMapping mapping, PlatformSensorProvider* provider, const SensorInfoLinux* sensor_device, scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner) : PlatformSensor(type, std::move(mapping), provider), default_configuration_( PlatformSensorConfiguration(sensor_device->device_frequency)), reporting_mode_(sensor_device->reporting_mode), polling_thread_task_runner_(std::move(polling_thread_task_runner)), weak_factory_(this) { sensor_reader_ = SensorReader::Create( sensor_device, weak_factory_.GetWeakPtr(), task_runner_); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732
PlatformSensorLinux::PlatformSensorLinux( mojom::SensorType type, SensorReadingSharedBuffer* reading_buffer, PlatformSensorProvider* provider, const SensorInfoLinux* sensor_device, scoped_refptr<base::SingleThreadTaskRunner> polling_thread_task_runner) : PlatformSensor(type, reading_buffer, provider), default_configuration_( PlatformSensorConfiguration(sensor_device->device_frequency)), reporting_mode_(sensor_device->reporting_mode), polling_thread_task_runner_(std::move(polling_thread_task_runner)), weak_factory_(this) { sensor_reader_ = SensorReader::Create( sensor_device, weak_factory_.GetWeakPtr(), task_runner_); }
28,723
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.
Code: MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; return(data); } Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43 CWE ID: CWE-416
MagickExport unsigned char *DetachBlob(BlobInfo *blob_info) { unsigned char *data; assert(blob_info != (BlobInfo *) NULL); if (blob_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (blob_info->mapped != MagickFalse) { (void) UnmapBlob(blob_info->data,blob_info->length); blob_info->data=NULL; RelinquishMagickResource(MapResource,blob_info->length); } blob_info->mapped=MagickFalse; blob_info->length=0; blob_info->offset=0; blob_info->eof=MagickFalse; blob_info->error=0; blob_info->exempt=MagickFalse; blob_info->type=UndefinedStream; blob_info->file_info.file=(FILE *) NULL; data=blob_info->data; blob_info->data=(unsigned char *) NULL; blob_info->stream=(StreamHandler) NULL; return(data); }
4,071
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.
Code: static void cliRefreshPrompt(void) { int len; if (config.eval_ldb) return; if (config.hostsocket != NULL) len = snprintf(config.prompt,sizeof(config.prompt),"redis %s", config.hostsocket); else len = anetFormatAddr(config.prompt, sizeof(config.prompt), config.hostip, config.hostport); /* Add [dbnum] if needed */ if (config.dbnum != 0) len += snprintf(config.prompt+len,sizeof(config.prompt)-len,"[%d]", config.dbnum); snprintf(config.prompt+len,sizeof(config.prompt)-len,"> "); } Commit Message: Security: fix redis-cli buffer overflow. Thanks to Fakhri Zulkifli for reporting it. The fix switched to dynamic allocation, copying the final prompt in the static buffer only at the end. CWE ID: CWE-119
static void cliRefreshPrompt(void) { if (config.eval_ldb) return; sds prompt = sdsempty(); if (config.hostsocket != NULL) { prompt = sdscatfmt(prompt,"redis %s",config.hostsocket); } else { char addr[256]; anetFormatAddr(addr, sizeof(addr), config.hostip, config.hostport); prompt = sdscatlen(prompt,addr,strlen(addr)); } /* Add [dbnum] if needed */ if (config.dbnum != 0) prompt = sdscatfmt(prompt,"[%i]",config.dbnum); /* Copy the prompt in the static buffer. */ prompt = sdscatlen(prompt,"> ",2); snprintf(config.prompt,sizeof(config.prompt),"%s",prompt); sdsfree(prompt); }
22,449
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.
Code: static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); }
19,989
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.
Code: int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; int ret; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) return -EPERM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) return -ENOMEM; ret = proc_alloc_inum(&ns->proc_inum); if (ret) { kmem_cache_free(user_ns_cachep, ns); return ret; } atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->owner = owner; ns->group = group; set_cred_user_ns(new, ns); return 0; } Commit Message: userns: Don't allow creation if the user is chrooted Guarantee that the policy of which files may be access that is established by setting the root directory will not be violated by user namespaces by verifying that the root directory points to the root of the mount namespace at the time of user namespace creation. Changing the root is a privileged operation, and as a matter of policy it serves to limit unprivileged processes to files below the current root directory. For reasons of simplicity and comprehensibility the privilege to change the root directory is gated solely on the CAP_SYS_CHROOT capability in the user namespace. Therefore when creating a user namespace we must ensure that the policy of which files may be access can not be violated by changing the root directory. Anyone who runs a processes in a chroot and would like to use user namespace can setup the same view of filesystems with a mount namespace instead. With this result that this is not a practical limitation for using user namespaces. Cc: [email protected] Acked-by: Serge Hallyn <[email protected]> Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-264
int create_user_ns(struct cred *new) { struct user_namespace *ns, *parent_ns = new->user_ns; kuid_t owner = new->euid; kgid_t group = new->egid; int ret; /* * Verify that we can not violate the policy of which files * may be accessed that is specified by the root directory, * by verifing that the root directory is at the root of the * mount namespace which allows all files to be accessed. */ if (current_chrooted()) return -EPERM; /* The creator needs a mapping in the parent user namespace * or else we won't be able to reasonably tell userspace who * created a user_namespace. */ if (!kuid_has_mapping(parent_ns, owner) || !kgid_has_mapping(parent_ns, group)) return -EPERM; ns = kmem_cache_zalloc(user_ns_cachep, GFP_KERNEL); if (!ns) return -ENOMEM; ret = proc_alloc_inum(&ns->proc_inum); if (ret) { kmem_cache_free(user_ns_cachep, ns); return ret; } atomic_set(&ns->count, 1); /* Leave the new->user_ns reference with the new user namespace. */ ns->parent = parent_ns; ns->owner = owner; ns->group = group; set_cred_user_ns(new, ns); return 0; }
10,237
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.
Code: void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { nsc_encode_argb_to_aycocg(context, bmpdata, rowstride); if (context->ChromaSubsamplingLevel) { nsc_encode_subsampling(context); } } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
void nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) BOOL nsc_encode(NSC_CONTEXT* context, const BYTE* bmpdata, UINT32 rowstride) { if (!context || !bmpdata || (rowstride == 0)) return FALSE; if (!nsc_encode_argb_to_aycocg(context, bmpdata, rowstride)) return FALSE; if (context->ChromaSubsamplingLevel) { if (!nsc_encode_subsampling(context)) return FALSE; } return TRUE; }
17,113
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.
Code: print_ipcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ipcpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ipcpopt_values,"unknown",opt), opt, len)); switch (opt) { case IPCPOPT_2ADDR: /* deprecated */ if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 6), 4); ND_PRINT((ndo, ": src %s, dst %s", ipaddr_string(ndo, p + 2), ipaddr_string(ndo, p + 6))); break; case IPCPOPT_IPCOMP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK2(*(p + 2), 2); compproto = EXTRACT_16BITS(p+2); ND_PRINT((ndo, ": %s (0x%02x):", tok2str(ipcpopt_compproto_values, "Unknown", compproto), compproto)); switch (compproto) { case PPP_VJC: /* XXX: VJ-Comp parameters should be decoded */ break; case IPCPOPT_IPCOMP_HDRCOMP: if (len < IPCPOPT_IPCOMP_MINLEN) { ND_PRINT((ndo, " (length bogus, should be >= %u)", IPCPOPT_IPCOMP_MINLEN)); return 0; } ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN); ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \ ", maxPeriod %u, maxTime %u, maxHdr %u", EXTRACT_16BITS(p+4), EXTRACT_16BITS(p+6), EXTRACT_16BITS(p+8), EXTRACT_16BITS(p+10), EXTRACT_16BITS(p+12))); /* suboptions present ? */ if (len > IPCPOPT_IPCOMP_MINLEN) { ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN; p += IPCPOPT_IPCOMP_MINLEN; ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen)); while (ipcomp_subopttotallen >= 2) { ND_TCHECK2(*p, 2); ipcomp_subopt = *p; ipcomp_suboptlen = *(p+1); /* sanity check */ if (ipcomp_subopt == 0 || ipcomp_suboptlen == 0 ) break; /* XXX: just display the suboptions for now */ ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u", tok2str(ipcpopt_compproto_subopt_values, "Unknown", ipcomp_subopt), ipcomp_subopt, ipcomp_suboptlen)); ipcomp_subopttotallen -= ipcomp_suboptlen; p += ipcomp_suboptlen; } } break; default: break; } break; case IPCPOPT_ADDR: /* those options share the same format - fall through */ case IPCPOPT_MOBILE4: case IPCPOPT_PRIDNS: case IPCPOPT_PRINBNS: case IPCPOPT_SECDNS: case IPCPOPT_SECNBNS: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ipcp]")); return 0; } Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks. For configuration protocol options, use ND_TCHECK() and ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument. This fixes one case where the ND_TCHECK2() call they replace was not checking enough bytes. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
print_ipcp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; u_int compproto, ipcomp_subopttotallen, ipcomp_subopt, ipcomp_suboptlen; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ipcpopt_values,"unknown",opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ipcpopt_values,"unknown",opt), opt, len)); switch (opt) { case IPCPOPT_2ADDR: /* deprecated */ if (len != 10) { ND_PRINT((ndo, " (length bogus, should be = 10)")); return len; } ND_TCHECK2(*(p + 6), 4); ND_PRINT((ndo, ": src %s, dst %s", ipaddr_string(ndo, p + 2), ipaddr_string(ndo, p + 6))); break; case IPCPOPT_IPCOMP: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return 0; } ND_TCHECK_16BITS(p+2); compproto = EXTRACT_16BITS(p+2); ND_PRINT((ndo, ": %s (0x%02x):", tok2str(ipcpopt_compproto_values, "Unknown", compproto), compproto)); switch (compproto) { case PPP_VJC: /* XXX: VJ-Comp parameters should be decoded */ break; case IPCPOPT_IPCOMP_HDRCOMP: if (len < IPCPOPT_IPCOMP_MINLEN) { ND_PRINT((ndo, " (length bogus, should be >= %u)", IPCPOPT_IPCOMP_MINLEN)); return 0; } ND_TCHECK2(*(p + 2), IPCPOPT_IPCOMP_MINLEN); ND_PRINT((ndo, "\n\t TCP Space %u, non-TCP Space %u" \ ", maxPeriod %u, maxTime %u, maxHdr %u", EXTRACT_16BITS(p+4), EXTRACT_16BITS(p+6), EXTRACT_16BITS(p+8), EXTRACT_16BITS(p+10), EXTRACT_16BITS(p+12))); /* suboptions present ? */ if (len > IPCPOPT_IPCOMP_MINLEN) { ipcomp_subopttotallen = len - IPCPOPT_IPCOMP_MINLEN; p += IPCPOPT_IPCOMP_MINLEN; ND_PRINT((ndo, "\n\t Suboptions, length %u", ipcomp_subopttotallen)); while (ipcomp_subopttotallen >= 2) { ND_TCHECK2(*p, 2); ipcomp_subopt = *p; ipcomp_suboptlen = *(p+1); /* sanity check */ if (ipcomp_subopt == 0 || ipcomp_suboptlen == 0 ) break; /* XXX: just display the suboptions for now */ ND_PRINT((ndo, "\n\t\t%s Suboption #%u, length %u", tok2str(ipcpopt_compproto_subopt_values, "Unknown", ipcomp_subopt), ipcomp_subopt, ipcomp_suboptlen)); ipcomp_subopttotallen -= ipcomp_suboptlen; p += ipcomp_suboptlen; } } break; default: break; } break; case IPCPOPT_ADDR: /* those options share the same format - fall through */ case IPCPOPT_MOBILE4: case IPCPOPT_PRIDNS: case IPCPOPT_PRINBNS: case IPCPOPT_SECDNS: case IPCPOPT_SECNBNS: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return 0; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": %s", ipaddr_string(ndo, p + 2))); break; default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ipcp]")); return 0; }
25,950
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.
Code: void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) { l->append("<SkBitmap>"); } Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices. Using memcpy() to serialize a POD struct is highly discouraged. Just use the standard IPC param traits macros for doing it. Bug: 779428 Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334 Reviewed-on: https://chromium-review.googlesource.com/899649 Reviewed-by: Tom Sepez <[email protected]> Commit-Queue: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#534562} CWE ID: CWE-125
void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) { l->append("<SkBitmap>"); LogParam(p.info(), l); }
15,475
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.
Code: void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_item_->RemoveObserver(this); std::string name = base::UTF16ToUTF8(folder_name_view_->text()); delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); } Commit Message: Enforce the maximum length of the folder name in UI. BUG=355797 [email protected] Review URL: https://codereview.chromium.org/203863005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void FolderHeaderView::ContentsChanged(views::Textfield* sender, const base::string16& new_contents) { if (!folder_item_) return; folder_name_view_->Update(); folder_item_->RemoveObserver(this); // Enforce the maximum folder name length in UI. std::string name = base::UTF16ToUTF8( folder_name_view_->text().substr(0, kMaxFolderNameChars)); if (name != folder_item_->name()) delegate_->SetItemName(folder_item_, name); folder_item_->AddObserver(this); Layout(); }
3,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.
Code: Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } } Commit Message: CWE ID: CWE-20
Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, PDFRectangle *box, PDFRectangle *cropBox, GBool (*abortCheckCbkA)(void *data), void *abortCheckCbkDataA) #ifdef USE_CMS : iccColorSpaceCache(5) #endif { int i; xref = xrefA; catalog = catalogA; subPage = gTrue; printCommands = globalParams->getPrintCommands(); profileCommands = globalParams->getProfileCommands(); textHaveCSPattern = gFalse; drawText = gFalse; drawText = gFalse; maskHaveCSPattern = gFalse; mcStack = NULL; parser = NULL; res = new GfxResources(xref, resDict, NULL); out = outA; state = new GfxState(72, 72, box, 0, gFalse); stackHeight = 1; pushStateGuard(); fontChanged = gFalse; clip = clipNone; ignoreUndef = 0; for (i = 0; i < 6; ++i) { baseMatrix[i] = state->getCTM()[i]; } formDepth = 0; abortCheckCbk = abortCheckCbkA; abortCheckCbkData = abortCheckCbkDataA; if (cropBox) { state->moveTo(cropBox->x1, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y1); state->lineTo(cropBox->x2, cropBox->y2); state->lineTo(cropBox->x1, cropBox->y2); state->closePath(); state->clip(); out->clip(state); state->clearPath(); } }
21,248
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.
Code: jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; } Commit Message: Fixed a bug that resulted in the destruction of JP2 box data that had never been constructed in the first place. CWE ID: CWE-476
jp2_box_t *jp2_box_get(jas_stream_t *in) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; jas_stream_t *tmpstream; uint_fast32_t len; uint_fast64_t extlen; bool dataflag; box = 0; tmpstream = 0; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { goto error; } box->ops = &jp2_boxinfo_unk.ops; if (jp2_getuint32(in, &len) || jp2_getuint32(in, &box->type)) { goto error; } boxinfo = jp2_boxinfolookup(box->type); box->info = boxinfo; box->ops = &boxinfo->ops; box->len = len; JAS_DBGLOG(10, ( "preliminary processing of JP2 box: type=%c%s%c (0x%08x); length=%d\n", '"', boxinfo->name, '"', box->type, box->len )); if (box->len == 1) { if (jp2_getuint64(in, &extlen)) { goto error; } if (extlen > 0xffffffffUL) { jas_eprintf("warning: cannot handle large 64-bit box length\n"); extlen = 0xffffffffUL; } box->len = extlen; box->datalen = extlen - JP2_BOX_HDRLEN(true); } else { box->datalen = box->len - JP2_BOX_HDRLEN(false); } if (box->len != 0 && box->len < 8) { goto error; } dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_copy(tmpstream, in, box->datalen)) { // Mark the box data as never having been constructed // so that we will not errantly attempt to destroy it later. box->ops = &jp2_boxinfo_unk.ops; jas_eprintf("cannot copy box data\n"); goto error; } jas_stream_rewind(tmpstream); if (box->ops->getdata) { if ((*box->ops->getdata)(box, tmpstream)) { jas_eprintf("cannot parse box data\n"); goto error; } } jas_stream_close(tmpstream); } if (jas_getdbglevel() >= 1) { jp2_box_dump(box, stderr); } return box; error: if (box) { jp2_box_destroy(box); } if (tmpstream) { jas_stream_close(tmpstream); } return 0; }
26,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.
Code: void MediaElementAudioSourceHandler::OnCurrentSrcChanged( const KURL& current_src) { DCHECK(IsMainThread()); Locker<MediaElementAudioSourceHandler> locker(*this); passes_current_src_cors_access_check_ = PassesCurrentSrcCORSAccessCheck(current_src); maybe_print_cors_message_ = !passes_current_src_cors_access_check_; current_src_string_ = current_src.GetString(); } 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
void MediaElementAudioSourceHandler::OnCurrentSrcChanged( bool MediaElementAudioSourceHandler::WouldTaintOrigin() { // If we're cross-origin and allowed access vie CORS, we're not tainted. if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } // Handles the case where the url is a redirect to another site that we're not // allowed to access. if (!MediaElement()->HasSingleSecurityOrigin()) { return true; }
6,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.
Code: ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } 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
ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingOverflowBubble()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; }
5,509
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.
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; // Don't load any DLLs that end with the pk3 extension if (COM_CompareExtension(name, ".pk3")) { Com_Printf("Rejecting DLL named \"%s\"", name); return NULL; } if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; }
20,195
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.
Code: static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages) { unsigned long i; for (i = 0; i < npages; ++i) kvm_release_pfn_clean(pfn + i); } Commit Message: kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601) The third parameter of kvm_iommu_put_pages is wrong, It should be 'gfn - slot->base_gfn'. By making gfn very large, malicious guest or userspace can cause kvm to go to this error path, and subsequently to pass a huge value as size. Alternatively if gfn is small, then pages would be pinned but never unpinned, causing host memory leak and local DOS. Passing a reasonable but large value could be the most dangerous case, because it would unpin a page that should have stayed pinned, and thus allow the device to DMA into arbitrary memory. However, this cannot happen because of the condition that can trigger the error: - out of memory (where you can't allocate even a single page) should not be possible for the attacker to trigger - when exceeding the iommu's address space, guest pages after gfn will also exceed the iommu's address space, and inside kvm_iommu_put_pages() the iommu_iova_to_phys() will fail. The page thus would not be unpinned at all. Reported-by: Jack Morgenstein <[email protected]> Cc: [email protected] Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-189
static void kvm_unpin_pages(struct kvm *kvm, pfn_t pfn, unsigned long npages)
16,646
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.
Code: VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); XMP_Uns32 width = ((bitstream[7] << 8) | bitstream[6]) & 0x3fff; XMP_Uns32 height = ((bitstream[9] << 8) | bitstream[8]) & 0x3fff; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } } Commit Message: CWE ID: CWE-476
VP8XChunk::VP8XChunk(Container* parent) : Chunk(parent, kChunk_VP8X) { this->needsRewrite = true; this->size = 10; this->data.resize(this->size); this->data.assign(this->size, 0); XMP_Uns8* bitstream = (XMP_Uns8*)parent->chunks[WEBP_CHUNK_IMAGE][0]->data.data(); // See bug https://bugs.freedesktop.org/show_bug.cgi?id=105247 // bitstream could be NULL. XMP_Uns32 width = bitstream ? ((bitstream[7] << 8) | bitstream[6]) & 0x3fff : 0; XMP_Uns32 height = bitstream ? ((bitstream[9] << 8) | bitstream[8]) & 0x3fff : 0; this->width(width); this->height(height); parent->vp8x = this; VP8XChunk::VP8XChunk(Container* parent, WEBP_MetaHandler* handler) : Chunk(parent, handler) { this->size = 10; this->needsRewrite = true; parent->vp8x = this; } XMP_Uns32 VP8XChunk::width() { return GetLE24(&this->data[4]) + 1; } void VP8XChunk::width(XMP_Uns32 val) { PutLE24(&this->data[4], val > 0 ? val - 1 : 0); } XMP_Uns32 VP8XChunk::height() { return GetLE24(&this->data[7]) + 1; } void VP8XChunk::height(XMP_Uns32 val) { PutLE24(&this->data[7], val > 0 ? val - 1 : 0); } bool VP8XChunk::xmp() { XMP_Uns32 flags = GetLE32(&this->data[0]); return (bool)((flags >> XMP_FLAG_BIT) & 1); } void VP8XChunk::xmp(bool hasXMP) { XMP_Uns32 flags = GetLE32(&this->data[0]); flags ^= (-hasXMP ^ flags) & (1 << XMP_FLAG_BIT); PutLE32(&this->data[0], flags); } Container::Container(WEBP_MetaHandler* handler) : Chunk(NULL, handler) { this->needsRewrite = false; XMP_IO* file = handler->parent->ioRef; file->Seek(12, kXMP_SeekFromStart); XMP_Int64 size = handler->initialFileSize; XMP_Uns32 peek = 0; while (file->Offset() < size) { peek = XIO::PeekUns32_LE(file); switch (peek) { case kChunk_XMP_: this->addChunk(new XMPChunk(this, handler)); break; case kChunk_VP8X: this->addChunk(new VP8XChunk(this, handler)); break; default: this->addChunk(new Chunk(this, handler)); break; } } if (this->chunks[WEBP_CHUNK_IMAGE].size() == 0) { XMP_Throw("File has no image bitstream", kXMPErr_BadFileFormat); } if (this->chunks[WEBP_CHUNK_VP8X].size() == 0) { this->needsRewrite = true; this->addChunk(new VP8XChunk(this)); } if (this->chunks[WEBP_CHUNK_XMP].size() == 0) { XMPChunk* xmpChunk = new XMPChunk(this); this->addChunk(xmpChunk); handler->xmpChunk = xmpChunk; this->vp8x->xmp(true); } } Chunk* Container::getExifChunk() { if (this->chunks[WEBP::WEBP_CHUNK_EXIF].size() == 0) { return NULL; } return this->chunks[WEBP::WEBP_CHUNK_EXIF][0]; } void Container::addChunk(Chunk* chunk) { ChunkId idx; try { idx = chunkMap.at(chunk->tag); } catch (const std::out_of_range& e) { idx = WEBP_CHUNK_UNKNOWN; } this->chunks[idx].push_back(chunk); } void Container::write(WEBP_MetaHandler* handler) { XMP_IO* file = handler->parent->ioRef; file->Rewind(); XIO::WriteUns32_LE(file, this->tag); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); XIO::WriteUns32_LE(file, kChunk_WEBP); size_t i, j; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; for (j = 0; j < chunkVect.size(); j++) { chunkVect.at(j)->write(handler); } } XMP_Int64 lastOffset = file->Offset(); this->size = lastOffset - 8; file->Seek(this->pos + 4, kXMP_SeekFromStart); XIO::WriteUns32_LE(file, (XMP_Uns32) this->size); file->Seek(lastOffset, kXMP_SeekFromStart); if (lastOffset < handler->initialFileSize) { file->Truncate(lastOffset); } } Container::~Container() { Chunk* chunk; size_t i; std::vector<Chunk*> chunkVect; for (i = 0; i < WEBP_CHUNK_NIL; i++) { chunkVect = this->chunks[i]; while (!chunkVect.empty()) { chunk = chunkVect.back(); delete chunk; chunkVect.pop_back(); } } } }
16,217
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.
Code: static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/549 CWE ID: CWE-770
static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); chunk=(unsigned char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | (p[6] << 8) | p[7]); if ((jng_width == 0) || (jng_height == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif if (length != 0) chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); (void) CopyMagickMemory(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if (image_info->ping == MagickFalse) { if (jng_color_type >= 12) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1, &image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange- GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); }
15,664
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.
Code: static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) { const char *userid = rock->userid; int isadmin = rock->isadmin; int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); char inbox[MAX_MAILBOX_BUFFER]; size_t inboxlen = 0; size_t prefixlen, len; size_t domainlen = 0; size_t userlen = userid ? strlen(userid) : 0; char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ char commonpat[MAX_MAILBOX_BUFFER]; int r = 0; int i; const char *p; if (patterns->count < 1) return 0; /* nothing to do */ for (i = 0; i < patterns->count; i++) { glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); ptrarray_append(&rock->globs, g); } if (config_virtdomains && userid && (p = strchr(userid, '@'))) { userlen = p - userid; domainlen = strlen(p); /* includes separator */ snprintf(domainpat, sizeof(domainpat), "%s!", p+1); } else domainpat[0] = '\0'; /* calculate the inbox (with trailing .INBOX. for later use) */ if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || ((p - userid) > (int)userlen)) && strlen(userid)+7 < MAX_MAILBOX_BUFFER) { char *t, *tmpuser = NULL; const char *inboxuser; if (domainlen) snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1); if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { tmpuser = xmalloc(userlen); memcpy(tmpuser, userid, userlen); t = tmpuser + (p - userid); while(t < (tmpuser + userlen)) { if (*t == '.') *t = '^'; t++; } inboxuser = tmpuser; } else inboxuser = userid; snprintf(inbox+domainlen, sizeof(inbox)-domainlen, "user.%.*s.INBOX.", (int)userlen, inboxuser); free(tmpuser); inboxlen = strlen(inbox) - 7; } else { userid = 0; } /* Find the common search prefix of all patterns */ const char *firstpat = strarray_nth(patterns, 0); for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { if (prefixlen >= MAX_MAILBOX_NAME) { r = IMAP_MAILBOX_BADNAME; goto done; } char c = firstpat[prefixlen]; for (i = 1; i < patterns->count; i++) { const char *pat = strarray_nth(patterns, i); if (pat[prefixlen] != c) break; } if (i < patterns->count) break; if (c == '*' || c == '%' || c == '?') break; commonpat[prefixlen] = c; } commonpat[prefixlen] = '\0'; if (patterns->count == 1) { /* Skip pattern which matches shared namespace prefix */ if (!strcmp(firstpat+prefixlen, "%")) rock->singlepercent = 2; /* output prefix regardless */ if (!strcmp(firstpat+prefixlen, "*%")) rock->singlepercent = 1; } /* * Personal (INBOX) namespace (only if not admin) */ if (userid && !isadmin) { /* first the INBOX */ rock->mb_category = MBNAME_INBOX; r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; if (rock->namespace->isalt) { /* do exact INBOX subs before resetting the namebuffer */ rock->mb_category = MBNAME_INBOXSUB; r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; } /* iterate through all the mailboxes under the user's inbox */ rock->mb_category = MBNAME_OWNER; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* "Alt Prefix" folders */ if (rock->namespace->isalt) { /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; rock->mb_category = MBNAME_ALTINBOX; /* special case user.foo.INBOX. If we're singlepercent == 2, this could return DONE, in which case we don't need to foreach the rest of the altprefix space */ r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) goto skipalt; if (r) goto done; /* special case any other altprefix stuff */ rock->mb_category = MBNAME_ALTPREFIX; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); skipalt: /* we got a done, so skip out of the foreach early */ if (r == CYRUSDB_DONE) r = 0; if (r) goto done; } } /* * Other Users namespace * * If "Other Users*" can match pattern, search for those mailboxes next */ if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { len = strlen(rock->namespace->prefix[NAMESPACE_USER]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { if (prefixlen < len) { /* we match all users */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); } else { /* just those in this prefix */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); } rock->mb_category = MBNAME_OTHERUSER; /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; r = mboxlist_find_category(rock, domainpat, thislen); if (r) goto done; } } /* * Shared namespace * * search for all remaining mailboxes. * just bother looking at the ones that have the same pattern prefix. */ if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { rock->mb_category = MBNAME_SHARED; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; /* iterate through all the non-user folders on the server */ r = mboxlist_find_category(rock, domainpat, domainlen); if (r) goto done; } } /* finish with a reset call always */ r = (*rock->proc)(NULL, rock->procrock); done: for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); glob_free(&g); } ptrarray_fini(&rock->globs); return r; } Commit Message: mboxlist: fix uninitialised memory use where pattern is "Other Users" CWE ID: CWE-20
static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) { const char *userid = rock->userid; int isadmin = rock->isadmin; int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); char inbox[MAX_MAILBOX_BUFFER]; size_t inboxlen = 0; size_t prefixlen, len; size_t domainlen = 0; size_t userlen = userid ? strlen(userid) : 0; char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ char commonpat[MAX_MAILBOX_BUFFER]; int r = 0; int i; const char *p; if (patterns->count < 1) return 0; /* nothing to do */ for (i = 0; i < patterns->count; i++) { glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); ptrarray_append(&rock->globs, g); } if (config_virtdomains && userid && (p = strchr(userid, '@'))) { userlen = p - userid; domainlen = strlen(p); /* includes separator */ snprintf(domainpat, sizeof(domainpat), "%s!", p+1); } else domainpat[0] = '\0'; /* calculate the inbox (with trailing .INBOX. for later use) */ if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || ((p - userid) > (int)userlen)) && strlen(userid)+7 < MAX_MAILBOX_BUFFER) { char *t, *tmpuser = NULL; const char *inboxuser; if (domainlen) snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1); if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { tmpuser = xmalloc(userlen); memcpy(tmpuser, userid, userlen); t = tmpuser + (p - userid); while(t < (tmpuser + userlen)) { if (*t == '.') *t = '^'; t++; } inboxuser = tmpuser; } else inboxuser = userid; snprintf(inbox+domainlen, sizeof(inbox)-domainlen, "user.%.*s.INBOX.", (int)userlen, inboxuser); free(tmpuser); inboxlen = strlen(inbox) - 7; } else { userid = 0; } /* Find the common search prefix of all patterns */ const char *firstpat = strarray_nth(patterns, 0); for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { if (prefixlen >= MAX_MAILBOX_NAME) { r = IMAP_MAILBOX_BADNAME; goto done; } char c = firstpat[prefixlen]; for (i = 1; i < patterns->count; i++) { const char *pat = strarray_nth(patterns, i); if (pat[prefixlen] != c) break; } if (i < patterns->count) break; if (c == '*' || c == '%' || c == '?') break; commonpat[prefixlen] = c; } commonpat[prefixlen] = '\0'; if (patterns->count == 1) { /* Skip pattern which matches shared namespace prefix */ if (!strcmp(firstpat+prefixlen, "%")) rock->singlepercent = 2; /* output prefix regardless */ if (!strcmp(firstpat+prefixlen, "*%")) rock->singlepercent = 1; } /* * Personal (INBOX) namespace (only if not admin) */ if (userid && !isadmin) { /* first the INBOX */ rock->mb_category = MBNAME_INBOX; r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; if (rock->namespace->isalt) { /* do exact INBOX subs before resetting the namebuffer */ rock->mb_category = MBNAME_INBOXSUB; r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; } /* iterate through all the mailboxes under the user's inbox */ rock->mb_category = MBNAME_OWNER; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) r = 0; if (r) goto done; /* "Alt Prefix" folders */ if (rock->namespace->isalt) { /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; rock->mb_category = MBNAME_ALTINBOX; /* special case user.foo.INBOX. If we're singlepercent == 2, this could return DONE, in which case we don't need to foreach the rest of the altprefix space */ r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); if (r == CYRUSDB_DONE) goto skipalt; if (r) goto done; /* special case any other altprefix stuff */ rock->mb_category = MBNAME_ALTPREFIX; r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); skipalt: /* we got a done, so skip out of the foreach early */ if (r == CYRUSDB_DONE) r = 0; if (r) goto done; } } /* * Other Users namespace * * If "Other Users*" can match pattern, search for those mailboxes next */ if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { len = strlen(rock->namespace->prefix[NAMESPACE_USER]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { if (prefixlen <= len) { /* we match all users */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); } else { /* just those in this prefix */ strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen); strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); } rock->mb_category = MBNAME_OTHERUSER; /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; r = mboxlist_find_category(rock, domainpat, thislen); if (r) goto done; } } /* * Shared namespace * * search for all remaining mailboxes. * just bother looking at the ones that have the same pattern prefix. */ if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); if (len) len--; // trailing separator if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { rock->mb_category = MBNAME_SHARED; /* reset the the namebuffer */ r = (*rock->proc)(NULL, rock->procrock); if (r) goto done; /* iterate through all the non-user folders on the server */ r = mboxlist_find_category(rock, domainpat, domainlen); if (r) goto done; } } /* finish with a reset call always */ r = (*rock->proc)(NULL, rock->procrock); done: for (i = 0; i < rock->globs.count; i++) { glob *g = ptrarray_nth(&rock->globs, i); glob_free(&g); } ptrarray_fini(&rock->globs); return r; }
29,535
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.
Code: SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; } Commit Message: inotify: stop kernel memory leak on file creation failure If inotify_init is unable to allocate a new file for the new inotify group we leak the new group. This patch drops the reference on the group on file allocation failure. Reported-by: Vegard Nossum <[email protected]> cc: [email protected] Signed-off-by: Eric Paris <[email protected]> CWE ID: CWE-399
SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; fsnotify_put_group(group); atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; }
11,079
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.
Code: kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); } Commit Message: KVM: Don't accept obviously wrong gsi values via KVM_IRQFD We cannot add routes for gsi values >= KVM_MAX_IRQ_ROUTES -- see kvm_set_irq_routing(). Hence, there is no sense in accepting them via KVM_IRQFD. Prevent them from entering the system in the first place. Signed-off-by: Jan H. Schönherr <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) { if (args->flags & ~(KVM_IRQFD_FLAG_DEASSIGN | KVM_IRQFD_FLAG_RESAMPLE)) return -EINVAL; if (args->gsi >= KVM_MAX_IRQ_ROUTES) return -EINVAL; if (args->flags & KVM_IRQFD_FLAG_DEASSIGN) return kvm_irqfd_deassign(kvm, args); return kvm_irqfd_assign(kvm, args); }
29,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.
Code: isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } Commit Message: CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV In isis_print_is_reach_subtlv() one of the case blocks did not check that the sub-TLV "V" is actually present and could over-read the input buffer. Add a length check to fix that and remove a useless boundary check from a loop because the boundary is tested for the full length of "V" before the switch block. Update one of the prior test cases as it turns out it depended on this previously incorrect code path to make it to its own malformed structure further down the buffer, the bugfix has changed its output. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: if (subl == 0) break; ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); }
27,348
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.
Code: EncodedJSValue JSC_HOST_CALL jsFloat64ArrayPrototypeFunctionFoo(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSFloat64Array::s_info)) return throwVMTypeError(exec); JSFloat64Array* castedThis = jsCast<JSFloat64Array*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSFloat64Array::s_info); Float64Array* impl = static_cast<Float64Array*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); Float32Array* array(toFloat32Array(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->foo(array))); 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 jsFloat64ArrayPrototypeFunctionFoo(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSFloat64Array::s_info)) return throwVMTypeError(exec); JSFloat64Array* castedThis = jsCast<JSFloat64Array*>(asObject(thisValue)); ASSERT_GC_OBJECT_INHERITS(castedThis, &JSFloat64Array::s_info); Float64Array* impl = static_cast<Float64Array*>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createNotEnoughArgumentsError(exec)); Float32Array* array(toFloat32Array(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(impl->foo(array))); return JSValue::encode(result); }
18,416
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.
Code: void SetManualFallbacks(bool enabled) { std::vector<std::string> features = { password_manager::features::kEnableManualFallbacksFilling.name, password_manager::features::kEnableManualFallbacksFillingStandalone .name, password_manager::features::kEnableManualFallbacksGeneration.name}; if (enabled) { scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","), std::string()); } else { scoped_feature_list_.InitFromCommandLine(std::string(), base::JoinString(features, ",")); } } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <[email protected]> Commit-Queue: NIKHIL SAHNI <[email protected]> Cr-Commit-Position: refs/heads/master@{#534923} CWE ID: CWE-264
void SetManualFallbacks(bool enabled) { std::vector<std::string> features = { password_manager::features::kManualFallbacksFilling.name, password_manager::features::kEnableManualFallbacksFillingStandalone .name, password_manager::features::kEnableManualFallbacksGeneration.name}; if (enabled) { scoped_feature_list_.InitFromCommandLine(base::JoinString(features, ","), std::string()); } else { scoped_feature_list_.InitFromCommandLine(std::string(), base::JoinString(features, ",")); } }
23,572
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.
Code: bool initiate_stratum(struct pool *pool) { bool ret = false, recvd = false, noresume = false, sockd = false; char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; json_error_t err; int n2size; resend: if (!setup_stratum_socket(pool)) { /* FIXME: change to LOG_DEBUG when issue #88 resolved */ applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool)); sockd = false; goto out; } sockd = true; if (recvd) { /* Get rid of any crap lying around if we're resending */ clear_sock(pool); sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++); } else { if (pool->sessionid) sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid); else sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++); } if (__stratum_send(pool, s, strlen(s)) != SEND_OK) { applog(LOG_DEBUG, "Failed to send s in initiate_stratum"); goto out; } if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum"); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC decode failed: %s", ss); free(ss); goto out; } sessionid = get_sessionid(res_val); if (!sessionid) applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum"); nonce1 = json_array_string(res_val, 1); if (!nonce1) { applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum"); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (!n2size) { applog(LOG_INFO, "Failed to get n2size in initiate_stratum"); free(sessionid); free(nonce1); goto out; } cg_wlock(&pool->data_lock); pool->sessionid = sessionid; pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; free(pool->nonce1bin); pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1); if (unlikely(!pool->nonce1bin)) quithere(1, "Failed to calloc pool->nonce1bin"); hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len); pool->n2size = n2size; cg_wunlock(&pool->data_lock); if (sessionid) applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid); ret = true; out: if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->swork.diff = 1; if (opt_protocol) { applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d", get_pool_name(pool), pool->nonce1, pool->n2size); } } else { if (recvd && !noresume) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ cg_wlock(&pool->data_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; cg_wunlock(&pool->data_lock); applog(LOG_DEBUG, "Failed to resume stratum, trying afresh"); noresume = true; json_decref(val); goto resend; } applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool)); if (sockd) { applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool)); suspend_stratum(pool); } } json_decref(val); return ret; } Commit Message: Bugfix: initiate_stratum: Ensure extranonce2 size is not negative (which could lead to exploits later as too little memory gets allocated) Thanks to Mick Ayzenberg <[email protected]> for finding this! CWE ID: CWE-119
bool initiate_stratum(struct pool *pool) { bool ret = false, recvd = false, noresume = false, sockd = false; char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid; json_t *val = NULL, *res_val, *err_val; json_error_t err; int n2size; resend: if (!setup_stratum_socket(pool)) { /* FIXME: change to LOG_DEBUG when issue #88 resolved */ applog(LOG_INFO, "setup_stratum_socket() on %s failed", get_pool_name(pool)); sockd = false; goto out; } sockd = true; if (recvd) { /* Get rid of any crap lying around if we're resending */ clear_sock(pool); sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++); } else { if (pool->sessionid) sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid); else sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++); } if (__stratum_send(pool, s, strlen(s)) != SEND_OK) { applog(LOG_DEBUG, "Failed to send s in initiate_stratum"); goto out; } if (!socket_full(pool, DEFAULT_SOCKWAIT)) { applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum"); goto out; } sret = recv_line(pool); if (!sret) goto out; recvd = true; val = JSON_LOADS(sret, &err); free(sret); if (!val) { applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text); goto out; } res_val = json_object_get(val, "result"); err_val = json_object_get(val, "error"); if (!res_val || json_is_null(res_val) || (err_val && !json_is_null(err_val))) { char *ss; if (err_val) ss = json_dumps(err_val, JSON_INDENT(3)); else ss = strdup("(unknown reason)"); applog(LOG_INFO, "JSON-RPC decode failed: %s", ss); free(ss); goto out; } sessionid = get_sessionid(res_val); if (!sessionid) applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum"); nonce1 = json_array_string(res_val, 1); if (!nonce1) { applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum"); free(sessionid); goto out; } n2size = json_integer_value(json_array_get(res_val, 2)); if (n2size < 1) { applog(LOG_INFO, "Failed to get n2size in initiate_stratum"); free(sessionid); free(nonce1); goto out; } cg_wlock(&pool->data_lock); pool->sessionid = sessionid; pool->nonce1 = nonce1; pool->n1_len = strlen(nonce1) / 2; free(pool->nonce1bin); pool->nonce1bin = (unsigned char *)calloc(pool->n1_len, 1); if (unlikely(!pool->nonce1bin)) quithere(1, "Failed to calloc pool->nonce1bin"); hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len); pool->n2size = n2size; cg_wunlock(&pool->data_lock); if (sessionid) applog(LOG_DEBUG, "%s stratum session id: %s", get_pool_name(pool), pool->sessionid); ret = true; out: if (ret) { if (!pool->stratum_url) pool->stratum_url = pool->sockaddr_url; pool->stratum_active = true; pool->swork.diff = 1; if (opt_protocol) { applog(LOG_DEBUG, "%s confirmed mining.subscribe with extranonce1 %s extran2size %d", get_pool_name(pool), pool->nonce1, pool->n2size); } } else { if (recvd && !noresume) { /* Reset the sessionid used for stratum resuming in case the pool * does not support it, or does not know how to respond to the * presence of the sessionid parameter. */ cg_wlock(&pool->data_lock); free(pool->sessionid); free(pool->nonce1); pool->sessionid = pool->nonce1 = NULL; cg_wunlock(&pool->data_lock); applog(LOG_DEBUG, "Failed to resume stratum, trying afresh"); noresume = true; json_decref(val); goto resend; } applog(LOG_DEBUG, "Initiating stratum failed on %s", get_pool_name(pool)); if (sockd) { applog(LOG_DEBUG, "Suspending stratum on %s", get_pool_name(pool)); suspend_stratum(pool); } } json_decref(val); return ret; }
16,828
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.
Code: bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; bool partition_is_privileged = false; for (size_t i = 0; i < info->webview_privileged_partitions_.size(); ++i) { if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) { partition_is_privileged = true; break; } } return partition_is_privileged && extension->ResourceMatches( info->webview_accessible_resources_, relative_path); } Commit Message: <webview>: Update format for local file access in manifest.json The new format is: "webview" : { "partitions" : [ { "name" : "foo*", "accessible_resources" : ["a.html", "b.html"] }, { "name" : "bar", "accessible_resources" : ["a.html", "c.html"] } ] } BUG=340291 Review URL: https://codereview.chromium.org/151923005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; for (size_t i = 0; i < info->partition_items_.size(); ++i) { const PartitionItem* const item = info->partition_items_[i]; if (item->Matches(partition_id) && extension->ResourceMatches(item->accessible_resources(), relative_path)) { return true; } } return false; } void WebviewInfo::AddPartitionItem(scoped_ptr<PartitionItem> item) { partition_items_.push_back(item.release()); }
6,837
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.
Code: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, open_flags); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, open_flags); spin_unlock(&state->owner->so_lock); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, fmode); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, fmode); spin_unlock(&state->owner->so_lock); }
13,645
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.
Code: static int list_locations(struct kmem_cache *s, char *buf, enum track_item alloc) { int len = 0; unsigned long i; struct loc_track t = { 0, 0, NULL }; int node; if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location), GFP_TEMPORARY)) return sprintf(buf, "Out of memory\n"); /* Push back cpu slabs */ flush_all(s); for_each_node_state(node, N_NORMAL_MEMORY) { struct kmem_cache_node *n = get_node(s, node); unsigned long flags; struct page *page; if (!atomic_long_read(&n->nr_slabs)) continue; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) process_slab(&t, s, page, alloc); list_for_each_entry(page, &n->full, lru) process_slab(&t, s, page, alloc); spin_unlock_irqrestore(&n->list_lock, flags); } for (i = 0; i < t.count; i++) { struct location *l = &t.loc[i]; if (len > PAGE_SIZE - 100) break; len += sprintf(buf + len, "%7ld ", l->count); if (l->addr) len += sprint_symbol(buf + len, (unsigned long)l->addr); else len += sprintf(buf + len, "<not-available>"); if (l->sum_time != l->min_time) { unsigned long remainder; len += sprintf(buf + len, " age=%ld/%ld/%ld", l->min_time, div_long_long_rem(l->sum_time, l->count, &remainder), l->max_time); } else len += sprintf(buf + len, " age=%ld", l->min_time); if (l->min_pid != l->max_pid) len += sprintf(buf + len, " pid=%ld-%ld", l->min_pid, l->max_pid); else len += sprintf(buf + len, " pid=%ld", l->min_pid); if (num_online_cpus() > 1 && !cpus_empty(l->cpus) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " cpus="); len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->cpus); } if (num_online_nodes() > 1 && !nodes_empty(l->nodes) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " nodes="); len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->nodes); } len += sprintf(buf + len, "\n"); } free_loc_track(&t); if (!t.count) len += sprintf(buf, "No data\n"); return len; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
static int list_locations(struct kmem_cache *s, char *buf, enum track_item alloc) { int len = 0; unsigned long i; struct loc_track t = { 0, 0, NULL }; int node; if (!alloc_loc_track(&t, PAGE_SIZE / sizeof(struct location), GFP_TEMPORARY)) return sprintf(buf, "Out of memory\n"); /* Push back cpu slabs */ flush_all(s); for_each_node_state(node, N_NORMAL_MEMORY) { struct kmem_cache_node *n = get_node(s, node); unsigned long flags; struct page *page; if (!atomic_long_read(&n->nr_slabs)) continue; spin_lock_irqsave(&n->list_lock, flags); list_for_each_entry(page, &n->partial, lru) process_slab(&t, s, page, alloc); list_for_each_entry(page, &n->full, lru) process_slab(&t, s, page, alloc); spin_unlock_irqrestore(&n->list_lock, flags); } for (i = 0; i < t.count; i++) { struct location *l = &t.loc[i]; if (len > PAGE_SIZE - 100) break; len += sprintf(buf + len, "%7ld ", l->count); if (l->addr) len += sprint_symbol(buf + len, (unsigned long)l->addr); else len += sprintf(buf + len, "<not-available>"); if (l->sum_time != l->min_time) { len += sprintf(buf + len, " age=%ld/%ld/%ld", l->min_time, (long)div_u64(l->sum_time, l->count), l->max_time); } else len += sprintf(buf + len, " age=%ld", l->min_time); if (l->min_pid != l->max_pid) len += sprintf(buf + len, " pid=%ld-%ld", l->min_pid, l->max_pid); else len += sprintf(buf + len, " pid=%ld", l->min_pid); if (num_online_cpus() > 1 && !cpus_empty(l->cpus) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " cpus="); len += cpulist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->cpus); } if (num_online_nodes() > 1 && !nodes_empty(l->nodes) && len < PAGE_SIZE - 60) { len += sprintf(buf + len, " nodes="); len += nodelist_scnprintf(buf + len, PAGE_SIZE - len - 50, l->nodes); } len += sprintf(buf + len, "\n"); } free_loc_track(&t); if (!t.count) len += sprintf(buf, "No data\n"); return len; }
16,980
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.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, unsigned char*& buf, size_t& buflen) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || len <= 0 || len > 8 || (available - pos) > len) return false; unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return false; pos += len; // consume length of size of payload rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return false; if ((pos + size) > available) return false; if (size >= LONG_MAX) return false; const long buflen_ = static_cast<long>(size); buf = SafeArrayAlloc<unsigned char>(1, buflen_); if (!buf) return false; status = pReader->Read(pos, buflen_, buf); if (status != 0) return false; buflen = buflen_; pos += size; // consume size of payload return true; }
15
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.
Code: struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key_restriction *restrict_link) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->index_key.description) goto no_memory_3; refcount_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; key->restrict_link = restrict_link; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_BUILT_IN) key->flags |= 1 << KEY_FLAG_BUILTIN; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; } Commit Message: KEYS: prevent creating a different user's keyrings It was possible for an unprivileged user to create the user and user session keyrings for another user. For example: sudo -u '#3000' sh -c 'keyctl add keyring _uid.4000 "" @u keyctl add keyring _uid_ses.4000 "" @u sleep 15' & sleep 1 sudo -u '#4000' keyctl describe @u sudo -u '#4000' keyctl describe @us This is problematic because these "fake" keyrings won't have the right permissions. In particular, the user who created them first will own them and will have full access to them via the possessor permissions, which can be used to compromise the security of a user's keys: -4: alswrv-----v------------ 3000 0 keyring: _uid.4000 -5: alswrv-----v------------ 3000 0 keyring: _uid_ses.4000 Fix it by marking user and user session keyrings with a flag KEY_FLAG_UID_KEYRING. Then, when searching for a user or user session keyring by name, skip all keyrings that don't have the flag set. Fixes: 69664cf16af4 ("keys: don't generate user and user session keyrings unless they're accessed") Cc: <[email protected]> [v2.6.26+] Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> CWE ID:
struct key *key_alloc(struct key_type *type, const char *desc, kuid_t uid, kgid_t gid, const struct cred *cred, key_perm_t perm, unsigned long flags, struct key_restriction *restrict_link) { struct key_user *user = NULL; struct key *key; size_t desclen, quotalen; int ret; key = ERR_PTR(-EINVAL); if (!desc || !*desc) goto error; if (type->vet_description) { ret = type->vet_description(desc); if (ret < 0) { key = ERR_PTR(ret); goto error; } } desclen = strlen(desc); quotalen = desclen + 1 + type->def_datalen; /* get hold of the key tracking for this user */ user = key_user_lookup(uid); if (!user) goto no_memory_1; /* check that the user's quota permits allocation of another key and * its description */ if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxkeys : key_quota_maxkeys; unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? key_quota_root_maxbytes : key_quota_maxbytes; spin_lock(&user->lock); if (!(flags & KEY_ALLOC_QUOTA_OVERRUN)) { if (user->qnkeys + 1 >= maxkeys || user->qnbytes + quotalen >= maxbytes || user->qnbytes + quotalen < user->qnbytes) goto no_quota; } user->qnkeys++; user->qnbytes += quotalen; spin_unlock(&user->lock); } /* allocate and initialise the key and its description */ key = kmem_cache_zalloc(key_jar, GFP_KERNEL); if (!key) goto no_memory_2; key->index_key.desc_len = desclen; key->index_key.description = kmemdup(desc, desclen + 1, GFP_KERNEL); if (!key->index_key.description) goto no_memory_3; refcount_set(&key->usage, 1); init_rwsem(&key->sem); lockdep_set_class(&key->sem, &type->lock_class); key->index_key.type = type; key->user = user; key->quotalen = quotalen; key->datalen = type->def_datalen; key->uid = uid; key->gid = gid; key->perm = perm; key->restrict_link = restrict_link; if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) key->flags |= 1 << KEY_FLAG_IN_QUOTA; if (flags & KEY_ALLOC_BUILT_IN) key->flags |= 1 << KEY_FLAG_BUILTIN; if (flags & KEY_ALLOC_UID_KEYRING) key->flags |= 1 << KEY_FLAG_UID_KEYRING; #ifdef KEY_DEBUGGING key->magic = KEY_DEBUG_MAGIC; #endif /* let the security module know about the key */ ret = security_key_alloc(key, cred, flags); if (ret < 0) goto security_error; /* publish the key by giving it a serial number */ atomic_inc(&user->nkeys); key_alloc_serial(key); error: return key; security_error: kfree(key->description); kmem_cache_free(key_jar, key); if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); key = ERR_PTR(ret); goto error; no_memory_3: kmem_cache_free(key_jar, key); no_memory_2: if (!(flags & KEY_ALLOC_NOT_IN_QUOTA)) { spin_lock(&user->lock); user->qnkeys--; user->qnbytes -= quotalen; spin_unlock(&user->lock); } key_user_put(user); no_memory_1: key = ERR_PTR(-ENOMEM); goto error; no_quota: spin_unlock(&user->lock); key_user_put(user); key = ERR_PTR(-EDQUOT); goto error; }
29,718
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.
Code: InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { InputMethodDescriptors* descriptors = new InputMethodDescriptors; descriptors->push_back( input_method::GetFallbackInputMethodDescriptor()); return descriptors; } 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
InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { input_method::InputMethodDescriptors* CrosMock::CreateInputMethodDescriptors() { input_method::InputMethodDescriptors* descriptors = new input_method::InputMethodDescriptors; descriptors->push_back( input_method::GetFallbackInputMethodDescriptor()); return descriptors; }
22,788
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.
Code: static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian); value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian); return 1; } else if(field_type==4) { // LONG (uint32) *pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian); return 1; } return 0; } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = get_exif_ui16(e, tag_pos+2); value_count = get_exif_ui32(e, tag_pos+4); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = get_exif_ui16(e, tag_pos+8); return 1; } else if(field_type==4) { // LONG (uint32) *pv = get_exif_ui32(e, tag_pos+8); return 1; } return 0; }
20,901
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.
Code: void SystemClipboard::WriteImage(Image* image, const KURL& url, const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); SkBitmap bitmap; if (sk_sp<SkImage> sk_image = paint_image.GetSkImage()) sk_image->asLegacyBitmap(&bitmap); if (bitmap.isNull()) return; if (!bitmap.getPixels()) return; clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap); if (url.IsValid() && !url.IsEmpty()) { #if !defined(OS_MACOSX) clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard, url.GetString(), NonNullString(title)); #endif clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); } Commit Message: System Clipboard: Remove extraneous check for bitmap.getPixels() Bug 369621 originally led to this check being introduced via https://codereview.chromium.org/289573002/patch/40001/50002, but after https://crrev.com/c/1345809, I'm not sure that it's still necessary. This change succeeds when tested against the "minimized test case" provided in crbug.com/369621 's description, but I'm unsure how to make the minimized test case fail, so this doesn't prove that the change would succeed against the fuzzer's test case (which originally filed the bug). As I'm unable to view the relevant fuzzer test case, (see crbug.com/918705), I don't know exactly what may have caused the fuzzer to fail. Therefore, I've added a CHECK for the time being, so that we will be notified in canary if my assumption was incorrect. Bug: 369621 Change-Id: Ie9b47a4b38ba1ed47624de776015728e541d27f7 Reviewed-on: https://chromium-review.googlesource.com/c/1393436 Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Kai Ninomiya <[email protected]> Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Victor Costan <[email protected]> Cr-Commit-Position: refs/heads/master@{#619591} CWE ID: CWE-119
void SystemClipboard::WriteImage(Image* image, const KURL& url, const String& title) { DCHECK(image); PaintImage paint_image = image->PaintImageForCurrentFrame(); SkBitmap bitmap; if (sk_sp<SkImage> sk_image = paint_image.GetSkImage()) sk_image->asLegacyBitmap(&bitmap); if (bitmap.isNull()) return; // TODO(crbug.com/918717): Remove CHECK if no crashes occur on it in canary. CHECK(bitmap.getPixels()); clipboard_->WriteImage(mojom::ClipboardBuffer::kStandard, bitmap); if (url.IsValid() && !url.IsEmpty()) { #if !defined(OS_MACOSX) clipboard_->WriteBookmark(mojom::ClipboardBuffer::kStandard, url.GetString(), NonNullString(title)); #endif clipboard_->WriteHtml(mojom::ClipboardBuffer::kStandard, URLToImageMarkup(url, title), KURL()); } clipboard_->CommitWrite(mojom::ClipboardBuffer::kStandard); }
13,308
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.
Code: static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) memcpy(&rcp2, rp, sizeof(rcp2)); spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } } Commit Message: net/appletalk: fix minor pointer leak to userspace in SIOCFINDIPDDPRT Fields ->dev and ->next of struct ipddp_route may be copied to userspace on the SIOCFINDIPDDPRT ioctl. This is only accessible to CAP_NET_ADMIN though. Let's manually copy the relevant fields instead of using memcpy(). BugLink: http://blog.infosectcbr.com.au/2018/09/linux-kernel-infoleaks.html Cc: Jann Horn <[email protected]> Signed-off-by: Willy Tarreau <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) { memset(&rcp2, 0, sizeof(rcp2)); rcp2.ip = rp->ip; rcp2.at = rp->at; rcp2.flags = rp->flags; } spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } }
179
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.
Code: void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); } Commit Message: [Fetch API] Fix redirect leak on "no-cors" requests The spec issue is now fixed, and this CL follows the spec change[1]. 1: https://github.com/whatwg/fetch/commit/14858d3e9402285a7ff3b5e47a22896ff3adc95d Bug: 791324 Change-Id: Ic3e3955f43578b38fc44a5a6b2a1b43d56a2becb Reviewed-on: https://chromium-review.googlesource.com/1023613 Reviewed-by: Tsuyoshi Horo <[email protected]> Commit-Queue: Yutaka Hirano <[email protected]> Cr-Commit-Position: refs/heads/master@{#552964} CWE ID: CWE-200
void FetchManager::Loader::Start() { if (!ContentSecurityPolicy::ShouldBypassMainWorld(execution_context_) && !execution_context_->GetContentSecurityPolicy()->AllowConnectToSource( fetch_request_data_->Url())) { PerformNetworkError( "Refused to connect to '" + fetch_request_data_->Url().ElidedString() + "' because it violates the document's Content Security Policy."); return; } if ((SecurityOrigin::Create(fetch_request_data_->Url()) ->IsSameSchemeHostPort(fetch_request_data_->Origin().get())) || (fetch_request_data_->Url().ProtocolIsData() && fetch_request_data_->SameOriginDataURLFlag()) || (fetch_request_data_->Mode() == FetchRequestMode::kNavigate)) { PerformSchemeFetch(); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kSameOrigin) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"same-origin\" but the URL\'s " "origin is not same as the request origin " + fetch_request_data_->Origin()->ToString() + "."); return; } if (fetch_request_data_->Mode() == FetchRequestMode::kNoCORS) { // "If |request|'s redirect mode is not |follow|, then return a network // error. if (fetch_request_data_->Redirect() != FetchRedirectMode::kFollow) { PerformNetworkError("Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". Request mode is \"no-cors\" but the redirect mode " " is not \"follow\"."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kOpaqueTainting); PerformSchemeFetch(); return; } if (!SchemeRegistry::ShouldTreatURLSchemeAsSupportingFetchAPI( fetch_request_data_->Url().Protocol())) { PerformNetworkError( "Fetch API cannot load " + fetch_request_data_->Url().GetString() + ". URL scheme must be \"http\" or \"https\" for CORS request."); return; } fetch_request_data_->SetResponseTainting(FetchRequestData::kCORSTainting); PerformHTTPFetch(); }
28,521
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.
Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = disconnect_mount(p, how); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } } Commit Message: mnt: Add a per mount namespace limit on the number of mounts CAI Qian <[email protected]> pointed out that the semantics of shared subtrees make it possible to create an exponentially increasing number of mounts in a mount namespace. mkdir /tmp/1 /tmp/2 mount --make-rshared / for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done Will create create 2^20 or 1048576 mounts, which is a practical problem as some people have managed to hit this by accident. As such CVE-2016-6213 was assigned. Ian Kent <[email protected]> described the situation for autofs users as follows: > The number of mounts for direct mount maps is usually not very large because of > the way they are implemented, large direct mount maps can have performance > problems. There can be anywhere from a few (likely case a few hundred) to less > than 10000, plus mounts that have been triggered and not yet expired. > > Indirect mounts have one autofs mount at the root plus the number of mounts that > have been triggered and not yet expired. > > The number of autofs indirect map entries can range from a few to the common > case of several thousand and in rare cases up to between 30000 and 50000. I've > not heard of people with maps larger than 50000 entries. > > The larger the number of map entries the greater the possibility for a large > number of active mounts so it's not hard to expect cases of a 1000 or somewhat > more active mounts. So I am setting the default number of mounts allowed per mount namespace at 100,000. This is more than enough for any use case I know of, but small enough to quickly stop an exponential increase in mounts. Which should be perfect to catch misconfigurations and malfunctioning programs. For anyone who needs a higher limit this can be changed by writing to the new /proc/sys/fs/mount-max sysctl. Tested-by: CAI Qian <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-400
static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { struct mnt_namespace *ns; bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); ns = p->mnt_ns; if (ns) { ns->mounts--; __touch_mnt_namespace(ns); } p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = disconnect_mount(p, how); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } }
21,454
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.
Code: RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() { SetContentViewCore(NULL); if (!shared_surface_.is_null()) { ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle( shared_surface_); } if (texture_id_in_layer_) { ImageTransportFactoryAndroid::GetInstance()->DeleteTexture( texture_id_in_layer_); } }
9,171
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.
Code: xfs_ioctl_setattr( xfs_inode_t *ip, struct fsxattr *fa, int mask) { struct xfs_mount *mp = ip->i_mount; struct xfs_trans *tp; unsigned int lock_flags = 0; struct xfs_dquot *udqp = NULL; struct xfs_dquot *pdqp = NULL; struct xfs_dquot *olddquot = NULL; int code; trace_xfs_ioctl_setattr(ip); if (mp->m_flags & XFS_MOUNT_RDONLY) return XFS_ERROR(EROFS); if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); /* * Disallow 32bit project ids when projid32bit feature is not enabled. */ if ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) && !xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb)) return XFS_ERROR(EINVAL); /* * If disk quotas is on, we make sure that the dquots do exist on disk, * before we start any other transactions. Trying to do this later * is messy. We don't care to take a readlock to look at the ids * in inode here, because we can't hold it across the trans_reserve. * If the IDs do change before we take the ilock, we're covered * because the i_*dquot fields will get updated anyway. */ if (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) { code = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid, ip->i_d.di_gid, fa->fsx_projid, XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp); if (code) return code; } /* * For the other attributes, we acquire the inode lock and * first do an error checking pass. */ tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE); code = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0); if (code) goto error_return; lock_flags = XFS_ILOCK_EXCL; xfs_ilock(ip, lock_flags); /* * CAP_FOWNER overrides the following restrictions: * * The user ID of the calling process must be equal * to the file owner ID, except in cases where the * CAP_FSETID capability is applicable. */ if (!inode_owner_or_capable(VFS_I(ip))) { code = XFS_ERROR(EPERM); goto error_return; } /* * Do a quota reservation only if projid is actually going to change. * Only allow changing of projid from init_user_ns since it is a * non user namespace aware identifier. */ if (mask & FSX_PROJID) { if (current_user_ns() != &init_user_ns) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp) && xfs_get_projid(ip) != fa->fsx_projid) { ASSERT(tp); code = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL, pdqp, capable(CAP_FOWNER) ? XFS_QMOPT_FORCE_RES : 0); if (code) /* out of quota */ goto error_return; } } if (mask & FSX_EXTSIZE) { /* * Can't change extent size if any extents are allocated. */ if (ip->i_d.di_nextents && ((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) != fa->fsx_extsize)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * Extent size must be a multiple of the appropriate block * size, if set at all. It must also be smaller than the * maximum extent size supported by the filesystem. * * Also, for non-realtime files, limit the extent size hint to * half the size of the AGs in the filesystem so alignment * doesn't result in extents larger than an AG. */ if (fa->fsx_extsize != 0) { xfs_extlen_t size; xfs_fsblock_t extsize_fsb; extsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize); if (extsize_fsb > MAXEXTLEN) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_REALTIME_INODE(ip) || ((mask & FSX_XFLAGS) && (fa->fsx_xflags & XFS_XFLAG_REALTIME))) { size = mp->m_sb.sb_rextsize << mp->m_sb.sb_blocklog; } else { size = mp->m_sb.sb_blocksize; if (extsize_fsb > mp->m_sb.sb_agblocks / 2) { code = XFS_ERROR(EINVAL); goto error_return; } } if (fa->fsx_extsize % size) { code = XFS_ERROR(EINVAL); goto error_return; } } } if (mask & FSX_XFLAGS) { /* * Can't change realtime flag if any extents are allocated. */ if ((ip->i_d.di_nextents || ip->i_delayed_blks) && (XFS_IS_REALTIME_INODE(ip)) != (fa->fsx_xflags & XFS_XFLAG_REALTIME)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * If realtime flag is set then must have realtime data. */ if ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) { if ((mp->m_sb.sb_rblocks == 0) || (mp->m_sb.sb_rextsize == 0) || (ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) { code = XFS_ERROR(EINVAL); goto error_return; } } /* * Can't modify an immutable/append-only file unless * we have appropriate permission. */ if ((ip->i_d.di_flags & (XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) || (fa->fsx_xflags & (XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) && !capable(CAP_LINUX_IMMUTABLE)) { code = XFS_ERROR(EPERM); goto error_return; } } xfs_trans_ijoin(tp, ip, 0); /* * Change file ownership. Must be the owner or privileged. */ if (mask & FSX_PROJID) { /* * CAP_FSETID overrides the following restrictions: * * The set-user-ID and set-group-ID bits of a file will be * cleared upon successful return from chown() */ if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) && !inode_capable(VFS_I(ip), CAP_FSETID)) ip->i_d.di_mode &= ~(S_ISUID|S_ISGID); /* * Change the ownerships and register quota modifications * in the transaction. */ if (xfs_get_projid(ip) != fa->fsx_projid) { if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) { olddquot = xfs_qm_vop_chown(tp, ip, &ip->i_pdquot, pdqp); } xfs_set_projid(ip, fa->fsx_projid); /* * We may have to rev the inode as well as * the superblock version number since projids didn't * exist before DINODE_VERSION_2 and SB_VERSION_NLINK. */ if (ip->i_d.di_version == 1) xfs_bump_ino_vers2(tp, ip); } } if (mask & FSX_EXTSIZE) ip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog; if (mask & FSX_XFLAGS) { xfs_set_diflags(ip, fa->fsx_xflags); xfs_diflags_to_linux(ip); } xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); XFS_STATS_INC(xs_ig_attrchg); /* * If this is a synchronous mount, make sure that the * transaction goes to disk before returning to the user. * This is slightly sub-optimal in that truncates require * two sync transactions instead of one for wsync filesystems. * One for the truncate and one for the timestamps since we * don't want to change the timestamps unless we're sure the * truncate worked. Truncates are less than 1% of the laddis * mix so this probably isn't worth the trouble to optimize. */ if (mp->m_flags & XFS_MOUNT_WSYNC) xfs_trans_set_sync(tp); code = xfs_trans_commit(tp, 0); xfs_iunlock(ip, lock_flags); /* * Release any dquot(s) the inode had kept before chown. */ xfs_qm_dqrele(olddquot); xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); return code; error_return: xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); xfs_trans_cancel(tp, 0); if (lock_flags) xfs_iunlock(ip, lock_flags); return code; } Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid The kernel has no concept of capabilities with respect to inodes; inodes exist independently of namespaces. For example, inode_capable(inode, CAP_LINUX_IMMUTABLE) would be nonsense. This patch changes inode_capable to check for uid and gid mappings and renames it to capable_wrt_inode_uidgid, which should make it more obvious what it does. Fixes CVE-2014-4014. Cc: Theodore Ts'o <[email protected]> Cc: Serge Hallyn <[email protected]> Cc: "Eric W. Biederman" <[email protected]> Cc: Dave Chinner <[email protected]> Cc: [email protected] Signed-off-by: Andy Lutomirski <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
xfs_ioctl_setattr( xfs_inode_t *ip, struct fsxattr *fa, int mask) { struct xfs_mount *mp = ip->i_mount; struct xfs_trans *tp; unsigned int lock_flags = 0; struct xfs_dquot *udqp = NULL; struct xfs_dquot *pdqp = NULL; struct xfs_dquot *olddquot = NULL; int code; trace_xfs_ioctl_setattr(ip); if (mp->m_flags & XFS_MOUNT_RDONLY) return XFS_ERROR(EROFS); if (XFS_FORCED_SHUTDOWN(mp)) return XFS_ERROR(EIO); /* * Disallow 32bit project ids when projid32bit feature is not enabled. */ if ((mask & FSX_PROJID) && (fa->fsx_projid > (__uint16_t)-1) && !xfs_sb_version_hasprojid32bit(&ip->i_mount->m_sb)) return XFS_ERROR(EINVAL); /* * If disk quotas is on, we make sure that the dquots do exist on disk, * before we start any other transactions. Trying to do this later * is messy. We don't care to take a readlock to look at the ids * in inode here, because we can't hold it across the trans_reserve. * If the IDs do change before we take the ilock, we're covered * because the i_*dquot fields will get updated anyway. */ if (XFS_IS_QUOTA_ON(mp) && (mask & FSX_PROJID)) { code = xfs_qm_vop_dqalloc(ip, ip->i_d.di_uid, ip->i_d.di_gid, fa->fsx_projid, XFS_QMOPT_PQUOTA, &udqp, NULL, &pdqp); if (code) return code; } /* * For the other attributes, we acquire the inode lock and * first do an error checking pass. */ tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE); code = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0); if (code) goto error_return; lock_flags = XFS_ILOCK_EXCL; xfs_ilock(ip, lock_flags); /* * CAP_FOWNER overrides the following restrictions: * * The user ID of the calling process must be equal * to the file owner ID, except in cases where the * CAP_FSETID capability is applicable. */ if (!inode_owner_or_capable(VFS_I(ip))) { code = XFS_ERROR(EPERM); goto error_return; } /* * Do a quota reservation only if projid is actually going to change. * Only allow changing of projid from init_user_ns since it is a * non user namespace aware identifier. */ if (mask & FSX_PROJID) { if (current_user_ns() != &init_user_ns) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp) && xfs_get_projid(ip) != fa->fsx_projid) { ASSERT(tp); code = xfs_qm_vop_chown_reserve(tp, ip, udqp, NULL, pdqp, capable(CAP_FOWNER) ? XFS_QMOPT_FORCE_RES : 0); if (code) /* out of quota */ goto error_return; } } if (mask & FSX_EXTSIZE) { /* * Can't change extent size if any extents are allocated. */ if (ip->i_d.di_nextents && ((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) != fa->fsx_extsize)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * Extent size must be a multiple of the appropriate block * size, if set at all. It must also be smaller than the * maximum extent size supported by the filesystem. * * Also, for non-realtime files, limit the extent size hint to * half the size of the AGs in the filesystem so alignment * doesn't result in extents larger than an AG. */ if (fa->fsx_extsize != 0) { xfs_extlen_t size; xfs_fsblock_t extsize_fsb; extsize_fsb = XFS_B_TO_FSB(mp, fa->fsx_extsize); if (extsize_fsb > MAXEXTLEN) { code = XFS_ERROR(EINVAL); goto error_return; } if (XFS_IS_REALTIME_INODE(ip) || ((mask & FSX_XFLAGS) && (fa->fsx_xflags & XFS_XFLAG_REALTIME))) { size = mp->m_sb.sb_rextsize << mp->m_sb.sb_blocklog; } else { size = mp->m_sb.sb_blocksize; if (extsize_fsb > mp->m_sb.sb_agblocks / 2) { code = XFS_ERROR(EINVAL); goto error_return; } } if (fa->fsx_extsize % size) { code = XFS_ERROR(EINVAL); goto error_return; } } } if (mask & FSX_XFLAGS) { /* * Can't change realtime flag if any extents are allocated. */ if ((ip->i_d.di_nextents || ip->i_delayed_blks) && (XFS_IS_REALTIME_INODE(ip)) != (fa->fsx_xflags & XFS_XFLAG_REALTIME)) { code = XFS_ERROR(EINVAL); /* EFBIG? */ goto error_return; } /* * If realtime flag is set then must have realtime data. */ if ((fa->fsx_xflags & XFS_XFLAG_REALTIME)) { if ((mp->m_sb.sb_rblocks == 0) || (mp->m_sb.sb_rextsize == 0) || (ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) { code = XFS_ERROR(EINVAL); goto error_return; } } /* * Can't modify an immutable/append-only file unless * we have appropriate permission. */ if ((ip->i_d.di_flags & (XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) || (fa->fsx_xflags & (XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) && !capable(CAP_LINUX_IMMUTABLE)) { code = XFS_ERROR(EPERM); goto error_return; } } xfs_trans_ijoin(tp, ip, 0); /* * Change file ownership. Must be the owner or privileged. */ if (mask & FSX_PROJID) { /* * CAP_FSETID overrides the following restrictions: * * The set-user-ID and set-group-ID bits of a file will be * cleared upon successful return from chown() */ if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) && !capable_wrt_inode_uidgid(VFS_I(ip), CAP_FSETID)) ip->i_d.di_mode &= ~(S_ISUID|S_ISGID); /* * Change the ownerships and register quota modifications * in the transaction. */ if (xfs_get_projid(ip) != fa->fsx_projid) { if (XFS_IS_QUOTA_RUNNING(mp) && XFS_IS_PQUOTA_ON(mp)) { olddquot = xfs_qm_vop_chown(tp, ip, &ip->i_pdquot, pdqp); } xfs_set_projid(ip, fa->fsx_projid); /* * We may have to rev the inode as well as * the superblock version number since projids didn't * exist before DINODE_VERSION_2 and SB_VERSION_NLINK. */ if (ip->i_d.di_version == 1) xfs_bump_ino_vers2(tp, ip); } } if (mask & FSX_EXTSIZE) ip->i_d.di_extsize = fa->fsx_extsize >> mp->m_sb.sb_blocklog; if (mask & FSX_XFLAGS) { xfs_set_diflags(ip, fa->fsx_xflags); xfs_diflags_to_linux(ip); } xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); XFS_STATS_INC(xs_ig_attrchg); /* * If this is a synchronous mount, make sure that the * transaction goes to disk before returning to the user. * This is slightly sub-optimal in that truncates require * two sync transactions instead of one for wsync filesystems. * One for the truncate and one for the timestamps since we * don't want to change the timestamps unless we're sure the * truncate worked. Truncates are less than 1% of the laddis * mix so this probably isn't worth the trouble to optimize. */ if (mp->m_flags & XFS_MOUNT_WSYNC) xfs_trans_set_sync(tp); code = xfs_trans_commit(tp, 0); xfs_iunlock(ip, lock_flags); /* * Release any dquot(s) the inode had kept before chown. */ xfs_qm_dqrele(olddquot); xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); return code; error_return: xfs_qm_dqrele(udqp); xfs_qm_dqrele(pdqp); xfs_trans_cancel(tp, 0); if (lock_flags) xfs_iunlock(ip, lock_flags); return code; }
15,231
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.
Code: void VRDisplay::OnFocus() { display_blurred_ = false; ConnectVSyncProvider(); navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create( EventTypeNames::vrdisplayfocus, true, false, this, "")); } Commit Message: WebVR: fix initial vsync Applications sometimes use window.rAF while not presenting, then switch to vrDisplay.rAF after presentation starts. Depending on the animation loop's timing, this can cause a race condition where presentation has been started but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync being processed after presentation starts so that a queued window.rAF can run and schedule a vrDisplay.rAF. BUG=711789 Review-Url: https://codereview.chromium.org/2848483003 Cr-Commit-Position: refs/heads/master@{#468167} CWE ID:
void VRDisplay::OnFocus() { DVLOG(1) << __FUNCTION__; display_blurred_ = false; ConnectVSyncProvider(); navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create( EventTypeNames::vrdisplayfocus, true, false, this, "")); }
18,134