instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(snmp_set_enum_print) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1); RETURN_TRUE; } Commit Message: CWE ID: CWE-416
PHP_FUNCTION(snmp_set_enum_print) { long a1; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) { RETURN_FALSE; } netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1); RETURN_TRUE;
164,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool BlockEntry::EOS() const { return (GetKind() == kBlockEOS); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
bool BlockEntry::EOS() const
174,271
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CameraSource::releaseQueuedFrames() { List<sp<IMemory> >::iterator it; while (!mFramesReceived.empty()) { it = mFramesReceived.begin(); releaseRecordingFrame(*it); mFramesReceived.erase(it); ++mNumFramesDropped; } } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void CameraSource::releaseQueuedFrames() { List<sp<IMemory> >::iterator it; while (!mFramesReceived.empty()) { it = mFramesReceived.begin(); // b/28466701 adjustOutgoingANWBuffer(it->get()); releaseRecordingFrame(*it); mFramesReceived.erase(it); ++mNumFramesDropped; } }
173,509
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Reinitialize(ReinitTestCase test_case) { feature_list_.InitAndEnableFeature(network::features::kNetworkService); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); EXPECT_TRUE(db.LazyOpen(true)); if (test_case == CORRUPT_CACHE_ON_INSTALL || test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { const std::string kCorruptData("deadbeef"); base::FilePath disk_cache_directory = temp_directory_.GetPath().AppendASCII("Cache"); ASSERT_TRUE(base::CreateDirectory(disk_cache_directory)); base::FilePath index_file = disk_cache_directory.AppendASCII("index"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index_file, kCorruptData.data(), kCorruptData.length())); base::FilePath entry_file = disk_cache_directory.AppendASCII("01234567_0"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(entry_file, kCorruptData.data(), kCorruptData.length())); } if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); GURL manifest_url = GetMockUrl("manifest"); AppCacheDatabase::GroupRecord group_record; group_record.group_id = 1; group_record.manifest_url = manifest_url; group_record.origin = url::Origin::Create(manifest_url); EXPECT_TRUE(db.InsertGroup(&group_record)); AppCacheDatabase::CacheRecord cache_record; cache_record.cache_id = 1; cache_record.group_id = 1; cache_record.online_wildcard = false; cache_record.update_time = kZeroTime; cache_record.cache_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertCache(&cache_record)); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.url = manifest_url; entry_record.flags = AppCacheEntry::MANIFEST; entry_record.response_id = 1; entry_record.response_size = kDefaultEntrySize; EXPECT_TRUE(db.InsertEntry(&entry_record)); } service_.reset(new AppCacheServiceImpl(nullptr)); auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); loader_factory_getter->SetNetworkFactoryForTesting( &mock_url_loader_factory_, /* is_corb_enabled = */ true); service_->set_url_loader_factory_getter(loader_factory_getter.get()); service_->Initialize(temp_directory_.GetPath()); mock_quota_manager_proxy_ = new MockQuotaManagerProxy(); service_->quota_manager_proxy_ = mock_quota_manager_proxy_; delegate_.reset(new MockStorageDelegate(this)); observer_.reset(new MockServiceObserver(this)); service_->AddObserver(observer_.get()); FlushAllTasks(); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize, base::Unretained(this), test_case)); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void Reinitialize(ReinitTestCase test_case) { feature_list_.InitAndEnableFeature(network::features::kNetworkService); ASSERT_TRUE(temp_directory_.CreateUniqueTempDir()); AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); EXPECT_TRUE(db.LazyOpen(true)); if (test_case == CORRUPT_CACHE_ON_INSTALL || test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { const std::string kCorruptData("deadbeef"); base::FilePath disk_cache_directory = temp_directory_.GetPath().AppendASCII("Cache"); ASSERT_TRUE(base::CreateDirectory(disk_cache_directory)); base::FilePath index_file = disk_cache_directory.AppendASCII("index"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(index_file, kCorruptData.data(), kCorruptData.length())); base::FilePath entry_file = disk_cache_directory.AppendASCII("01234567_0"); EXPECT_EQ(static_cast<int>(kCorruptData.length()), base::WriteFile(entry_file, kCorruptData.data(), kCorruptData.length())); } if (test_case == CORRUPT_CACHE_ON_LOAD_EXISTING) { AppCacheDatabase db(temp_directory_.GetPath().AppendASCII("Index")); GURL manifest_url = GetMockUrl("manifest"); AppCacheDatabase::GroupRecord group_record; group_record.group_id = 1; group_record.manifest_url = manifest_url; group_record.origin = url::Origin::Create(manifest_url); EXPECT_TRUE(db.InsertGroup(&group_record)); AppCacheDatabase::CacheRecord cache_record; cache_record.cache_id = 1; cache_record.group_id = 1; cache_record.online_wildcard = false; cache_record.update_time = kZeroTime; cache_record.cache_size = kDefaultEntrySize; cache_record.padding_size = 0; EXPECT_TRUE(db.InsertCache(&cache_record)); AppCacheDatabase::EntryRecord entry_record; entry_record.cache_id = 1; entry_record.url = manifest_url; entry_record.flags = AppCacheEntry::MANIFEST; entry_record.response_id = 1; entry_record.response_size = kDefaultEntrySize; entry_record.padding_size = 0; EXPECT_TRUE(db.InsertEntry(&entry_record)); } service_.reset(new AppCacheServiceImpl(nullptr)); auto loader_factory_getter = base::MakeRefCounted<URLLoaderFactoryGetter>(); loader_factory_getter->SetNetworkFactoryForTesting( &mock_url_loader_factory_, /* is_corb_enabled = */ true); service_->set_url_loader_factory_getter(loader_factory_getter.get()); service_->Initialize(temp_directory_.GetPath()); mock_quota_manager_proxy_ = new MockQuotaManagerProxy(); service_->quota_manager_proxy_ = mock_quota_manager_proxy_; delegate_.reset(new MockStorageDelegate(this)); observer_.reset(new MockServiceObserver(this)); service_->AddObserver(observer_.get()); FlushAllTasks(); base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AppCacheStorageImplTest::Continue_Reinitialize, base::Unretained(this), test_case)); }
172,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, current_fsuid())) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, current_fsgid())) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. */ if (ns_capable(ns->parent, cap_setid)) return true; return false; } Commit Message: userns: Don't let unprivileged users trick privileged users into setting the id_map When we require privilege for setting /proc/<pid>/uid_map or /proc/<pid>/gid_map no longer allow an unprivileged user to open the file and pass it to a privileged program to write to the file. Instead when privilege is required require both the opener and the writer to have the necessary capabilities. I have tested this code and verified that setting /proc/<pid>/uid_map fails when an unprivileged user opens the file and a privielged user attempts to set the mapping, that unprivileged users can still map their own id, and that a privileged users can still setup an arbitrary mapping. Reported-by: Andy Lutomirski <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Andy Lutomirski <[email protected]> CWE ID: CWE-264
static bool new_idmap_permitted(struct user_namespace *ns, int cap_setid, static bool new_idmap_permitted(const struct file *file, struct user_namespace *ns, int cap_setid, struct uid_gid_map *new_map) { /* Allow mapping to your own filesystem ids */ if ((new_map->nr_extents == 1) && (new_map->extent[0].count == 1)) { u32 id = new_map->extent[0].lower_first; if (cap_setid == CAP_SETUID) { kuid_t uid = make_kuid(ns->parent, id); if (uid_eq(uid, current_fsuid())) return true; } else if (cap_setid == CAP_SETGID) { kgid_t gid = make_kgid(ns->parent, id); if (gid_eq(gid, current_fsgid())) return true; } } /* Allow anyone to set a mapping that doesn't require privilege */ if (!cap_valid(cap_setid)) return true; /* Allow the specified ids if we have the appropriate capability * (CAP_SETUID or CAP_SETGID) over the parent user namespace. * And the opener of the id file also had the approprpiate capability. */ if (ns_capable(ns->parent, cap_setid) && file_ns_capable(file, ns->parent, cap_setid)) return true; return false; }
166,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (content::GetContentClient()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; }
171,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual const ImePropertyList& current_ime_properties() const { return current_ime_properties_; } 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
virtual const ImePropertyList& current_ime_properties() const { virtual const input_method::ImePropertyList& current_ime_properties() const { return current_ime_properties_; }
170,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){ int status = 0; int16_t level; int16_t ratio; uint32_t time; t_reverb_settings *pProperties; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; if (pContext->preset) { if (param != REVERB_PARAM_PRESET) { return -EINVAL; } uint16_t preset = *(uint16_t *)pValue; ALOGV("set REVERB_PARAM_PRESET, preset %d", preset); if (preset > REVERB_PRESET_LAST) { return -EINVAL; } pContext->nextPreset = preset; return 0; } switch (param){ case REVERB_PARAM_PROPERTIES: ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES"); pProperties = (t_reverb_settings *) pValue; ReverbSetRoomLevel(pContext, pProperties->roomLevel); ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel); ReverbSetDecayTime(pContext, pProperties->decayTime); ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio); ReverbSetReverbLevel(pContext, pProperties->reverbLevel); ReverbSetDiffusion(pContext, pProperties->diffusion); ReverbSetDensity(pContext, pProperties->density); break; case REVERB_PARAM_ROOM_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomLevel(pContext, level); break; case REVERB_PARAM_ROOM_HF_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomHfLevel(pContext, level); break; case REVERB_PARAM_DECAY_TIME: time = *(uint32_t *)pValue; ReverbSetDecayTime(pContext, time); break; case REVERB_PARAM_DECAY_HF_RATIO: ratio = *(int16_t *)pValue; ReverbSetDecayHfRatio(pContext, ratio); break; case REVERB_PARAM_REVERB_LEVEL: level = *(int16_t *)pValue; ReverbSetReverbLevel(pContext, level); break; case REVERB_PARAM_DIFFUSION: ratio = *(int16_t *)pValue; ReverbSetDiffusion(pContext, ratio); break; case REVERB_PARAM_DENSITY: ratio = *(int16_t *)pValue; ReverbSetDensity(pContext, ratio); break; break; case REVERB_PARAM_REFLECTIONS_LEVEL: case REVERB_PARAM_REFLECTIONS_DELAY: case REVERB_PARAM_REVERB_DELAY: break; default: ALOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param); break; } return status; } /* end Reverb_setParameter */ Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking to Downmix and Reverb Bug: 63662938 Bug: 63526567 Test: Added CTS tests Change-Id: I8ed398cd62a9f461b0590e37f593daa3d8e4dbc4 (cherry picked from commit 804632afcdda6e80945bf27c384757bda50560cb) CWE ID: CWE-200
int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue){ int Reverb_setParameter (ReverbContext *pContext, void *pParam, void *pValue, int vsize){ int status = 0; int16_t level; int16_t ratio; uint32_t time; t_reverb_settings *pProperties; int32_t *pParamTemp = (int32_t *)pParam; int32_t param = *pParamTemp++; if (pContext->preset) { if (param != REVERB_PARAM_PRESET) { return -EINVAL; } uint16_t preset = *(uint16_t *)pValue; ALOGV("set REVERB_PARAM_PRESET, preset %d", preset); if (preset > REVERB_PRESET_LAST) { return -EINVAL; } pContext->nextPreset = preset; return 0; } if (vsize < Reverb_paramValueSize(param)) { android_errorWriteLog(0x534e4554, "63526567"); return -EINVAL; } switch (param){ case REVERB_PARAM_PROPERTIES: ALOGV("\tReverb_setParameter() REVERB_PARAM_PROPERTIES"); pProperties = (t_reverb_settings *) pValue; ReverbSetRoomLevel(pContext, pProperties->roomLevel); ReverbSetRoomHfLevel(pContext, pProperties->roomHFLevel); ReverbSetDecayTime(pContext, pProperties->decayTime); ReverbSetDecayHfRatio(pContext, pProperties->decayHFRatio); ReverbSetReverbLevel(pContext, pProperties->reverbLevel); ReverbSetDiffusion(pContext, pProperties->diffusion); ReverbSetDensity(pContext, pProperties->density); break; case REVERB_PARAM_ROOM_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomLevel(pContext, level); break; case REVERB_PARAM_ROOM_HF_LEVEL: level = *(int16_t *)pValue; ReverbSetRoomHfLevel(pContext, level); break; case REVERB_PARAM_DECAY_TIME: time = *(uint32_t *)pValue; ReverbSetDecayTime(pContext, time); break; case REVERB_PARAM_DECAY_HF_RATIO: ratio = *(int16_t *)pValue; ReverbSetDecayHfRatio(pContext, ratio); break; case REVERB_PARAM_REVERB_LEVEL: level = *(int16_t *)pValue; ReverbSetReverbLevel(pContext, level); break; case REVERB_PARAM_DIFFUSION: ratio = *(int16_t *)pValue; ReverbSetDiffusion(pContext, ratio); break; case REVERB_PARAM_DENSITY: ratio = *(int16_t *)pValue; ReverbSetDensity(pContext, ratio); break; break; case REVERB_PARAM_REFLECTIONS_LEVEL: case REVERB_PARAM_REFLECTIONS_DELAY: case REVERB_PARAM_REVERB_DELAY: break; default: ALOGV("\tLVM_ERROR : Reverb_setParameter() invalid param %d", param); break; } return status; } /* end Reverb_setParameter */
173,980
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); } Commit Message: CWE ID: CWE-399
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &/*reply*/) { Q_UNUSED(ctcptype) emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix); }
164,877
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick = im->thick; if (color == gdAntiAliased) { /* gdAntiAliased passed as color: use the much faster, much cheaper and equally attractive gdImageAALine implementation. That clips too, so don't clip twice. */ gdImageAALine(im, x1, y1, x2, y2, im->AA_color); return; } /* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */ if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im))) { return; } dx = abs (x2 - x1); dy = abs (y2 - y1); if (dx == 0) { gdImageVLine(im, x1, y1, y2, color); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, color); return; } if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ if ((dx == 0) && (dy == 0)) { wid = 1; } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 (dy, dx)); if (ac != 0) { wid = thick / ac; } else { wid = 1; } if (wid == 0) { wid = 1; } } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel(im, x, w, color); } if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } if (wid == 0) { wid = 1; } d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick = im->thick; if (color == gdAntiAliased) { /* gdAntiAliased passed as color: use the much faster, much cheaper and equally attractive gdImageAALine implementation. That clips too, so don't clip twice. */ gdImageAALine(im, x1, y1, x2, y2, im->AA_color); return; } /* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */ if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im))) { return; } dx = abs (x2 - x1); dy = abs (y2 - y1); if (dx == 0) { gdImageVLine(im, x1, y1, y2, color); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, color); return; } if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ if ((dx == 0) && (dy == 0)) { wid = 1; } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 (dy, dx)); if (ac != 0) { wid = thick / ac; } else { wid = 1; } if (wid == 0) { wid = 1; } } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel(im, x, w, color); } if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } if (wid == 0) { wid = 1; } d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } } }
167,129
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { if(_ignoreListManager->ctcpMatch(prefix, network()->networkName(), "PING")) return; reply(nickFromMask(prefix), "PING", param); emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") } } Commit Message: CWE ID: CWE-399
void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param) { void CtcpHandler::handlePing(CtcpType ctcptype, const QString &prefix, const QString &target, const QString &param, QString &reply) { Q_UNUSED(target) if(ctcptype == CtcpQuery) { reply = param; emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP PING request from %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME request by %1").arg(prefix)); } else { emit displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Received CTCP TIME answer from %1: %2") } }
164,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaInterfaceProxy::ConnectToService() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!interface_factory_ptr_); service_manager::mojom::InterfaceProviderPtr interfaces; auto provider = base::MakeUnique<media::MediaInterfaceProvider>( mojo::MakeRequest(&interfaces)); #if BUILDFLAG(ENABLE_MOJO_CDM) net::URLRequestContextGetter* context_getter = BrowserContext::GetDefaultStoragePartition( render_frame_host_->GetProcess()->GetBrowserContext()) ->GetURLRequestContext(); provider->registry()->AddInterface(base::Bind( &ProvisionFetcherImpl::Create, base::RetainedRef(context_getter))); #endif // BUILDFLAG(ENABLE_MOJO_CDM) GetContentClient()->browser()->ExposeInterfacesToMediaService( provider->registry(), render_frame_host_); media_registries_.push_back(std::move(provider)); media::mojom::MediaServicePtr media_service; service_manager::Connector* connector = ServiceManagerConnection::GetForProcess()->GetConnector(); connector->BindInterface(media::mojom::kMediaServiceName, &media_service); media_service->CreateInterfaceFactory(MakeRequest(&interface_factory_ptr_), std::move(interfaces)); interface_factory_ptr_.set_connection_error_handler(base::Bind( &MediaInterfaceProxy::OnConnectionError, base::Unretained(this))); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
void MediaInterfaceProxy::ConnectToService() { void MediaInterfaceProxy::OnCdmServiceConnectionError() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); cdm_interface_factory_ptr_.reset(); } service_manager::mojom::InterfaceProviderPtr MediaInterfaceProxy::GetFrameServices() { service_manager::mojom::InterfaceProviderPtr interfaces; auto provider = base::MakeUnique<media::MediaInterfaceProvider>( mojo::MakeRequest(&interfaces)); #if BUILDFLAG(ENABLE_MOJO_CDM) net::URLRequestContextGetter* context_getter = BrowserContext::GetDefaultStoragePartition( render_frame_host_->GetProcess()->GetBrowserContext()) ->GetURLRequestContext(); provider->registry()->AddInterface(base::Bind( &ProvisionFetcherImpl::Create, base::RetainedRef(context_getter))); #endif // BUILDFLAG(ENABLE_MOJO_CDM) GetContentClient()->browser()->ExposeInterfacesToMediaService( provider->registry(), render_frame_host_); media_registries_.push_back(std::move(provider)); return interfaces; } void MediaInterfaceProxy::ConnectToMediaService() { DVLOG(1) << __FUNCTION__; media::mojom::MediaServicePtr media_service; // TODO(slan): Use the BrowserContext Connector instead. See crbug.com/638950. service_manager::Connector* connector = ServiceManagerConnection::GetForProcess()->GetConnector(); connector->BindInterface(media::mojom::kMediaServiceName, &media_service); media_service->CreateInterfaceFactory(MakeRequest(&interface_factory_ptr_), GetFrameServices()); interface_factory_ptr_.set_connection_error_handler( base::Bind(&MediaInterfaceProxy::OnMediaServiceConnectionError, base::Unretained(this))); } void MediaInterfaceProxy::ConnectToCdmService() { DVLOG(1) << __FUNCTION__; media::mojom::MediaServicePtr media_service; // TODO(slan): Use the BrowserContext Connector instead. See crbug.com/638950. service_manager::Connector* connector = ServiceManagerConnection::GetForProcess()->GetConnector(); connector->BindInterface(media::mojom::kCdmServiceName, &media_service); media_service->CreateInterfaceFactory( MakeRequest(&cdm_interface_factory_ptr_), GetFrameServices()); cdm_interface_factory_ptr_.set_connection_error_handler( base::Bind(&MediaInterfaceProxy::OnCdmServiceConnectionError, base::Unretained(this))); }
171,935
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = yr_max(64, (index + 1) * 2); array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119
int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = 64; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; }
168,045
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; }
169,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } }
167,035
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode *inode = dentry->d_inode; int error = -EACCES; /* We don't need a base pointer in the /proc filesystem */ path_put(&nd->path); /* Are we allowed to snoop on the tasks file descriptors? */ if (!proc_fd_access_allowed(inode)) goto out; error = PROC_I(inode)->op.proc_get_link(inode, &nd->path); nd->last_type = LAST_BIND; out: return ERR_PTR(error); } Commit Message: fix autofs/afs/etc. magic mountpoint breakage We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT) if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type is bogus here; we want LAST_BIND for everything of that kind and we get LAST_NORM left over from finding parent directory. So make sure that it *is* set properly; set to LAST_BIND before doing ->follow_link() - for normal symlinks it will be changed by __vfs_follow_link() and everything else needs it set that way. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-20
static void *proc_pid_follow_link(struct dentry *dentry, struct nameidata *nd) { struct inode *inode = dentry->d_inode; int error = -EACCES; /* We don't need a base pointer in the /proc filesystem */ path_put(&nd->path); /* Are we allowed to snoop on the tasks file descriptors? */ if (!proc_fd_access_allowed(inode)) goto out; error = PROC_I(inode)->op.proc_get_link(inode, &nd->path); out: return ERR_PTR(error); }
166,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltFuncRegisterImportFunc (exsltFuncFunctionData *data, exsltFuncImportRegData *ch, const xmlChar *URI, const xmlChar *name, ATTRIBUTE_UNUSED const xmlChar *ignored) { exsltFuncFunctionData *func=NULL; if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL)) return; if (ch->ctxt == NULL || ch->hash == NULL) return; /* Check if already present */ func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name); if (func == NULL) { /* Not yet present - copy it in */ func = exsltFuncNewFunctionData(); memcpy(func, data, sizeof(exsltFuncFunctionData)); if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) { xsltGenericError(xsltGenericErrorContext, "Failed to register function {%s}%s\n", URI, name); } else { /* Do the registration */ xsltGenericDebug(xsltGenericDebugContext, "exsltFuncRegisterImportFunc: register {%s}%s\n", URI, name); xsltRegisterExtFunction(ch->ctxt, name, URI, exsltFuncFunctionFunction); } } } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltFuncRegisterImportFunc (exsltFuncFunctionData *data, exsltFuncImportRegData *ch, const xmlChar *URI, const xmlChar *name, ATTRIBUTE_UNUSED const xmlChar *ignored) { exsltFuncFunctionData *func=NULL; if ((data == NULL) || (ch == NULL) || (URI == NULL) || (name == NULL)) return; if (ch->ctxt == NULL || ch->hash == NULL) return; /* Check if already present */ func = (exsltFuncFunctionData*)xmlHashLookup2(ch->hash, URI, name); if (func == NULL) { /* Not yet present - copy it in */ func = exsltFuncNewFunctionData(); if (func == NULL) return; memcpy(func, data, sizeof(exsltFuncFunctionData)); if (xmlHashAddEntry2(ch->hash, URI, name, func) < 0) { xsltGenericError(xsltGenericErrorContext, "Failed to register function {%s}%s\n", URI, name); } else { /* Do the registration */ xsltGenericDebug(xsltGenericDebugContext, "exsltFuncRegisterImportFunc: register {%s}%s\n", URI, name); xsltRegisterExtFunction(ch->ctxt, name, URI, exsltFuncFunctionFunction); } } }
173,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection( blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) { DCHECK_EQ(WORKER_NOT_READY, state_); state_ = WORKER_READY; agent_ptr_.Bind(std::move(devtools_agent_ptr_info)); if (!sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_); for (DevToolsSession* session : sessions()) { session->SetRenderer(host, nullptr); session->AttachToAgent(agent_ptr_); } } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::WorkerReadyForInspection( blink::mojom::DevToolsAgentAssociatedPtrInfo devtools_agent_ptr_info) { DCHECK_EQ(WORKER_NOT_READY, state_); state_ = WORKER_READY; agent_ptr_.Bind(std::move(devtools_agent_ptr_info)); if (!sessions().empty()) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } for (DevToolsSession* session : sessions()) { session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } }
172,785
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseContentEncodingEntry(long long start, long long size, IMkvReader* pReader) { assert(pReader); long long pos = start; const long long stop = start + size; int compression_count = 0; int encryption_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1034) // ContentCompression ID ++compression_count; if (id == 0x1035) // ContentEncryption ID ++encryption_count; pos += size; // consume payload assert(pos <= stop); } if (compression_count <= 0 && encryption_count <= 0) return -1; if (compression_count > 0) { compression_entries_ = new (std::nothrow) ContentCompression* [compression_count]; if (!compression_entries_) return -1; compression_entries_end_ = compression_entries_; } if (encryption_count > 0) { encryption_entries_ = new (std::nothrow) ContentEncryption* [encryption_count]; if (!encryption_entries_) { delete[] compression_entries_; return -1; } encryption_entries_end_ = encryption_entries_; } pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1031) { encoding_order_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1032) { encoding_scope_ = UnserializeUInt(pReader, pos, size); if (encoding_scope_ < 1) return -1; } else if (id == 0x1033) { encoding_type_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1034) { ContentCompression* const compression = new (std::nothrow) ContentCompression(); if (!compression) return -1; status = ParseCompressionEntry(pos, size, pReader, compression); if (status) { delete compression; return status; } *compression_entries_end_++ = compression; } else if (id == 0x1035) { ContentEncryption* const encryption = new (std::nothrow) ContentEncryption(); if (!encryption) return -1; status = ParseEncryptionEntry(pos, size, pReader, encryption); if (status) { delete encryption; return status; } *encryption_entries_end_++ = encryption; } pos += size; // consume payload assert(pos <= stop); } 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::ParseContentEncodingEntry(long long start, long long size, IMkvReader* pReader) { assert(pReader); long long pos = start; const long long stop = start + size; int compression_count = 0; int encryption_count = 0; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1034) // ContentCompression ID ++compression_count; if (id == 0x1035) // ContentEncryption ID ++encryption_count; pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (compression_count <= 0 && encryption_count <= 0) return -1; if (compression_count > 0) { compression_entries_ = new (std::nothrow) ContentCompression*[compression_count]; if (!compression_entries_) return -1; compression_entries_end_ = compression_entries_; } if (encryption_count > 0) { encryption_entries_ = new (std::nothrow) ContentEncryption*[encryption_count]; if (!encryption_entries_) { delete[] compression_entries_; return -1; } encryption_entries_end_ = encryption_entries_; } pos = start; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x1031) { encoding_order_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1032) { encoding_scope_ = UnserializeUInt(pReader, pos, size); if (encoding_scope_ < 1) return -1; } else if (id == 0x1033) { encoding_type_ = UnserializeUInt(pReader, pos, size); } else if (id == 0x1034) { ContentCompression* const compression = new (std::nothrow) ContentCompression(); if (!compression) return -1; status = ParseCompressionEntry(pos, size, pReader, compression); if (status) { delete compression; return status; } *compression_entries_end_++ = compression; } else if (id == 0x1035) { ContentEncryption* const encryption = new (std::nothrow) ContentEncryption(); if (!encryption) return -1; status = ParseEncryptionEntry(pos, size, pReader, encryption); if (status) { delete encryption; return status; } *encryption_entries_end_++ = encryption; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
173,850
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LockContentsView::OnUsersChanged( const std::vector<mojom::LoginUserInfoPtr>& users) { main_view_->RemoveAllChildViews(true /*delete_children*/); opt_secondary_big_view_ = nullptr; users_list_ = nullptr; rotation_actions_.clear(); users_.clear(); if (users.empty()) { LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin) << "Empty user list received"; Shell::Get()->login_screen_controller()->ShowGaiaSignin( false /*can_close*/, base::nullopt /*prefilled_account*/); return; } for (const mojom::LoginUserInfoPtr& user : users) { UserState state(user->basic_user_info->account_id); state.fingerprint_state = user->allow_fingerprint_unlock ? mojom::FingerprintUnlockState::AVAILABLE : mojom::FingerprintUnlockState::UNAVAILABLE; users_.push_back(std::move(state)); } auto box_layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal); main_layout_ = box_layout.get(); main_layout_->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); main_layout_->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); main_view_->SetLayoutManager(std::move(box_layout)); primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/); main_view_->AddChildView(primary_big_view_); if (users.size() == 2) CreateLowDensityLayout(users); else if (users.size() >= 3 && users.size() <= 6) CreateMediumDensityLayout(users); else if (users.size() >= 7) CreateHighDensityLayout(users); LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/); OnBigUserChanged(); PreferredSizeChanged(); Layout(); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void LockContentsView::OnUsersChanged( const std::vector<mojom::LoginUserInfoPtr>& users) { main_view_->RemoveAllChildViews(true /*delete_children*/); opt_secondary_big_view_ = nullptr; users_list_ = nullptr; rotation_actions_.clear(); users_.clear(); if (users.empty()) { LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin) << "Empty user list received"; Shell::Get()->login_screen_controller()->ShowGaiaSignin( false /*can_close*/, base::nullopt /*prefilled_account*/); return; } for (const mojom::LoginUserInfoPtr& user : users) users_.push_back(UserState(user)); auto box_layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal); main_layout_ = box_layout.get(); main_layout_->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); main_layout_->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); main_view_->SetLayoutManager(std::move(box_layout)); primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/); main_view_->AddChildView(primary_big_view_); if (users.size() == 2) CreateLowDensityLayout(users); else if (users.size() >= 3 && users.size() <= 6) CreateMediumDensityLayout(users); else if (users.size() >= 7) CreateHighDensityLayout(users); LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/); OnBigUserChanged(); PreferredSizeChanged(); Layout(); }
172,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path_old; char *norm_path_new; char *join_path_old; char *join_path_new; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; size_t len; size_t i; M_uint64 total_count = 0; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; M_fs_error_t res; if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') { return M_FS_ERROR_INVALID; } /* It's okay if new path doesn't exist. */ res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); return res; } /* If a path is a file and the destination is a directory the file should be copied * into the directory. E.g. /file.txt -> /dir = /dir/file.txt */ if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) { M_free(norm_path_new); res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags); M_free(norm_path_old); return res; } /* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path * existing to rename because any check we perform may not be true when rename is called. */ res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); M_free(norm_path_old); return res; } progress = M_fs_progress_create(); res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; } type = M_fs_info_get_type(info); /* There is a race condition where the path could not exist but be created between the exists check and calling * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this * situation won't cause an error. */ if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return M_FS_ERROR_FILE_EXISTS; } entries = M_fs_dir_entries_create(); /* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed. * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is * stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); if (type == M_FS_TYPE_DIR) { if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL; } else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } /* Get all the files under the dir. */ M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter)); } /* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */ M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE); len = M_fs_dir_entries_len(entries); if (cb) { total_size = 0; for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; type = M_fs_dir_entry_get_type(entry); /* The total isn't the total number of files but the total number of operations. * Making dirs and symlinks is one operation and copying a file will be split into * multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in * chunks. We determine how many chunks will be needed to read the entire file and * use that for the number of operations for the file. */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { total_count++; } else { total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE; } } /* Change the progress total size to reflect all entries. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, total_count); } } for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); type = M_fs_dir_entry_get_type(entry); join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; if (cb) { M_fs_progress_set_path(progress, join_path_new); if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); } } /* op */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { if (type == M_FS_TYPE_DIR) { res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL); } else if (type == M_FS_TYPE_SYMLINK) { res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry)); } if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) { res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new); } } else { res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry))); } M_free(join_path_old); M_free(join_path_new); /* Call the callback and stop processing if requested. */ if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) { M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, entry_size); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } /* Delete the file(s) if it could not be copied properly, but only if we are not overwriting. * If we're overwriting then there could be other files in that location (especially if it's a dir). */ if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) { M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA); } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path_old; char *norm_path_new; char *join_path_old; char *join_path_new; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; size_t len; size_t i; M_uint64 total_count = 0; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; M_fs_error_t res; if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') { return M_FS_ERROR_INVALID; } /* It's okay if new path doesn't exist. */ res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); return res; } /* If a path is a file and the destination is a directory the file should be copied * into the directory. E.g. /file.txt -> /dir = /dir/file.txt */ if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) { M_free(norm_path_new); res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags); M_free(norm_path_old); return res; } /* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path * existing to rename because any check we perform may not be true when rename is called. */ res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path_new); M_free(norm_path_old); return res; } progress = M_fs_progress_create(); res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; } type = M_fs_info_get_type(info); /* There is a race condition where the path could not exist but be created between the exists check and calling * rename to move the file but there isn't much we can do in this case. copy will delete and the file so this * situation won't cause an error. */ if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) { M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return M_FS_ERROR_FILE_EXISTS; } entries = M_fs_dir_entries_create(); /* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed. * M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is * stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); if (type == M_FS_TYPE_DIR) { if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL; } else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } /* Get all the files under the dir. */ M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter)); } /* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */ M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE); len = M_fs_dir_entries_len(entries); if (cb) { total_size = 0; for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; type = M_fs_dir_entry_get_type(entry); /* The total isn't the total number of files but the total number of operations. * Making dirs and symlinks is one operation and copying a file will be split into * multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in * chunks. We determine how many chunks will be needed to read the entire file and * use that for the number of operations for the file. */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { total_count++; } else { total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE; } } /* Change the progress total size to reflect all entries. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, total_count); } } for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); type = M_fs_dir_entry_get_type(entry); join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; if (cb) { M_fs_progress_set_path(progress, join_path_new); if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); } } /* op */ if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) { if (type == M_FS_TYPE_DIR) { res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL); } else if (type == M_FS_TYPE_SYMLINK) { res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry)); } if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) { res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new); } } else { res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry))); } M_free(join_path_old); M_free(join_path_new); /* Call the callback and stop processing if requested. */ if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) { M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res); if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current_progress(progress, entry_size); } if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1); } if (!cb(progress)) { res = M_FS_ERROR_CANCELED; } } if (res != M_FS_ERROR_SUCCESS) { break; } } /* Delete the file(s) if it could not be copied properly, but only if we are not overwriting. * If we're overwriting then there could be other files in that location (especially if it's a dir). */ if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) { M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA); } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path_new); M_free(norm_path_old); return res; }
169,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void serveloop(GArray* servers) { struct sockaddr_storage addrin; socklen_t addrinlen=sizeof(addrin); int i; int max; fd_set mset; fd_set rset; /* * Set up the master fd_set. The set of descriptors we need * to select() for never changes anyway and it buys us a *lot* * of time to only build this once. However, if we ever choose * to not fork() for clients anymore, we may have to revisit * this. */ max=0; FD_ZERO(&mset); for(i=0;i<servers->len;i++) { int sock; if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) { FD_SET(sock, &mset); max=sock>max?sock:max; } } for(i=0;i<modernsocks->len;i++) { int sock = g_array_index(modernsocks, int, i); FD_SET(sock, &mset); max=sock>max?sock:max; } for(;;) { /* SIGHUP causes the root server process to reconfigure * itself and add new export servers for each newly * found export configuration group, i.e. spawn new * server processes for each previously non-existent * export. This does not alter old runtime configuration * but just appends new exports. */ if (is_sighup_caught) { int n; GError *gerror = NULL; msg(LOG_INFO, "reconfiguration request received"); is_sighup_caught = 0; /* Reset to allow catching * it again. */ n = append_new_servers(servers, &gerror); if (n == -1) msg(LOG_ERR, "failed to append new servers: %s", gerror->message); for (i = servers->len - n; i < servers->len; ++i) { const SERVER server = g_array_index(servers, SERVER, i); if (server.socket >= 0) { FD_SET(server.socket, &mset); max = server.socket > max ? server.socket : max; } msg(LOG_INFO, "reconfigured new server: %s", server.servename); } } memcpy(&rset, &mset, sizeof(fd_set)); if(select(max+1, &rset, NULL, NULL, NULL)>0) { int net; DEBUG("accept, "); for(i=0; i < modernsocks->len; i++) { int sock = g_array_index(modernsocks, int, i); if(!FD_ISSET(sock, &rset)) { continue; } CLIENT *client; if((net=accept(sock, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } client = negotiate(net, NULL, servers, NEG_INIT | NEG_MODERN); if(!client) { close(net); continue; } handle_connection(servers, net, client->server, client); } for(i=0; i < servers->len; i++) { SERVER *serve; serve=&(g_array_index(servers, SERVER, i)); if(serve->socket < 0) { continue; } if(FD_ISSET(serve->socket, &rset)) { if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } handle_connection(servers, net, serve, NULL); } } } } } Commit Message: nbd-server: handle modern-style negotiation in a child process Previously, the modern style negotiation was carried out in the root server (listener) process before forking the actual client handler. This made it possible for a malfunctioning or evil client to terminate the root process simply by querying a non-existent export or aborting in the middle of the negotation process (caused SIGPIPE in the server). This commit moves the negotiation process to the child to keep the root process up and running no matter what happens during the negotiation. See http://sourceforge.net/mailarchive/message.php?msg_id=30410146 Signed-off-by: Tuomas Räsänen <[email protected]> CWE ID: CWE-399
void serveloop(GArray* servers) { struct sockaddr_storage addrin; socklen_t addrinlen=sizeof(addrin); int i; int max; fd_set mset; fd_set rset; /* * Set up the master fd_set. The set of descriptors we need * to select() for never changes anyway and it buys us a *lot* * of time to only build this once. However, if we ever choose * to not fork() for clients anymore, we may have to revisit * this. */ max=0; FD_ZERO(&mset); for(i=0;i<servers->len;i++) { int sock; if((sock=(g_array_index(servers, SERVER, i)).socket) >= 0) { FD_SET(sock, &mset); max=sock>max?sock:max; } } for(i=0;i<modernsocks->len;i++) { int sock = g_array_index(modernsocks, int, i); FD_SET(sock, &mset); max=sock>max?sock:max; } for(;;) { /* SIGHUP causes the root server process to reconfigure * itself and add new export servers for each newly * found export configuration group, i.e. spawn new * server processes for each previously non-existent * export. This does not alter old runtime configuration * but just appends new exports. */ if (is_sighup_caught) { int n; GError *gerror = NULL; msg(LOG_INFO, "reconfiguration request received"); is_sighup_caught = 0; /* Reset to allow catching * it again. */ n = append_new_servers(servers, &gerror); if (n == -1) msg(LOG_ERR, "failed to append new servers: %s", gerror->message); for (i = servers->len - n; i < servers->len; ++i) { const SERVER server = g_array_index(servers, SERVER, i); if (server.socket >= 0) { FD_SET(server.socket, &mset); max = server.socket > max ? server.socket : max; } msg(LOG_INFO, "reconfigured new server: %s", server.servename); } } memcpy(&rset, &mset, sizeof(fd_set)); if(select(max+1, &rset, NULL, NULL, NULL)>0) { DEBUG("accept, "); for(i=0; i < modernsocks->len; i++) { int sock = g_array_index(modernsocks, int, i); if(!FD_ISSET(sock, &rset)) { continue; } handle_modern_connection(servers, sock); } for(i=0; i < servers->len; i++) { int net; SERVER *serve; serve=&(g_array_index(servers, SERVER, i)); if(serve->socket < 0) { continue; } if(FD_ISSET(serve->socket, &rset)) { if ((net=accept(serve->socket, (struct sockaddr *) &addrin, &addrinlen)) < 0) { err_nonfatal("accept: %m"); continue; } handle_connection(servers, net, serve, NULL); } } } } }
166,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int parse_exports_table(long long *table_start) { int res; int indexes = SQUASHFS_LOOKUP_BLOCKS(sBlk.s.inodes); long long export_index_table[indexes]; res = read_fs_bytes(fd, sBlk.s.lookup_table_start, SQUASHFS_LOOKUP_BLOCK_BYTES(sBlk.s.inodes), export_index_table); if(res == FALSE) { ERROR("parse_exports_table: failed to read export index table\n"); return FALSE; } SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes); /* * export_index_table[0] stores the start of the compressed export blocks. * This by definition is also the end of the previous filesystem * table - the fragment table. */ *table_start = export_index_table[0]; return TRUE; } Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6 Add more filesystem table sanity checks to Unsquashfs-4 and also properly fix CVE-2015-4645 and CVE-2015-4646. The CVEs were raised due to Unsquashfs having variable oveflow and stack overflow in a number of vulnerable functions. The suggested patch only "fixed" one such function and fixed it badly, and so it was buggy and introduced extra bugs! The suggested patch was not only buggy, but, it used the essentially wrong approach too. It was "fixing" the symptom but not the cause. The symptom is wrong values causing overflow, the cause is filesystem corruption. This corruption should be detected and the filesystem rejected *before* trying to allocate memory. This patch applies the following fixes: 1. The filesystem super-block tables are checked, and the values must match across the filesystem. This will trap corrupted filesystems created by Mksquashfs. 2. The maximum (theorectical) size the filesystem tables could grow to, were analysed, and some variables were increased from int to long long. This analysis has been added as comments. 3. Stack allocation was removed, and a shared buffer (which is checked and increased as necessary) is used to read the table indexes. Signed-off-by: Phillip Lougher <[email protected]> CWE ID: CWE-190
static int parse_exports_table(long long *table_start) { /* * Note on overflow limits: * Size of SBlk.s.inodes is 2^32 (unsigned int) * Max indexes is (2^32*8)/8K or 2^22 * Max length is ((2^32*8)/8K)*8 or 2^25 */ int res; int indexes = SQUASHFS_LOOKUP_BLOCKS((long long) sBlk.s.inodes); int length = SQUASHFS_LOOKUP_BLOCK_BYTES((long long) sBlk.s.inodes); long long *export_index_table; /* * The size of the index table (length bytes) should match the * table start and end points */ if(length != (*table_start - sBlk.s.lookup_table_start)) { ERROR("parse_exports_table: Bad inode count in super block\n"); return FALSE; } export_index_table = alloc_index_table(indexes); res = read_fs_bytes(fd, sBlk.s.lookup_table_start, length, export_index_table); if(res == FALSE) { ERROR("parse_exports_table: failed to read export index table\n"); return FALSE; } SQUASHFS_INSWAP_LOOKUP_BLOCKS(export_index_table, indexes); /* * export_index_table[0] stores the start of the compressed export blocks. * This by definition is also the end of the previous filesystem * table - the fragment table. */ *table_start = export_index_table[0]; return TRUE; }
168,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; int hlen = 20; int ttl = 64; uint8_t *pcontent; IPV4Hdr ip4h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip4h.ip_verhl = 4 << 4; ip4h.ip_verhl |= hlen >> 2; ip4h.ip_len = htons(hlen + content_len); ip4h.ip_id = htons(id); ip4h.ip_off = htons(off); if (mf) ip4h.ip_off = htons(IP_MF | off); else ip4h.ip_off = htons(off); ip4h.ip_ttl = ttl; ip4h.ip_proto = IPPROTO_ICMP; ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */ ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */ /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h)); p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); SET_IPV4_SRC_ADDR(p, &p->src); SET_IPV4_DST_ADDR(p, &p->dst); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, hlen, pcontent, content_len); SET_PKT_LEN(p, hlen + content_len); SCFree(pcontent); p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen); /* Self test. */ if (IPV4_GET_VER(p) != 4) goto error; if (IPV4_GET_HLEN(p) != hlen) goto error; if (IPV4_GET_IPLEN(p) != hlen + content_len) goto error; if (IPV4_GET_IPID(p) != id) goto error; if (IPV4_GET_IPOFFSET(p) != off) goto error; if (IPV4_GET_MF(p) != mf) goto error; if (IPV4_GET_IPTTL(p) != ttl) goto error; if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP) goto error; return p; error: if (p != NULL) SCFree(p); return NULL; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; int hlen = 20; int ttl = 64; uint8_t *pcontent; IPV4Hdr ip4h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip4h.ip_verhl = 4 << 4; ip4h.ip_verhl |= hlen >> 2; ip4h.ip_len = htons(hlen + content_len); ip4h.ip_id = htons(id); ip4h.ip_off = htons(off); if (mf) ip4h.ip_off = htons(IP_MF | off); else ip4h.ip_off = htons(off); ip4h.ip_ttl = ttl; ip4h.ip_proto = proto; ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */ ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */ /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip4h, sizeof(ip4h)); p->ip4h = (IPV4Hdr *)GET_PKT_DATA(p); SET_IPV4_SRC_ADDR(p, &p->src); SET_IPV4_DST_ADDR(p, &p->dst); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, hlen, pcontent, content_len); SET_PKT_LEN(p, hlen + content_len); SCFree(pcontent); p->ip4h->ip_csum = IPV4CalculateChecksum((uint16_t *)GET_PKT_DATA(p), hlen); /* Self test. */ if (IPV4_GET_VER(p) != 4) goto error; if (IPV4_GET_HLEN(p) != hlen) goto error; if (IPV4_GET_IPLEN(p) != hlen + content_len) goto error; if (IPV4_GET_IPID(p) != id) goto error; if (IPV4_GET_IPOFFSET(p) != off) goto error; if (IPV4_GET_MF(p) != mf) goto error; if (IPV4_GET_IPTTL(p) != ttl) goto error; if (IPV4_GET_IPPROTO(p) != proto) goto error; return p; error: if (p != NULL) SCFree(p); return NULL; }
168,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num) { const uni_to_enc *l = table, *h = &table[num-1], *m; unsigned short code_key; /* we have no mappings outside the BMP */ if (code_key_a > 0xFFFFU) return 0; code_key = (unsigned short) code_key_a; while (l <= h) { m = l + (h - l) / 2; if (code_key < m->un_code_point) h = m - 1; else if (code_key > m->un_code_point) l = m + 1; else return m->cs_code; } return 0; }
167,180
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } 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
nfssvc_decode_readlinkargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readlinkargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; if (!xdr_argsize_check(rqstp, p)) return 0; args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,152
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; } Commit Message: CWE ID: CWE-704
gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; }
164,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
int jas_stream_gobble(jas_stream_t *stream, int n) { int m; if (n < 0) { jas_deprecated("negative count for jas_stream_gobble"); } m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; }
168,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); if (CSSDefaultStyleSheets::simpleDefaultStyleSheet) collector.matchedResult().isCacheable = false; RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void StyleResolver::matchUARules(ElementRuleCollector& collector) { collector.setMatchingUARules(true); RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print") ? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle; matchUARules(collector, userAgentStyleSheet); if (document().inQuirksMode()) matchUARules(collector, CSSDefaultStyleSheets::defaultQuirksStyle); if (document().isViewSource()) matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle()); collector.setMatchingUARules(false); matchWatchSelectorRules(collector); }
171,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long CuePoint::GetTimeCode() const { return m_timecode; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long CuePoint::GetTimeCode() const long long CuePoint::GetTime(const Segment* pSegment) const { assert(pSegment); assert(m_timecode >= 0); const SegmentInfo* const pInfo = pSegment->GetInfo(); assert(pInfo); const long long scale = pInfo->GetTimeCodeScale(); assert(scale >= 1); const long long time = scale * m_timecode; return time; }
174,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderMessageFilter::OnCreateWindow( const ViewHostMsg_CreateWindow_Params& params, int* route_id, int* surface_id, int64* cloned_session_storage_namespace_id) { bool no_javascript_access; bool can_create_window = GetContentClient()->browser()->CanCreateWindow( GURL(params.opener_url), GURL(params.opener_security_origin), params.window_container_type, resource_context_, render_process_id_, &no_javascript_access); if (!can_create_window) { *route_id = MSG_ROUTING_NONE; *surface_id = 0; return; } scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace = new SessionStorageNamespaceImpl(dom_storage_context_, params.session_storage_namespace_id); *cloned_session_storage_namespace_id = cloned_namespace->id(); render_widget_helper_->CreateNewWindow(params, no_javascript_access, peer_handle(), route_id, surface_id, cloned_namespace); } Commit Message: Filter more incoming URLs in the CreateWindow path. BUG=170532 Review URL: https://chromiumcodereview.appspot.com/12036002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderMessageFilter::OnCreateWindow( const ViewHostMsg_CreateWindow_Params& params, int* route_id, int* surface_id, int64* cloned_session_storage_namespace_id) { bool no_javascript_access; bool can_create_window = GetContentClient()->browser()->CanCreateWindow( params.opener_url, params.opener_security_origin, params.window_container_type, resource_context_, render_process_id_, &no_javascript_access); if (!can_create_window) { *route_id = MSG_ROUTING_NONE; *surface_id = 0; return; } scoped_refptr<SessionStorageNamespaceImpl> cloned_namespace = new SessionStorageNamespaceImpl(dom_storage_context_, params.session_storage_namespace_id); *cloned_session_storage_namespace_id = cloned_namespace->id(); render_widget_helper_->CreateNewWindow(params, no_javascript_access, peer_handle(), route_id, surface_id, cloned_namespace); }
171,497
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry, char *args, int lsm_rule, int audit_type) { int result; if (entry->lsm[lsm_rule].rule) return -EINVAL; entry->lsm[lsm_rule].type = audit_type; result = security_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal, args, &entry->lsm[lsm_rule].rule); return result; } Commit Message: ima: fix add LSM rule bug If security_filter_rule_init() doesn't return a rule, then not everything is as fine as the return code implies. This bug only occurs when the LSM (eg. SELinux) is disabled at runtime. Adding an empty LSM rule causes ima_match_rules() to always succeed, ignoring any remaining rules. default IMA TCB policy: # PROC_SUPER_MAGIC dont_measure fsmagic=0x9fa0 # SYSFS_MAGIC dont_measure fsmagic=0x62656572 # DEBUGFS_MAGIC dont_measure fsmagic=0x64626720 # TMPFS_MAGIC dont_measure fsmagic=0x01021994 # SECURITYFS_MAGIC dont_measure fsmagic=0x73636673 < LSM specific rule > dont_measure obj_type=var_log_t measure func=BPRM_CHECK measure func=FILE_MMAP mask=MAY_EXEC measure func=FILE_CHECK mask=MAY_READ uid=0 Thus without the patch, with the boot parameters 'tcb selinux=0', adding the above 'dont_measure obj_type=var_log_t' rule to the default IMA TCB measurement policy, would result in nothing being measured. The patch prevents the default TCB policy from being replaced. Signed-off-by: Mimi Zohar <[email protected]> Cc: James Morris <[email protected]> Acked-by: Serge Hallyn <[email protected]> Cc: David Safford <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int ima_lsm_rule_init(struct ima_measure_rule_entry *entry, char *args, int lsm_rule, int audit_type) { int result; if (entry->lsm[lsm_rule].rule) return -EINVAL; entry->lsm[lsm_rule].type = audit_type; result = security_filter_rule_init(entry->lsm[lsm_rule].type, Audit_equal, args, &entry->lsm[lsm_rule].rule); if (!entry->lsm[lsm_rule].rule) return -EINVAL; return result; }
165,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) { #if !defined(NACL_WIN64) // We don't need this code on win nacl64. if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } else { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationSwiftShaderName || cmd_line->HasSwitch(switches::kReduceGpuSandbox)) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_LIMITED_USER, JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS); } else { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_RESTRICTED); policy->SetJobLevel(sandbox::JOB_LOCKDOWN, JOB_OBJECT_UILIMIT_HANDLES); } policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } } else { policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetTokenLevel(sandbox::USER_UNPROTECTED, sandbox::USER_LIMITED); } sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_NAMED_PIPES, sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"\\\\.\\pipe\\chrome.gpu.*"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; AddGenericDllEvictionPolicy(policy); #endif return true; } Commit Message: Prevent sandboxed processes from opening each other TBR=brettw BUG=117627 BUG=119150 TEST=sbox_validation_tests Review URL: https://chromiumcodereview.appspot.com/9716027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132477 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) { #if !defined(NACL_WIN64) // We don't need this code on win nacl64. if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationDesktopName) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } else { if (cmd_line->GetSwitchValueASCII(switches::kUseGL) == gfx::kGLImplementationSwiftShaderName || cmd_line->HasSwitch(switches::kReduceGpuSandbox)) { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_LIMITED); policy->SetJobLevel(sandbox::JOB_LIMITED_USER, JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS | JOB_OBJECT_UILIMIT_DESKTOP | JOB_OBJECT_UILIMIT_EXITWINDOWS | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS); } else { policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS, sandbox::USER_RESTRICTED); policy->SetJobLevel(sandbox::JOB_LOCKDOWN, JOB_OBJECT_UILIMIT_HANDLES); // This is a trick to keep the GPU out of low-integrity processes. It // starts at low-integrity for UIPI to work, then drops below // low-integrity after warm-up. policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_UNTRUSTED); } policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW); } } else { policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0); policy->SetTokenLevel(sandbox::USER_UNPROTECTED, sandbox::USER_LIMITED); } sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_NAMED_PIPES, sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY, L"\\\\.\\pipe\\chrome.gpu.*"); if (result != sandbox::SBOX_ALL_OK) return false; result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES, sandbox::TargetPolicy::HANDLES_DUP_ANY, L"Section"); if (result != sandbox::SBOX_ALL_OK) return false; AddGenericDllEvictionPolicy(policy); #endif return true; }
170,911
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; if (s->state != MPI_IOC_STATE_OPERATIONAL) { mptsas_set_fault(s, MPI_IOCSTATUS_INVALID_STATE); return; } /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); } Commit Message: CWE ID: CWE-20
static void mptsas_fetch_request(MPTSASState *s) { PCIDevice *pci = (PCIDevice *) s; char req[MPTSAS_MAX_REQUEST_SIZE]; MPIRequestHeader *hdr = (MPIRequestHeader *)req; hwaddr addr; int size; /* Read the message header from the guest first. */ addr = s->host_mfa_high_addr | MPTSAS_FIFO_GET(s, request_post); pci_dma_read(pci, addr, req, sizeof(hdr)); }
165,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_serial *serial = port->serial; struct usb_serial_port *wport; wport = serial->port[1]; tty_port_tty_set(&wport->port, tty); return usb_serial_generic_open(tty, port); } Commit Message: USB: serial: omninet: fix reference leaks at open This driver needlessly took another reference to the tty on open, a reference which was then never released on close. This lead to not just a leak of the tty, but also a driver reference leak that prevented the driver from being unloaded after a port had once been opened. Fixes: 4a90f09b20f4 ("tty: usb-serial krefs") Cc: stable <[email protected]> # 2.6.28 Signed-off-by: Johan Hovold <[email protected]> CWE ID: CWE-404
static int omninet_open(struct tty_struct *tty, struct usb_serial_port *port) { return usb_serial_generic_open(tty, port); }
168,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess( BrowserContext* browser_context, const GURL& url) { if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites()) return true; if (url.SchemeIs(kChromeErrorScheme)) return true; GURL site_url = SiteInstance::GetSiteForURL(browser_context, url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (policy->IsIsolatedOrigin(url::Origin::Create(site_url))) return true; if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess( browser_context, site_url)) { return true; } return false; } Commit Message: Allow origin lock for WebUI pages. Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps to keep enforcing a SiteInstance swap during chrome://foo -> chrome://bar navigation, even after relaxing BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost (see https://crrev.com/c/783470 for that fixes process sharing in isolated(b(c),d(c)) scenario). I've manually tested this CL by visiting the following URLs: - chrome://welcome/ - chrome://settings - chrome://extensions - chrome://history - chrome://help and chrome://chrome (both redirect to chrome://settings/help) Bug: 510588, 847127 Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971 Reviewed-on: https://chromium-review.googlesource.com/1237392 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: François Doray <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#595259} CWE ID: CWE-119
bool SiteInstanceImpl::DoesSiteRequireDedicatedProcess( BrowserContext* browser_context, const GURL& url) { if (SiteIsolationPolicy::UseDedicatedProcessesForAllSites()) return true; // Always require a dedicated process for isolated origins. GURL site_url = SiteInstance::GetSiteForURL(browser_context, url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); if (policy->IsIsolatedOrigin(url::Origin::Create(site_url))) return true; if (site_url.SchemeIs(kChromeErrorScheme)) return true; // Isolate kChromeUIScheme pages from one another and from other kinds of // schemes. if (site_url.SchemeIs(content::kChromeUIScheme)) return true; if (GetContentClient()->browser()->DoesSiteRequireDedicatedProcess( browser_context, site_url)) { return true; } return false; }
173,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1) { return OMX_ErrorUndefined; } bitRate->eControlRate = OMX_Video_ControlRateVariable; bitRate->nTargetBitrate = mBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } h263type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); h263type->eProfile = OMX_VIDEO_H263ProfileBaseline; h263type->eLevel = OMX_VIDEO_H263Level45; h263type->bPLUSPTYPEAllowed = OMX_FALSE; h263type->bForceRoundingTypeToZero = OMX_FALSE; h263type->nPictureHeaderRepetition = 0; h263type->nGOBHeaderInterval = 0; return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore; mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2; mpeg4type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); mpeg4type->nBFrames = 0; mpeg4type->nIDCVLCThreshold = 0; mpeg4type->bACPred = OMX_TRUE; mpeg4type->nMaxPacketSize = 256; mpeg4type->nTimeIncRes = 1000; mpeg4type->nHeaderExtension = 0; mpeg4type->bReversibleVLC = OMX_FALSE; return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (!isValidOMXParam(bitRate)) { return OMX_ErrorBadParameter; } if (bitRate->nPortIndex != 1) { return OMX_ErrorUndefined; } bitRate->eControlRate = OMX_Video_ControlRateVariable; bitRate->nTargetBitrate = mBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoH263: { OMX_VIDEO_PARAM_H263TYPE *h263type = (OMX_VIDEO_PARAM_H263TYPE *)params; if (!isValidOMXParam(h263type)) { return OMX_ErrorBadParameter; } if (h263type->nPortIndex != 1) { return OMX_ErrorUndefined; } h263type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); h263type->eProfile = OMX_VIDEO_H263ProfileBaseline; h263type->eLevel = OMX_VIDEO_H263Level45; h263type->bPLUSPTYPEAllowed = OMX_FALSE; h263type->bForceRoundingTypeToZero = OMX_FALSE; h263type->nPictureHeaderRepetition = 0; h263type->nGOBHeaderInterval = 0; return OMX_ErrorNone; } case OMX_IndexParamVideoMpeg4: { OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type = (OMX_VIDEO_PARAM_MPEG4TYPE *)params; if (!isValidOMXParam(mpeg4type)) { return OMX_ErrorBadParameter; } if (mpeg4type->nPortIndex != 1) { return OMX_ErrorUndefined; } mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore; mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2; mpeg4type->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP); mpeg4type->nBFrames = 0; mpeg4type->nIDCVLCThreshold = 0; mpeg4type->bACPred = OMX_TRUE; mpeg4type->nMaxPacketSize = 256; mpeg4type->nTimeIncRes = 1000; mpeg4type->nHeaderExtension = 0; mpeg4type->bReversibleVLC = OMX_FALSE; return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, params); } }
174,209
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void Sp_replace_regexp(js_State *J) { js_Regexp *re; const char *source, *s, *r; js_Buffer *sb = NULL; int n, x; Resub m; source = checkstring(J, 0); re = js_toregexp(J, 1); if (js_regexec(re->prog, source, &m, 0)) { js_copy(J, 0); return; } re->last = 0; loop: s = m.sub[0].sp; n = m.sub[0].ep - m.sub[0].sp; if (js_iscallable(J, 2)) { js_copy(J, 2); js_pushundefined(J); for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */ js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp); js_pushnumber(J, s - source); /* arg x+2: offset within search string */ js_copy(J, 0); /* arg x+3: search string */ js_call(J, 2 + x); r = js_tostring(J, -1); js_putm(J, &sb, source, s); js_puts(J, &sb, r); js_pop(J, 1); } else { r = js_tostring(J, 2); js_putm(J, &sb, source, s); while (*r) { if (*r == '$') { switch (*(++r)) { case 0: --r; /* end of string; back up */ /* fallthrough */ case '$': js_putc(J, &sb, '$'); break; case '`': js_putm(J, &sb, source, s); break; case '\'': js_puts(J, &sb, s + n); break; case '&': js_putm(J, &sb, s, s + n); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': x = *r - '0'; if (r[1] >= '0' && r[1] <= '9') x = x * 10 + *(++r) - '0'; if (x > 0 && x < m.nsub) { js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep); } else { js_putc(J, &sb, '$'); if (x > 10) { js_putc(J, &sb, '0' + x / 10); js_putc(J, &sb, '0' + x % 10); } else { js_putc(J, &sb, '0' + x); } } break; default: js_putc(J, &sb, '$'); js_putc(J, &sb, *r); break; } ++r; } else { js_putc(J, &sb, *r++); } } } if (re->flags & JS_REGEXP_G) { source = m.sub[0].ep; if (n == 0) { if (*source) js_putc(J, &sb, *source++); else goto end; } if (!js_regexec(re->prog, source, &m, REG_NOTBOL)) goto loop; } end: js_puts(J, &sb, s + n); js_putc(J, &sb, 0); if (js_try(J)) { js_free(J, sb); js_throw(J); } js_pushstring(J, sb ? sb->s : ""); js_endtry(J); js_free(J, sb); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400
static void Sp_replace_regexp(js_State *J) { js_Regexp *re; const char *source, *s, *r; js_Buffer *sb = NULL; int n, x; Resub m; source = checkstring(J, 0); re = js_toregexp(J, 1); if (js_doregexec(J, re->prog, source, &m, 0)) { js_copy(J, 0); return; } re->last = 0; loop: s = m.sub[0].sp; n = m.sub[0].ep - m.sub[0].sp; if (js_iscallable(J, 2)) { js_copy(J, 2); js_pushundefined(J); for (x = 0; m.sub[x].sp; ++x) /* arg 0..x: substring and subexps that matched */ js_pushlstring(J, m.sub[x].sp, m.sub[x].ep - m.sub[x].sp); js_pushnumber(J, s - source); /* arg x+2: offset within search string */ js_copy(J, 0); /* arg x+3: search string */ js_call(J, 2 + x); r = js_tostring(J, -1); js_putm(J, &sb, source, s); js_puts(J, &sb, r); js_pop(J, 1); } else { r = js_tostring(J, 2); js_putm(J, &sb, source, s); while (*r) { if (*r == '$') { switch (*(++r)) { case 0: --r; /* end of string; back up */ /* fallthrough */ case '$': js_putc(J, &sb, '$'); break; case '`': js_putm(J, &sb, source, s); break; case '\'': js_puts(J, &sb, s + n); break; case '&': js_putm(J, &sb, s, s + n); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': x = *r - '0'; if (r[1] >= '0' && r[1] <= '9') x = x * 10 + *(++r) - '0'; if (x > 0 && x < m.nsub) { js_putm(J, &sb, m.sub[x].sp, m.sub[x].ep); } else { js_putc(J, &sb, '$'); if (x > 10) { js_putc(J, &sb, '0' + x / 10); js_putc(J, &sb, '0' + x % 10); } else { js_putc(J, &sb, '0' + x); } } break; default: js_putc(J, &sb, '$'); js_putc(J, &sb, *r); break; } ++r; } else { js_putc(J, &sb, *r++); } } } if (re->flags & JS_REGEXP_G) { source = m.sub[0].ep; if (n == 0) { if (*source) js_putc(J, &sb, *source++); else goto end; } if (!js_doregexec(J, re->prog, source, &m, REG_NOTBOL)) goto loop; } end: js_puts(J, &sb, s + n); js_putc(J, &sb, 0); if (js_try(J)) { js_free(J, sb); js_throw(J); } js_pushstring(J, sb ? sb->s : ""); js_endtry(J); js_free(J, sb); }
169,699
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { const xmlChar *in; int nbchar = 0; int line = ctxt->input->line; int col = ctxt->input->col; int ccol; SHRINK; GROW; /* * Accelerated common case where input don't need to be * modified before passing it to the handler. */ if (!cdata) { in = ctxt->input->cur; do { get_more_space: while (*in == 0x20) { in++; ctxt->input->col++; } if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more_space; } if (*in == '<') { nbchar = in - ctxt->input->cur; if (nbchar > 0) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters)) { if (areBlanks(ctxt, tmp, nbchar, 1)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } } else if ((ctxt->sax != NULL) && (ctxt->sax->characters != NULL)) { ctxt->sax->characters(ctxt->userData, tmp, nbchar); } } return; } get_more: ccol = ctxt->input->col; while (test_char_data[*in]) { in++; ccol++; } ctxt->input->col = ccol; if (*in == 0xA) { do { ctxt->input->line++; ctxt->input->col = 1; in++; } while (*in == 0xA); goto get_more; } if (*in == ']') { if ((in[1] == ']') && (in[2] == '>')) { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); ctxt->input->cur = in; return; } in++; ctxt->input->col++; goto get_more; } nbchar = in - ctxt->input->cur; if (nbchar > 0) { if ((ctxt->sax != NULL) && (ctxt->sax->ignorableWhitespace != ctxt->sax->characters) && (IS_BLANK_CH(*ctxt->input->cur))) { const xmlChar *tmp = ctxt->input->cur; ctxt->input->cur = in; if (areBlanks(ctxt, tmp, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, tmp, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, tmp, nbchar); if (*ctxt->space == -1) *ctxt->space = -2; } line = ctxt->input->line; col = ctxt->input->col; } else if (ctxt->sax != NULL) { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, ctxt->input->cur, nbchar); line = ctxt->input->line; col = ctxt->input->col; } /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } ctxt->input->cur = in; if (*in == 0xD) { in++; if (*in == 0xA) { ctxt->input->cur = in; in++; ctxt->input->line++; ctxt->input->col = 1; continue; /* while */ } in--; } if (*in == '<') { return; } if (*in == '&') { return; } SHRINK; GROW; if (ctxt->instate == XML_PARSER_EOF) return; in = ctxt->input->cur; } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); nbchar = 0; } ctxt->input->line = line; ctxt->input->col = col; xmlParseCharDataComplex(ctxt, cdata); }
171,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool glfs_check_config(const char *cfgstring, char **reason) { char *path; glfs_t *fs = NULL; glfs_fd_t *gfd = NULL; gluster_server *hosts = NULL; /* gluster server defination */ bool result = true; path = strchr(cfgstring, '/'); if (!path) { if (asprintf(reason, "No path found") == -1) *reason = NULL; result = false; goto done; } path += 1; /* get past '/' */ fs = tcmu_create_glfs_object(path, &hosts); if (!fs) { tcmu_err("tcmu_create_glfs_object failed\n"); goto done; } gfd = glfs_open(fs, hosts->path, ALLOWED_BSOFLAGS); if (!gfd) { if (asprintf(reason, "glfs_open failed: %m") == -1) *reason = NULL; result = false; goto unref; } if (glfs_access(fs, hosts->path, R_OK|W_OK) == -1) { if (asprintf(reason, "glfs_access file not present, or not writable") == -1) *reason = NULL; result = false; goto unref; } goto done; unref: gluster_cache_refresh(fs, path); done: if (gfd) glfs_close(gfd); gluster_free_server(&hosts); return result; } Commit Message: glfs: discard glfs_check_config Signed-off-by: Prasanna Kumar Kalever <[email protected]> CWE ID: CWE-119
static bool glfs_check_config(const char *cfgstring, char **reason)
167,635
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GpuVideoDecodeAccelerator::OnDecode( base::SharedMemoryHandle handle, int32 id, int32 size) { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size)); } Commit Message: Sizes going across an IPC should be uint32. BUG=164946 Review URL: https://chromiumcodereview.appspot.com/11472038 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171944 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void GpuVideoDecodeAccelerator::OnDecode( base::SharedMemoryHandle handle, int32 id, uint32 size) { DCHECK(video_decode_accelerator_.get()); video_decode_accelerator_->Decode(media::BitstreamBuffer(id, handle, size)); }
171,407
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int remove_bond(const bt_bdaddr_t *bd_addr) { /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static int remove_bond(const bt_bdaddr_t *bd_addr) { if (is_restricted_mode() && !btif_storage_is_restricted_device(bd_addr)) return BT_STATUS_SUCCESS; /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); }
173,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LogoService::LogoService( const base::FilePath& cache_directory, TemplateURLService* template_url_service, std::unique_ptr<image_fetcher::ImageDecoder> image_decoder, scoped_refptr<net::URLRequestContextGetter> request_context_getter, bool use_gray_background) : cache_directory_(cache_directory), template_url_service_(template_url_service), request_context_getter_(request_context_getter), use_gray_background_(use_gray_background), image_decoder_(std::move(image_decoder)) {} Commit Message: Local NTP: add smoke tests for doodles Split LogoService into LogoService interface and LogoServiceImpl to make it easier to provide fake data to the test. Bug: 768419 Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation Change-Id: I84639189d2db1b24a2e139936c99369352bab587 Reviewed-on: https://chromium-review.googlesource.com/690198 Reviewed-by: Sylvain Defresne <[email protected]> Reviewed-by: Marc Treib <[email protected]> Commit-Queue: Chris Pickel <[email protected]> Cr-Commit-Position: refs/heads/master@{#505374} CWE ID: CWE-119
LogoService::LogoService(
171,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cipso_v4_delopt(struct ip_options **opt_ptr) { int hdr_delta = 0; struct ip_options *opt = *opt_ptr; if (opt->srr || opt->rr || opt->ts || opt->router_alert) { u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int iter; int optlen_new; cipso_off = opt->cipso - sizeof(struct iphdr); cipso_ptr = &opt->__data[cipso_off]; cipso_len = cipso_ptr[1]; if (opt->srr > opt->cipso) opt->srr -= cipso_len; if (opt->rr > opt->cipso) opt->rr -= cipso_len; if (opt->ts > opt->cipso) opt->ts -= cipso_len; if (opt->router_alert > opt->cipso) opt->router_alert -= cipso_len; opt->cipso = 0; memmove(cipso_ptr, cipso_ptr + cipso_len, opt->optlen - cipso_off - cipso_len); /* determining the new total option length is tricky because of * the padding necessary, the only thing i can think to do at * this point is walk the options one-by-one, skipping the * padding at the end to determine the actual option size and * from there we can determine the new total option length */ iter = 0; optlen_new = 0; while (iter < opt->optlen) if (opt->__data[iter] != IPOPT_NOP) { iter += opt->__data[iter + 1]; optlen_new = iter; } else iter++; hdr_delta = opt->optlen; opt->optlen = (optlen_new + 3) & ~3; hdr_delta -= opt->optlen; } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ *opt_ptr = NULL; hdr_delta = opt->optlen; kfree(opt); } return hdr_delta; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static int cipso_v4_delopt(struct ip_options **opt_ptr) static int cipso_v4_delopt(struct ip_options_rcu **opt_ptr) { int hdr_delta = 0; struct ip_options_rcu *opt = *opt_ptr; if (opt->opt.srr || opt->opt.rr || opt->opt.ts || opt->opt.router_alert) { u8 cipso_len; u8 cipso_off; unsigned char *cipso_ptr; int iter; int optlen_new; cipso_off = opt->opt.cipso - sizeof(struct iphdr); cipso_ptr = &opt->opt.__data[cipso_off]; cipso_len = cipso_ptr[1]; if (opt->opt.srr > opt->opt.cipso) opt->opt.srr -= cipso_len; if (opt->opt.rr > opt->opt.cipso) opt->opt.rr -= cipso_len; if (opt->opt.ts > opt->opt.cipso) opt->opt.ts -= cipso_len; if (opt->opt.router_alert > opt->opt.cipso) opt->opt.router_alert -= cipso_len; opt->opt.cipso = 0; memmove(cipso_ptr, cipso_ptr + cipso_len, opt->opt.optlen - cipso_off - cipso_len); /* determining the new total option length is tricky because of * the padding necessary, the only thing i can think to do at * this point is walk the options one-by-one, skipping the * padding at the end to determine the actual option size and * from there we can determine the new total option length */ iter = 0; optlen_new = 0; while (iter < opt->opt.optlen) if (opt->opt.__data[iter] != IPOPT_NOP) { iter += opt->opt.__data[iter + 1]; optlen_new = iter; } else iter++; hdr_delta = opt->opt.optlen; opt->opt.optlen = (optlen_new + 3) & ~3; hdr_delta -= opt->opt.optlen; } else { /* only the cipso option was present on the socket so we can * remove the entire option struct */ *opt_ptr = NULL; hdr_delta = opt->opt.optlen; call_rcu(&opt->rcu, opt_kfree_rcu); } return hdr_delta; }
165,546
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: i915_gem_execbuffer2(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list = NULL; int ret; if (args->buffer_count < 1) { DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count); return -EINVAL; } exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (exec2_list == NULL) exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %d buffers\n", args->buffer_count); return -ENOMEM; } ret = copy_from_user(exec2_list, (struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, sizeof(*exec2_list) * args->buffer_count); if (ret != 0) { DRM_DEBUG("copy %d exec entries failed %d\n", args->buffer_count, ret); drm_free_large(exec2_list); return -EFAULT; } ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list); if (!ret) { /* Copy the new buffer offsets back to the user's exec list. */ ret = copy_to_user((struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, exec2_list, sizeof(*exec2_list) * args->buffer_count); if (ret) { ret = -EFAULT; DRM_DEBUG("failed to copy %d exec entries " "back to user (%d)\n", args->buffer_count, ret); } } drm_free_large(exec2_list); return ret; } Commit Message: drm/i915: fix integer overflow in i915_gem_execbuffer2() On 32-bit systems, a large args->buffer_count from userspace via ioctl may overflow the allocation size, leading to out-of-bounds access. This vulnerability was introduced in commit 8408c282 ("drm/i915: First try a normal large kmalloc for the temporary exec buffers"). Signed-off-by: Xi Wang <[email protected]> Reviewed-by: Chris Wilson <[email protected]> Cc: [email protected] Signed-off-by: Daniel Vetter <[email protected]> CWE ID: CWE-189
i915_gem_execbuffer2(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_execbuffer2 *args = data; struct drm_i915_gem_exec_object2 *exec2_list = NULL; int ret; if (args->buffer_count < 1 || args->buffer_count > UINT_MAX / sizeof(*exec2_list)) { DRM_DEBUG("execbuf2 with %d buffers\n", args->buffer_count); return -EINVAL; } exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); if (exec2_list == NULL) exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); if (exec2_list == NULL) { DRM_DEBUG("Failed to allocate exec list for %d buffers\n", args->buffer_count); return -ENOMEM; } ret = copy_from_user(exec2_list, (struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, sizeof(*exec2_list) * args->buffer_count); if (ret != 0) { DRM_DEBUG("copy %d exec entries failed %d\n", args->buffer_count, ret); drm_free_large(exec2_list); return -EFAULT; } ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list); if (!ret) { /* Copy the new buffer offsets back to the user's exec list. */ ret = copy_to_user((struct drm_i915_relocation_entry __user *) (uintptr_t) args->buffers_ptr, exec2_list, sizeof(*exec2_list) * args->buffer_count); if (ret) { ret = -EFAULT; DRM_DEBUG("failed to copy %d exec entries " "back to user (%d)\n", args->buffer_count, ret); } } drm_free_large(exec2_list); return ret; }
165,597
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsRequestFunction::RunImpl() { if (!user_gesture() && !ignore_user_gesture_for_tests) { error_ = kUserGestureRequiredError; return false; } scoped_ptr<Request::Params> params(Request::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); requested_permissions_ = helpers::UnpackPermissionSet(params->permissions, &error_); if (!requested_permissions_.get()) return false; extensions::ExtensionPrefs* prefs = profile()->GetExtensionService()->extension_prefs(); APIPermissionSet apis = requested_permissions_->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } scoped_refptr<extensions::PermissionSet> manifest_required_requested_permissions = PermissionSet::ExcludeNotInManifestPermissions( requested_permissions_.get()); if (!GetExtension()->optional_permission_set()->Contains( *manifest_required_requested_permissions)) { error_ = kNotInOptionalPermissionsError; results_ = Request::Results::Create(false); return false; } scoped_refptr<const PermissionSet> granted = prefs->GetGrantedPermissions(GetExtension()->id()); if (granted.get() && granted->Contains(*requested_permissions_)) { PermissionsUpdater perms_updater(profile()); perms_updater.AddPermissions(GetExtension(), requested_permissions_.get()); results_ = Request::Results::Create(true); SendResponse(true); return true; } requested_permissions_ = PermissionSet::CreateDifference( requested_permissions_.get(), granted.get()); AddRef(); // Balanced in InstallUIProceed() / InstallUIAbort(). bool has_no_warnings = requested_permissions_->GetWarningMessages( GetExtension()->GetType()).empty(); if (auto_confirm_for_tests == PROCEED || has_no_warnings) { InstallUIProceed(); } else if (auto_confirm_for_tests == ABORT) { InstallUIAbort(true); } else { CHECK_EQ(DO_NOT_SKIP, auto_confirm_for_tests); install_ui_.reset(new ExtensionInstallPrompt(GetAssociatedWebContents())); install_ui_->ConfirmPermissions( this, GetExtension(), requested_permissions_.get()); } return true; } Commit Message: Check prefs before allowing extension file access in the permissions API. [email protected] BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsRequestFunction::RunImpl() { results_ = Request::Results::Create(false); if (!user_gesture() && !ignore_user_gesture_for_tests) { error_ = kUserGestureRequiredError; return false; } scoped_ptr<Request::Params> params(Request::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs(); requested_permissions_ = helpers::UnpackPermissionSet(params->permissions, prefs->AllowFileAccess(extension_->id()), &error_); if (!requested_permissions_.get()) return false; APIPermissionSet apis = requested_permissions_->apis(); for (APIPermissionSet::const_iterator i = apis.begin(); i != apis.end(); ++i) { if (!i->info()->supports_optional()) { error_ = ErrorUtils::FormatErrorMessage( kNotWhitelistedError, i->name()); return false; } } scoped_refptr<extensions::PermissionSet> manifest_required_requested_permissions = PermissionSet::ExcludeNotInManifestPermissions( requested_permissions_.get()); if (!GetExtension()->optional_permission_set()->Contains( *manifest_required_requested_permissions)) { error_ = kNotInOptionalPermissionsError; results_ = Request::Results::Create(false); return false; } scoped_refptr<const PermissionSet> granted = prefs->GetGrantedPermissions(GetExtension()->id()); if (granted.get() && granted->Contains(*requested_permissions_)) { PermissionsUpdater perms_updater(profile()); perms_updater.AddPermissions(GetExtension(), requested_permissions_.get()); results_ = Request::Results::Create(true); SendResponse(true); return true; } requested_permissions_ = PermissionSet::CreateDifference( requested_permissions_.get(), granted.get()); AddRef(); // Balanced in InstallUIProceed() / InstallUIAbort(). bool has_no_warnings = requested_permissions_->GetWarningMessages( GetExtension()->GetType()).empty(); if (auto_confirm_for_tests == PROCEED || has_no_warnings) { InstallUIProceed(); } else if (auto_confirm_for_tests == ABORT) { InstallUIAbort(true); } else { CHECK_EQ(DO_NOT_SKIP, auto_confirm_for_tests); install_ui_.reset(new ExtensionInstallPrompt(GetAssociatedWebContents())); install_ui_->ConfirmPermissions( this, GetExtension(), requested_permissions_.get()); } return true; }
171,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save) { os_ptr op = osp; int code; ref token; /* Note that gs_scan_token may change osp! */ pop(1); /* remove the file or scanner state */ again: gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object); break; case scan_BOS: code = 0; case 0: /* read a token */ push(2); ref_assign(op - 1, &token); make_true(op); break; case scan_EOF: /* no tokens */ push(1); make_false(op); code = 0; break; case scan_Refill: /* need more data */ code = gs_scan_handle_refill(i_ctx_p, pstate, save, ztoken_continue); switch (code) { case 0: /* state is not copied to the heap */ goto again; case o_push_estack: return code; } break; /* error */ } Commit Message: CWE ID: CWE-125
token_continue(i_ctx_t *i_ctx_p, scanner_state * pstate, bool save) { os_ptr op = osp; int code; ref token; /* Since we might free pstate below, and we're dealing with * gc memory referenced by the stack, we need to explicitly * remove the reference to pstate from the stack, otherwise * the garbager will fall over */ make_null(osp); /* Note that gs_scan_token may change osp! */ pop(1); /* remove the file or scanner state */ again: gs_scanner_error_object(i_ctx_p, pstate, &i_ctx_p->error_object); break; case scan_BOS: code = 0; case 0: /* read a token */ push(2); ref_assign(op - 1, &token); make_true(op); break; case scan_EOF: /* no tokens */ push(1); make_false(op); code = 0; break; case scan_Refill: /* need more data */ code = gs_scan_handle_refill(i_ctx_p, pstate, save, ztoken_continue); switch (code) { case 0: /* state is not copied to the heap */ goto again; case o_push_estack: return code; } break; /* error */ }
164,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: enum ImapAuthRes imap_auth_cram_md5(struct ImapData *idata, const char *method) { char ibuf[LONG_STRING * 2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset(idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message(_("Authenticating (CRAM-MD5)...")); /* get auth info */ if (mutt_account_getlogin(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; imap_cmd_start(idata, "AUTHENTICATE CRAM-MD5"); /* From RFC2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { mutt_debug(1, "Invalid response from server: %s\n", ibuf); goto bail; } len = mutt_b64_decode(obuf, idata->buf + 2); if (len == -1) { mutt_debug(1, "Error decoding base64 response.\n"); goto bail; } obuf[len] = '\0'; mutt_debug(2, "CRAM challenge: %s\n", obuf); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5(idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ int off = snprintf(obuf, sizeof(obuf), "%s ", idata->conn->account.user); mutt_md5_toascii(hmac_response, obuf + off); mutt_debug(2, "CRAM response: %s\n", obuf); /* ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_b64_encode(ibuf, obuf, strlen(obuf), sizeof(ibuf) - 2); mutt_str_strcat(ibuf, sizeof(ibuf), "\r\n"); mutt_socket_send(idata->conn, ibuf); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { mutt_debug(1, "Error receiving server response.\n"); goto bail; } if (imap_code(idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error(_("CRAM-MD5 authentication failed.")); return IMAP_AUTH_FAILURE; } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
enum ImapAuthRes imap_auth_cram_md5(struct ImapData *idata, const char *method) { char ibuf[LONG_STRING * 2], obuf[LONG_STRING]; unsigned char hmac_response[MD5_DIGEST_LEN]; int len; int rc; if (!mutt_bit_isset(idata->capabilities, ACRAM_MD5)) return IMAP_AUTH_UNAVAIL; mutt_message(_("Authenticating (CRAM-MD5)...")); /* get auth info */ if (mutt_account_getlogin(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; if (mutt_account_getpass(&idata->conn->account) < 0) return IMAP_AUTH_FAILURE; imap_cmd_start(idata, "AUTHENTICATE CRAM-MD5"); /* From RFC2195: * The data encoded in the first ready response contains a presumptively * arbitrary string of random digits, a timestamp, and the fully-qualified * primary host name of the server. The syntax of the unencoded form must * correspond to that of an RFC822 'msg-id' [RFC822] as described in [POP3]. */ do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_RESPOND) { mutt_debug(1, "Invalid response from server: %s\n", ibuf); goto bail; } len = mutt_b64_decode(obuf, idata->buf + 2, sizeof(obuf)); if (len == -1) { mutt_debug(1, "Error decoding base64 response.\n"); goto bail; } obuf[len] = '\0'; mutt_debug(2, "CRAM challenge: %s\n", obuf); /* The client makes note of the data and then responds with a string * consisting of the user name, a space, and a 'digest'. The latter is * computed by applying the keyed MD5 algorithm from [KEYED-MD5] where the * key is a shared secret and the digested text is the timestamp (including * angle-brackets). * * Note: The user name shouldn't be quoted. Since the digest can't contain * spaces, there is no ambiguity. Some servers get this wrong, we'll work * around them when the bug report comes in. Until then, we'll remain * blissfully RFC-compliant. */ hmac_md5(idata->conn->account.pass, obuf, hmac_response); /* dubious optimisation I saw elsewhere: make the whole string in one call */ int off = snprintf(obuf, sizeof(obuf), "%s ", idata->conn->account.user); mutt_md5_toascii(hmac_response, obuf + off); mutt_debug(2, "CRAM response: %s\n", obuf); /* ibuf must be long enough to store the base64 encoding of obuf, * plus the additional debris */ mutt_b64_encode(ibuf, obuf, strlen(obuf), sizeof(ibuf) - 2); mutt_str_strcat(ibuf, sizeof(ibuf), "\r\n"); mutt_socket_send(idata->conn, ibuf); do rc = imap_cmd_step(idata); while (rc == IMAP_CMD_CONTINUE); if (rc != IMAP_CMD_OK) { mutt_debug(1, "Error receiving server response.\n"); goto bail; } if (imap_code(idata->buf)) return IMAP_AUTH_SUCCESS; bail: mutt_error(_("CRAM-MD5 authentication failed.")); return IMAP_AUTH_FAILURE; }
169,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAACEncoder2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = (OMX_AUDIO_AACPROFILETYPE) mAACProfile; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; switch (mSBRMode) { case 1: // sbr on switch (mSBRRatio) { case 0: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case 1: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR ratio %d", mSBRRatio); TRESPASS(); } break; case 0: // sbr off case -1: // sbr undefined aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR mode %d", mSBRMode); TRESPASS(); } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAACEncoder2::internalGetParameter( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPortFormat: { OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } formatParams->eEncoding = (formatParams->nPortIndex == 0) ? OMX_AUDIO_CodingPCM : OMX_AUDIO_CodingAAC; return OMX_ErrorNone; } case OMX_IndexParamAudioAac: { OMX_AUDIO_PARAM_AACPROFILETYPE *aacParams = (OMX_AUDIO_PARAM_AACPROFILETYPE *)params; if (!isValidOMXParam(aacParams)) { return OMX_ErrorBadParameter; } if (aacParams->nPortIndex != 1) { return OMX_ErrorUndefined; } aacParams->nBitRate = mBitRate; aacParams->nAudioBandWidth = 0; aacParams->nAACtools = 0; aacParams->nAACERtools = 0; aacParams->eAACProfile = (OMX_AUDIO_AACPROFILETYPE) mAACProfile; aacParams->eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF; aacParams->eChannelMode = OMX_AUDIO_ChannelModeStereo; aacParams->nChannels = mNumChannels; aacParams->nSampleRate = mSampleRate; aacParams->nFrameLength = 0; switch (mSBRMode) { case 1: // sbr on switch (mSBRRatio) { case 0: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; case 1: aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; case 2: aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools |= OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR ratio %d", mSBRRatio); TRESPASS(); } break; case 0: // sbr off case -1: // sbr undefined aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidSSBR; aacParams->nAACtools &= ~OMX_AUDIO_AACToolAndroidDSBR; break; default: ALOGE("invalid SBR mode %d", mSBRMode); TRESPASS(); } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } pcmParams->eNumData = OMX_NumericalDataSigned; pcmParams->eEndian = OMX_EndianBig; pcmParams->bInterleaved = OMX_TRUE; pcmParams->nBitPerSample = 16; pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear; pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF; pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF; pcmParams->nChannels = mNumChannels; pcmParams->nSamplingRate = mSampleRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalGetParameter(index, params); } }
174,190
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen) { UNUSED(msg_evt); BTIF_TRACE_DEBUG("UIPC_Send : ch_id:%d %d bytes", ch_id, msglen); UIPC_LOCK(); if (write(uipc_main.ch[ch_id].fd, p_buf, msglen) < 0) { BTIF_TRACE_ERROR("failed to write (%s)", strerror(errno)); } UIPC_UNLOCK(); return FALSE; } 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
BOOLEAN UIPC_Send(tUIPC_CH_ID ch_id, UINT16 msg_evt, UINT8 *p_buf, UINT16 msglen) { UNUSED(msg_evt); BTIF_TRACE_DEBUG("UIPC_Send : ch_id:%d %d bytes", ch_id, msglen); UIPC_LOCK(); if (TEMP_FAILURE_RETRY(write(uipc_main.ch[ch_id].fd, p_buf, msglen)) < 0) { BTIF_TRACE_ERROR("failed to write (%s)", strerror(errno)); } UIPC_UNLOCK(); return FALSE; }
173,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { uch sig[8]; /* first do a quick check that the file really is a PNG image; could * have used slightly more general png_sig_cmp() function instead */ fread(sig, 1, 8, infile); if (png_sig_cmp(sig, 0, 8)) return 1; /* bad signature */ /* could pass pointers to user-defined error handlers instead of NULLs: */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); *pWidth = width; *pHeight = height; /* OK, that's all we need for now; return happy */ return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { uch sig[8]; /* first do a quick check that the file really is a PNG image; could * have used slightly more general png_sig_cmp() function instead */ fread(sig, 1, 8, infile); if (png_sig_cmp(sig, 0, 8)) return 1; /* bad signature */ /* could pass pointers to user-defined error handlers instead of NULLs: */ png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), NULL, NULL, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); *pWidth = width; *pHeight = height; /* OK, that's all we need for now; return happy */ return 0; }
173,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(); check_return_status(status); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
void bdt_enable(void) { bdt_log("ENABLE BT"); if (bt_enabled) { bdt_log("Bluetooth is already enabled"); return; } status = sBtInterface->enable(false); check_return_status(status); }
173,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int test_sqr(BIO *bp, BN_CTX *ctx) { BIGNUM a,c,d,e; int i; BN_init(&a); BN_init(&c); BN_init(&d); BN_init(&e); for (i=0; i<num0; i++) { BN_bntest_rand(&a,40+i*10,0,0); a.neg=rand_neg(); BN_sqr(&c,&a,ctx); if (bp != NULL) { if (!results) { BN_print(bp,&a); BIO_puts(bp," * "); BN_print(bp,&a); BIO_puts(bp," - "); } BN_print(bp,&c); BIO_puts(bp,"\n"); } BN_div(&d,&e,&c,&a,ctx); BN_sub(&d,&d,&a); if(!BN_is_zero(&d) || !BN_is_zero(&e)) { fprintf(stderr,"Square test failed!\n"); return 0; } } BN_free(&a); BN_free(&c); BN_free(&d); BN_free(&e); return(1); } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310
int test_sqr(BIO *bp, BN_CTX *ctx) { BIGNUM *a,*c,*d,*e; int i, ret = 0; a = BN_new(); c = BN_new(); d = BN_new(); e = BN_new(); if (a == NULL || c == NULL || d == NULL || e == NULL) { goto err; } for (i=0; i<num0; i++) { BN_bntest_rand(a,40+i*10,0,0); a->neg=rand_neg(); BN_sqr(c,a,ctx); if (bp != NULL) { if (!results) { BN_print(bp,a); BIO_puts(bp," * "); BN_print(bp,a); BIO_puts(bp," - "); } BN_print(bp,c); BIO_puts(bp,"\n"); } BN_div(d,e,c,a,ctx); BN_sub(d,d,a); if(!BN_is_zero(d) || !BN_is_zero(e)) { fprintf(stderr,"Square test failed!\n"); goto err; } } /* Regression test for a BN_sqr overflow bug. */ BN_hex2bn(&a, "80000000000000008000000000000001FFFFFFFFFFFFFFFE0000000000000000"); BN_sqr(c, a, ctx); if (bp != NULL) { if (!results) { BN_print(bp,a); BIO_puts(bp," * "); BN_print(bp,a); BIO_puts(bp," - "); } BN_print(bp,c); BIO_puts(bp,"\n"); } BN_mul(d, a, a, ctx); if (BN_cmp(c, d)) { fprintf(stderr, "Square test failed: BN_sqr and BN_mul produce " "different results!\n"); goto err; } /* Regression test for a BN_sqr overflow bug. */ BN_hex2bn(&a, "80000000000000000000000080000001FFFFFFFE000000000000000000000000"); BN_sqr(c, a, ctx); if (bp != NULL) { if (!results) { BN_print(bp,a); BIO_puts(bp," * "); BN_print(bp,a); BIO_puts(bp," - "); } BN_print(bp,c); BIO_puts(bp,"\n"); } BN_mul(d, a, a, ctx); if (BN_cmp(c, d)) { fprintf(stderr, "Square test failed: BN_sqr and BN_mul produce " "different results!\n"); goto err; } ret = 1; err: if (a != NULL) BN_free(a); if (c != NULL) BN_free(c); if (d != NULL) BN_free(d); if (e != NULL) BN_free(e); return ret; }
166,832
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, const std::string& mime_type) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename, jmime_type); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename, void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename); }
171,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { return gss_verify_mic_iov(minor_status, context_handle, qop_state, iov, iov_count); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_qop_t *qop_state, gss_iov_buffer_desc *iov, int iov_count) { spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); return gss_verify_mic_iov(minor_status, sc->ctx_handle, qop_state, iov, iov_count); }
166,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::didTimeout() void XMLHttpRequest::handleDidTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); m_exceptionCode = TimeoutError; handleDidFailGeneric(); if (!m_async) { m_state = DONE; return; } changeState(DONE); dispatchEventAndLoadEnd(eventNames().timeoutEvent); }
171,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt) { struct svc_rdma_req_map *map = NULL; spin_lock(&xprt->sc_map_lock); if (list_empty(&xprt->sc_maps)) goto out_empty; map = list_first_entry(&xprt->sc_maps, struct svc_rdma_req_map, free); list_del_init(&map->free); spin_unlock(&xprt->sc_map_lock); out: map->count = 0; return map; out_empty: spin_unlock(&xprt->sc_map_lock); /* Pre-allocation amount was incorrect */ map = alloc_req_map(GFP_NOIO); if (map) goto out; WARN_ONCE(1, "svcrdma: empty request map list?\n"); return NULL; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
struct svc_rdma_req_map *svc_rdma_get_req_map(struct svcxprt_rdma *xprt)
168,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: 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; }
171,439
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void process_blob(struct rev_info *revs, struct blob *blob, show_object_fn show, struct strbuf *path, const char *name, void *cb_data) { struct object *obj = &blob->object; if (!revs->blob_objects) return; if (!obj) die("bad blob object"); if (obj->flags & (UNINTERESTING | SEEN)) return; obj->flags |= SEEN; show(obj, path, name, cb_data); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void process_blob(struct rev_info *revs, struct blob *blob, show_object_fn show, struct strbuf *path, const char *name, void *cb_data) { struct object *obj = &blob->object; size_t pathlen; if (!revs->blob_objects) return; if (!obj) die("bad blob object"); if (obj->flags & (UNINTERESTING | SEEN)) return; obj->flags |= SEEN; pathlen = path->len; strbuf_addstr(path, name); show(obj, path->buf, cb_data); strbuf_setlen(path, pathlen); }
167,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long SimpleBlock::Parse()
174,410
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int netlink_dump(struct sock *sk) { struct netlink_sock *nlk = nlk_sk(sk); struct netlink_callback *cb; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; int len, err = -ENOBUFS; int alloc_min_size; int alloc_size; mutex_lock(nlk->cb_mutex); if (!nlk->cb_running) { err = -EINVAL; goto errout_skb; } if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) goto errout_skb; /* NLMSG_GOODSIZE is small to avoid high order allocations being * required, but it makes sense to _attempt_ a 16K bytes allocation * to reduce number of system calls on dump operations, if user * ever provided a big enough buffer. */ cb = &nlk->cb; alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE); if (alloc_min_size < nlk->max_recvmsg_len) { alloc_size = nlk->max_recvmsg_len; skb = alloc_skb(alloc_size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); } if (!skb) { alloc_size = alloc_min_size; skb = alloc_skb(alloc_size, GFP_KERNEL); } if (!skb) goto errout_skb; /* Trim skb to allocated size. User is expected to provide buffer as * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at * netlink_recvmsg())). dump will pack as many smaller messages as * could fit within the allocated skb. skb is typically allocated * with larger space than required (could be as much as near 2x the * requested size with align to next power of 2 approach). Allowing * dump to use the excess space makes it difficult for a user to have a * reasonable static buffer based on the expected largest dump of a * single netdev. The outcome is MSG_TRUNC error. */ skb_reserve(skb, skb_tailroom(skb) - alloc_size); netlink_skb_set_owner_r(skb, sk); len = cb->dump(skb, cb); if (len > 0) { mutex_unlock(nlk->cb_mutex); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); return 0; } nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI); if (!nlh) goto errout_skb; nl_dump_check_consistent(cb, nlh); memcpy(nlmsg_data(nlh), &len, sizeof(len)); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); if (cb->done) cb->done(cb); nlk->cb_running = false; mutex_unlock(nlk->cb_mutex); module_put(cb->module); consume_skb(cb->skb); return 0; errout_skb: mutex_unlock(nlk->cb_mutex); kfree_skb(skb); return err; } Commit Message: netlink: Fix dump skb leak/double free When we free cb->skb after a dump, we do it after releasing the lock. This means that a new dump could have started in the time being and we'll end up freeing their skb instead of ours. This patch saves the skb and module before we unlock so we free the right memory. Fixes: 16b304f3404f ("netlink: Eliminate kmalloc in netlink dump operation.") Reported-by: Baozeng Ding <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Acked-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-415
static int netlink_dump(struct sock *sk) { struct netlink_sock *nlk = nlk_sk(sk); struct netlink_callback *cb; struct sk_buff *skb = NULL; struct nlmsghdr *nlh; struct module *module; int len, err = -ENOBUFS; int alloc_min_size; int alloc_size; mutex_lock(nlk->cb_mutex); if (!nlk->cb_running) { err = -EINVAL; goto errout_skb; } if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) goto errout_skb; /* NLMSG_GOODSIZE is small to avoid high order allocations being * required, but it makes sense to _attempt_ a 16K bytes allocation * to reduce number of system calls on dump operations, if user * ever provided a big enough buffer. */ cb = &nlk->cb; alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE); if (alloc_min_size < nlk->max_recvmsg_len) { alloc_size = nlk->max_recvmsg_len; skb = alloc_skb(alloc_size, GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY); } if (!skb) { alloc_size = alloc_min_size; skb = alloc_skb(alloc_size, GFP_KERNEL); } if (!skb) goto errout_skb; /* Trim skb to allocated size. User is expected to provide buffer as * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at * netlink_recvmsg())). dump will pack as many smaller messages as * could fit within the allocated skb. skb is typically allocated * with larger space than required (could be as much as near 2x the * requested size with align to next power of 2 approach). Allowing * dump to use the excess space makes it difficult for a user to have a * reasonable static buffer based on the expected largest dump of a * single netdev. The outcome is MSG_TRUNC error. */ skb_reserve(skb, skb_tailroom(skb) - alloc_size); netlink_skb_set_owner_r(skb, sk); len = cb->dump(skb, cb); if (len > 0) { mutex_unlock(nlk->cb_mutex); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); return 0; } nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI); if (!nlh) goto errout_skb; nl_dump_check_consistent(cb, nlh); memcpy(nlmsg_data(nlh), &len, sizeof(len)); if (sk_filter(sk, skb)) kfree_skb(skb); else __netlink_sendskb(sk, skb); if (cb->done) cb->done(cb); nlk->cb_running = false; module = cb->module; skb = cb->skb; mutex_unlock(nlk->cb_mutex); module_put(module); consume_skb(skb); return 0; errout_skb: mutex_unlock(nlk->cb_mutex); kfree_skb(skb); return err; }
166,844
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob) { ASSERT(&blob->registry() == this); ThreadableBlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url()); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob) { ASSERT(&blob->registry() == this); BlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url()); }
170,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionTtsController::~ExtensionTtsController() { FinishCurrentUtterance(); ClearUtteranceQueue(); } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController::~ExtensionTtsController() {
170,396
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Block::~Block() { delete[] m_frames; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
Block::~Block()
174,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void xmlrpc_char_encode(char *outbuffer, const char *s1) { long unsigned int i; unsigned char c; char buf2[15]; mowgli_string_t *s = mowgli_string_create(); *buf2 = '\0'; *outbuffer = '\0'; if ((!(s1) || (*(s1) == '\0'))) { return; } for (i = 0; s1[i] != '\0'; i++) { c = s1[i]; if (c > 127) { snprintf(buf2, sizeof buf2, "&#%d;", c); s->append(s, buf2, strlen(buf2)); } else if (c == '&') { s->append(s, "&amp;", 5); } else if (c == '<') { s->append(s, "&lt;", 4); } else if (c == '>') { s->append(s, "&gt;", 4); } else if (c == '"') { s->append(s, "&quot;", 6); } else { s->append_char(s, c); } } memcpy(outbuffer, s->str, XMLRPC_BUFSIZE); } Commit Message: Do not copy more bytes than were allocated CWE ID: CWE-119
void xmlrpc_char_encode(char *outbuffer, const char *s1) { long unsigned int i; unsigned char c; char buf2[15]; mowgli_string_t *s = mowgli_string_create(); *buf2 = '\0'; *outbuffer = '\0'; if ((!(s1) || (*(s1) == '\0'))) { return; } for (i = 0; s1[i] != '\0'; i++) { c = s1[i]; if (c > 127) { snprintf(buf2, sizeof buf2, "&#%d;", c); s->append(s, buf2, strlen(buf2)); } else if (c == '&') { s->append(s, "&amp;", 5); } else if (c == '<') { s->append(s, "&lt;", 4); } else if (c == '>') { s->append(s, "&gt;", 4); } else if (c == '"') { s->append(s, "&quot;", 6); } else { s->append_char(s, c); } } s->append_char(s, 0); strncpy(outbuffer, s->str, XMLRPC_BUFSIZE); }
167,260
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_value( cJSON *item, int depth, int fmt ) { char *out = 0; if ( ! item ) return 0; switch ( ( item->type ) & 255 ) { case cJSON_NULL: out = cJSON_strdup( "null" ); break; case cJSON_False: out = cJSON_strdup( "false" ); break; case cJSON_True: out = cJSON_strdup( "true" ); break; case cJSON_Number: out = print_number( item ); break; case cJSON_String: out = print_string( item ); break; case cJSON_Array: out = print_array( item, depth, fmt ); break; case cJSON_Object: out = print_object( item, depth, fmt ); break; } return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_value( cJSON *item, int depth, int fmt ) static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) { char *out=0; if (!item) return 0; if (p) { switch ((item->type)&255) { case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} case cJSON_Number: out=print_number(item,p);break; case cJSON_String: out=print_string(item,p);break; case cJSON_Array: out=print_array(item,depth,fmt,p);break; case cJSON_Object: out=print_object(item,depth,fmt,p);break; } } else { switch ((item->type)&255) { case cJSON_NULL: out=cJSON_strdup("null"); break; case cJSON_False: out=cJSON_strdup("false");break; case cJSON_True: out=cJSON_strdup("true"); break; case cJSON_Number: out=print_number(item,0);break; case cJSON_String: out=print_string(item,0);break; case cJSON_Array: out=print_array(item,depth,fmt,0);break; case cJSON_Object: out=print_object(item,depth,fmt,0);break; } } return out; }
167,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __be32 nfsacld_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; dprintk("nfsd: SETACL(2acl) %s\n", SVCFH_fmt(&argp->fh)); fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); if (!IS_POSIXACL(inode) || !inode->i_op->set_acl) { error = -EOPNOTSUPP; goto out_errno; } error = fh_want_write(fh); if (error) goto out_errno; error = inode->i_op->set_acl(inode, argp->acl_access, ACL_TYPE_ACCESS); if (error) goto out_drop_write; error = inode->i_op->set_acl(inode, argp->acl_default, ACL_TYPE_DEFAULT); if (error) goto out_drop_write; fh_drop_write(fh); nfserr = fh_getattr(fh, &resp->stat); out: /* argp->acl_{access,default} may have been allocated in nfssvc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); return nfserr; out_drop_write: fh_drop_write(fh); out_errno: nfserr = nfserrno(error); goto out; } Commit Message: nfsd: check permissions when setting ACLs Use set_posix_acl, which includes proper permission checks, instead of calling ->set_acl directly. Without this anyone may be able to grant themselves permissions to a file by setting the ACL. Lock the inode to make the new checks atomic with respect to set_acl. (Also, nfsd was the only caller of set_acl not locking the inode, so I suspect this may fix other races.) This also simplifies the code, and ensures our ACLs are checked by posix_acl_valid. The permission checks and the inode locking were lost with commit 4ac7249e, which changed nfsd to use the set_acl inode operation directly instead of going through xattr handlers. Reported-by: David Sinquin <[email protected]> [[email protected]: use set_posix_acl] Fixes: 4ac7249e Cc: Christoph Hellwig <[email protected]> Cc: Al Viro <[email protected]> Cc: [email protected] Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-284
static __be32 nfsacld_proc_setacl(struct svc_rqst * rqstp, struct nfsd3_setaclargs *argp, struct nfsd_attrstat *resp) { struct inode *inode; svc_fh *fh; __be32 nfserr = 0; int error; dprintk("nfsd: SETACL(2acl) %s\n", SVCFH_fmt(&argp->fh)); fh = fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_SATTR); if (nfserr) goto out; inode = d_inode(fh->fh_dentry); error = fh_want_write(fh); if (error) goto out_errno; fh_lock(fh); error = set_posix_acl(inode, ACL_TYPE_ACCESS, argp->acl_access); if (error) goto out_drop_lock; error = set_posix_acl(inode, ACL_TYPE_DEFAULT, argp->acl_default); if (error) goto out_drop_lock; fh_unlock(fh); fh_drop_write(fh); nfserr = fh_getattr(fh, &resp->stat); out: /* argp->acl_{access,default} may have been allocated in nfssvc_decode_setaclargs. */ posix_acl_release(argp->acl_access); posix_acl_release(argp->acl_default); return nfserr; out_drop_lock: fh_unlock(fh); fh_drop_write(fh); out_errno: nfserr = nfserrno(error); goto out; }
167,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int nntp_add_group(char *line, void *data) { struct NntpServer *nserv = data; struct NntpData *nntp_data = NULL; char group[LONG_STRING]; char desc[HUGE_STRING] = ""; char mod; anum_t first, last; if (!nserv || !line) return 0; if (sscanf(line, "%s " ANUM " " ANUM " %c %[^\n]", group, &last, &first, &mod, desc) < 4) return 0; nntp_data = nntp_data_find(nserv, group); nntp_data->deleted = false; nntp_data->first_message = first; nntp_data->last_message = last; nntp_data->allowed = (mod == 'y') || (mod == 'm'); mutt_str_replace(&nntp_data->desc, desc); if (nntp_data->newsrc_ent || nntp_data->last_cached) nntp_group_unread_stat(nntp_data); else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message) nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1; else nntp_data->unread = 0; return 0; } Commit Message: Set length modifiers for group and desc nntp_add_group parses a line controlled by the connected nntp server. Restrict the maximum lengths read into the stack buffers group, and desc. CWE ID: CWE-119
int nntp_add_group(char *line, void *data) { struct NntpServer *nserv = data; struct NntpData *nntp_data = NULL; char group[LONG_STRING] = ""; char desc[HUGE_STRING] = ""; char mod; anum_t first, last; if (!nserv || !line) return 0; /* These sscanf limits must match the sizes of the group and desc arrays */ if (sscanf(line, "%1023s " ANUM " " ANUM " %c %8191[^\n]", group, &last, &first, &mod, desc) < 4) { mutt_debug(4, "Cannot parse server line: %s\n", line); return 0; } nntp_data = nntp_data_find(nserv, group); nntp_data->deleted = false; nntp_data->first_message = first; nntp_data->last_message = last; nntp_data->allowed = (mod == 'y') || (mod == 'm'); mutt_str_replace(&nntp_data->desc, desc); if (nntp_data->newsrc_ent || nntp_data->last_cached) nntp_group_unread_stat(nntp_data); else if (nntp_data->last_message && nntp_data->first_message <= nntp_data->last_message) nntp_data->unread = nntp_data->last_message - nntp_data->first_message + 1; else nntp_data->unread = 0; return 0; }
169,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: socket_t *socket_accept(const socket_t *socket) { assert(socket != NULL); int fd = accept(socket->fd, NULL, NULL); if (fd == INVALID_FD) { LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno)); return NULL; } socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t)); if (!ret) { close(fd); LOG_ERROR("%s unable to allocate memory for socket.", __func__); return NULL; } ret->fd = fd; return ret; } 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
socket_t *socket_accept(const socket_t *socket) { assert(socket != NULL); int fd = TEMP_FAILURE_RETRY(accept(socket->fd, NULL, NULL)); if (fd == INVALID_FD) { LOG_ERROR("%s unable to accept socket: %s", __func__, strerror(errno)); return NULL; } socket_t *ret = (socket_t *)osi_calloc(sizeof(socket_t)); if (!ret) { close(fd); LOG_ERROR("%s unable to allocate memory for socket.", __func__); return NULL; } ret->fd = fd; return ret; }
173,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; }
173,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EmulationHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { if (host_ == frame_host) return; host_ = frame_host; if (touch_emulation_enabled_) UpdateTouchEventEmulationState(); UpdateDeviceEmulationState(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void EmulationHandler::SetRenderer(RenderProcessHost* process_host, void EmulationHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { if (host_ == frame_host) return; host_ = frame_host; if (touch_emulation_enabled_) UpdateTouchEventEmulationState(); UpdateDeviceEmulationState(); }
172,746
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic, unsigned long addr, unsigned long length) { unsigned long result = 0; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16) | (IOAPIC_VERSION_ID & 0xff)); break; case IOAPIC_REG_APIC_ID: case IOAPIC_REG_ARB_ID: result = ((ioapic->id & 0xf) << 24); break; default: { u32 redir_index = (ioapic->ioregsel - 0x10) >> 1; u64 redir_content; ASSERT(redir_index < IOAPIC_NUM_PINS); redir_content = ioapic->redirtbl[redir_index].bits; result = (ioapic->ioregsel & 0x1) ? (redir_content >> 32) & 0xffffffff : redir_content & 0xffffffff; break; } } return result; } Commit Message: KVM: Fix bounds checking in ioapic indirect register reads (CVE-2013-1798) If the guest specifies a IOAPIC_REG_SELECT with an invalid value and follows that with a read of the IOAPIC_REG_WINDOW KVM does not properly validate that request. ioapic_read_indirect contains an ASSERT(redir_index < IOAPIC_NUM_PINS), but the ASSERT has no effect in non-debug builds. In recent kernels this allows a guest to cause a kernel oops by reading invalid memory. In older kernels (pre-3.3) this allows a guest to read from large ranges of host memory. Tested: tested against apic unit tests. Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-20
static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic, unsigned long addr, unsigned long length) { unsigned long result = 0; switch (ioapic->ioregsel) { case IOAPIC_REG_VERSION: result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16) | (IOAPIC_VERSION_ID & 0xff)); break; case IOAPIC_REG_APIC_ID: case IOAPIC_REG_ARB_ID: result = ((ioapic->id & 0xf) << 24); break; default: { u32 redir_index = (ioapic->ioregsel - 0x10) >> 1; u64 redir_content; if (redir_index < IOAPIC_NUM_PINS) redir_content = ioapic->redirtbl[redir_index].bits; else redir_content = ~0ULL; result = (ioapic->ioregsel & 0x1) ? (redir_content >> 32) & 0xffffffff : redir_content & 0xffffffff; break; } } return result; }
166,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; ret = gss_unwrap_aead(minor_status, context_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_unwrap_aead(OM_uint32 *minor_status, gss_ctx_id_t context_handle, gss_buffer_t input_message_buffer, gss_buffer_t input_assoc_buffer, gss_buffer_t output_payload_buffer, int *conf_state, gss_qop_t *qop_state) { OM_uint32 ret; spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle; if (sc->ctx_handle == GSS_C_NO_CONTEXT) return (GSS_S_NO_CONTEXT); ret = gss_unwrap_aead(minor_status, sc->ctx_handle, input_message_buffer, input_assoc_buffer, output_payload_buffer, conf_state, qop_state); return (ret); }
166,667
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebLocalFrameImpl::SetCommittedFirstRealLoad() { DCHECK(GetFrame()); GetFrame()->Loader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedMultipleRealLoads); GetFrame()->DidSendResourceTimingInfoToParent(); } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
void WebLocalFrameImpl::SetCommittedFirstRealLoad() { DCHECK(GetFrame()); GetFrame()->Loader().StateMachine()->AdvanceTo( FrameLoaderStateMachine::kCommittedMultipleRealLoads); GetFrame()->SetShouldSendResourceTimingInfoToParent(false); }
172,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void server_process_native_message( Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) { struct iovec *iovec = NULL; unsigned n = 0, m = 0, j, tn = (unsigned) -1; const char *p; size_t remaining; int priority = LOG_INFO; char *identifier = NULL, *message = NULL; assert(s); assert(buffer || buffer_size == 0); p = buffer; remaining = buffer_size; while (remaining > 0) { const char *e, *q; e = memchr(p, '\n', remaining); if (!e) { /* Trailing noise, let's ignore it, and flush what we collected */ log_debug("Received message with trailing noise, ignoring."); break; } if (e == p) { /* Entry separator */ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); n = 0; priority = LOG_INFO; p++; remaining--; continue; } if (*p == '.' || *p == '#') { /* Ignore control commands for now, and * comments too. */ remaining -= (e - p) + 1; p = e + 1; continue; } /* A property follows */ if (n+N_IOVEC_META_FIELDS >= m) { struct iovec *c; unsigned u; u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U); c = realloc(iovec, u * sizeof(struct iovec)); if (!c) { log_oom(); break; } iovec = c; m = u; } q = memchr(p, '=', e - p); if (q) { if (valid_user_field(p, q - p)) { size_t l; l = e - p; /* If the field name starts with an * underscore, skip the variable, * since that indidates a trusted * field */ iovec[n].iov_base = (char*) p; iovec[n].iov_len = l; n++; /* We need to determine the priority * of this entry for the rate limiting * logic */ if (l == 10 && memcmp(p, "PRIORITY=", 9) == 0 && p[9] >= '0' && p[9] <= '9') priority = (priority & LOG_FACMASK) | (p[9] - '0'); else if (l == 17 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9') priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3); else if (l == 18 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9' && p[17] >= '0' && p[17] <= '9') priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3); else if (l >= 19 && memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) { char *t; t = strndup(p + 18, l - 18); if (t) { free(identifier); identifier = t; } } else if (l >= 8 && memcmp(p, "MESSAGE=", 8) == 0) { char *t; t = strndup(p + 8, l - 8); if (t) { free(message); message = t; } } } remaining -= (e - p) + 1; p = e + 1; continue; } else { le64_t l_le; uint64_t l; char *k; if (remaining < e - p + 1 + sizeof(uint64_t) + 1) { log_debug("Failed to parse message, ignoring."); break; } memcpy(&l_le, e + 1, sizeof(uint64_t)); memcpy(&l_le, e + 1, sizeof(uint64_t)); l = le64toh(l_le); if (remaining < e - p + 1 + sizeof(uint64_t) + l + 1 || e[1+sizeof(uint64_t)+l] != '\n') { log_debug("Failed to parse message, ignoring."); break; } memcpy(k, p, e - p); k[e - p] = '='; memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l); if (valid_user_field(p, e - p)) { iovec[n].iov_base = k; iovec[n].iov_len = (e - p) + 1 + l; n++; } else free(k); remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1; p = e + 1 + sizeof(uint64_t) + l + 1; } } if (n <= 0) goto finish; tn = n++; IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal"); if (message) { if (s->forward_to_syslog) server_forward_syslog(s, priority, identifier, message, ucred, tv); if (s->forward_to_kmsg) server_forward_kmsg(s, priority, identifier, message, ucred); if (s->forward_to_console) server_forward_console(s, priority, identifier, message, ucred); } server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); finish: for (j = 0; j < n; j++) { if (j == tn) continue; if (iovec[j].iov_base < buffer || (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size) free(iovec[j].iov_base); } free(iovec); free(identifier); free(message); } Commit Message: CWE ID: CWE-189
void server_process_native_message( Server *s, const void *buffer, size_t buffer_size, struct ucred *ucred, struct timeval *tv, const char *label, size_t label_len) { struct iovec *iovec = NULL; unsigned n = 0, m = 0, j, tn = (unsigned) -1; const char *p; size_t remaining; int priority = LOG_INFO; char *identifier = NULL, *message = NULL; assert(s); assert(buffer || buffer_size == 0); p = buffer; remaining = buffer_size; while (remaining > 0) { const char *e, *q; e = memchr(p, '\n', remaining); if (!e) { /* Trailing noise, let's ignore it, and flush what we collected */ log_debug("Received message with trailing noise, ignoring."); break; } if (e == p) { /* Entry separator */ server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); n = 0; priority = LOG_INFO; p++; remaining--; continue; } if (*p == '.' || *p == '#') { /* Ignore control commands for now, and * comments too. */ remaining -= (e - p) + 1; p = e + 1; continue; } /* A property follows */ if (n+N_IOVEC_META_FIELDS >= m) { struct iovec *c; unsigned u; u = MAX((n+N_IOVEC_META_FIELDS+1) * 2U, 4U); c = realloc(iovec, u * sizeof(struct iovec)); if (!c) { log_oom(); break; } iovec = c; m = u; } q = memchr(p, '=', e - p); if (q) { if (valid_user_field(p, q - p)) { size_t l; l = e - p; /* If the field name starts with an * underscore, skip the variable, * since that indidates a trusted * field */ iovec[n].iov_base = (char*) p; iovec[n].iov_len = l; n++; /* We need to determine the priority * of this entry for the rate limiting * logic */ if (l == 10 && memcmp(p, "PRIORITY=", 9) == 0 && p[9] >= '0' && p[9] <= '9') priority = (priority & LOG_FACMASK) | (p[9] - '0'); else if (l == 17 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9') priority = (priority & LOG_PRIMASK) | ((p[16] - '0') << 3); else if (l == 18 && memcmp(p, "SYSLOG_FACILITY=", 16) == 0 && p[16] >= '0' && p[16] <= '9' && p[17] >= '0' && p[17] <= '9') priority = (priority & LOG_PRIMASK) | (((p[16] - '0')*10 + (p[17] - '0')) << 3); else if (l >= 19 && memcmp(p, "SYSLOG_IDENTIFIER=", 18) == 0) { char *t; t = strndup(p + 18, l - 18); if (t) { free(identifier); identifier = t; } } else if (l >= 8 && memcmp(p, "MESSAGE=", 8) == 0) { char *t; t = strndup(p + 8, l - 8); if (t) { free(message); message = t; } } } remaining -= (e - p) + 1; p = e + 1; continue; } else { le64_t l_le; uint64_t l; char *k; if (remaining < e - p + 1 + sizeof(uint64_t) + 1) { log_debug("Failed to parse message, ignoring."); break; } memcpy(&l_le, e + 1, sizeof(uint64_t)); memcpy(&l_le, e + 1, sizeof(uint64_t)); l = le64toh(l_le); if (l > DATA_SIZE_MAX) { log_debug("Received binary data block too large, ignoring."); break; } if ((uint64_t) remaining < e - p + 1 + sizeof(uint64_t) + l + 1 || e[1+sizeof(uint64_t)+l] != '\n') { log_debug("Failed to parse message, ignoring."); break; } memcpy(k, p, e - p); k[e - p] = '='; memcpy(k + (e - p) + 1, e + 1 + sizeof(uint64_t), l); if (valid_user_field(p, e - p)) { iovec[n].iov_base = k; iovec[n].iov_len = (e - p) + 1 + l; n++; } else free(k); remaining -= (e - p) + 1 + sizeof(uint64_t) + l + 1; p = e + 1 + sizeof(uint64_t) + l + 1; } } if (n <= 0) goto finish; tn = n++; IOVEC_SET_STRING(iovec[tn], "_TRANSPORT=journal"); if (message) { if (s->forward_to_syslog) server_forward_syslog(s, priority, identifier, message, ucred, tv); if (s->forward_to_kmsg) server_forward_kmsg(s, priority, identifier, message, ucred); if (s->forward_to_console) server_forward_console(s, priority, identifier, message, ucred); } server_dispatch_message(s, iovec, n, m, ucred, tv, label, label_len, NULL, priority); finish: for (j = 0; j < n; j++) { if (j == tn) continue; if (iovec[j].iov_base < buffer || (const uint8_t*) iovec[j].iov_base >= (const uint8_t*) buffer + buffer_size) free(iovec[j].iov_base); } free(iovec); free(identifier); free(message); }
164,658
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_host_hdr(hp); if (retval != 0) { WSP(sp, SLT_Error, "Duplicated Host header"); return (retval); } return (retval); } Commit Message: Check for duplicate Content-Length headers in requests If a duplicate CL header is in the request, we fail the request with a 400 (Bad Request) Fix a test case that was sending duplicate CL by misstake and would not fail because of that. CWE ID:
http_DissectRequest(struct sess *sp) { struct http_conn *htc; struct http *hp; uint16_t retval; CHECK_OBJ_NOTNULL(sp, SESS_MAGIC); htc = sp->htc; CHECK_OBJ_NOTNULL(htc, HTTP_CONN_MAGIC); hp = sp->http; CHECK_OBJ_NOTNULL(hp, HTTP_MAGIC); hp->logtag = HTTP_Rx; retval = http_splitline(sp->wrk, sp->fd, hp, htc, HTTP_HDR_REQ, HTTP_HDR_URL, HTTP_HDR_PROTO); if (retval != 0) { WSPR(sp, SLT_HttpGarbage, htc->rxbuf); return (retval); } http_ProtoVer(hp); retval = htc_request_check_hdrs(sp, hp); return (retval); }
167,479
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; } Commit Message: CVE-2017-13042/HNCP: add DHCPv6-Data bounds checks hncp_print_rec() validates each HNCP TLV to be within the declared as well as the on-the-wire packet space. However, dhcpv6_print() in the same file didn't do the same for the DHCPv6 options within the HNCP DHCPv6-Data TLV value, which could cause an out-of-bounds read when decoding an invalid packet. Add missing checks to dhcpv6_print(). 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
dhcpv6_print(netdissect_options *ndo, const u_char *cp, u_int length, int indent) { u_int i, t; const u_char *tlv, *value; uint16_t type, optlen; i = 0; while (i < length) { if (i + 4 > length) return -1; tlv = cp + i; type = EXTRACT_16BITS(tlv); optlen = EXTRACT_16BITS(tlv + 2); value = tlv + 4; ND_PRINT((ndo, "\n")); for (t = indent; t > 0; t--) ND_PRINT((ndo, "\t")); ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type))); ND_PRINT((ndo," (%u)", optlen + 4 )); if (i + 4 + optlen > length) return -1; switch (type) { case DH6OPT_DNS_SERVERS: case DH6OPT_SNTP_SERVERS: { if (optlen % 16 != 0) { ND_PRINT((ndo, " %s", istr)); return -1; } for (t = 0; t < optlen; t += 16) ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t))); } break; case DH6OPT_DOMAIN_LIST: { const u_char *tp = value; while (tp < value + optlen) { ND_PRINT((ndo, " ")); if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL) return -1; } } break; } i += 4 + optlen; } return 0; }
167,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static js_Ast *memberexp(js_State *J) { js_Ast *a; INCREC(); a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } DECREC(); return a; } Commit Message: CWE ID: CWE-674
static js_Ast *memberexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } POPREC(); return a; }
165,136
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheDispatcherHost::OnChannelConnected(int32 peer_pid) { if (appcache_service_.get()) { backend_impl_.Initialize( appcache_service_.get(), &frontend_proxy_, process_id_); get_status_callback_ = base::Bind(&AppCacheDispatcherHost::GetStatusCallback, base::Unretained(this)); start_update_callback_ = base::Bind(&AppCacheDispatcherHost::StartUpdateCallback, base::Unretained(this)); swap_cache_callback_ = base::Bind(&AppCacheDispatcherHost::SwapCacheCallback, base::Unretained(this)); } } Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug. BUG=554908 Review URL: https://codereview.chromium.org/1441683004 Cr-Commit-Position: refs/heads/master@{#359930} CWE ID:
void AppCacheDispatcherHost::OnChannelConnected(int32 peer_pid) { if (appcache_service_.get()) { backend_impl_.Initialize( appcache_service_.get(), &frontend_proxy_, process_id_); get_status_callback_ = base::Bind(&AppCacheDispatcherHost::GetStatusCallback, weak_factory_.GetWeakPtr()); start_update_callback_ = base::Bind(&AppCacheDispatcherHost::StartUpdateCallback, weak_factory_.GetWeakPtr()); swap_cache_callback_ = base::Bind(&AppCacheDispatcherHost::SwapCacheCallback, weak_factory_.GetWeakPtr()); } }
171,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: print_bacp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; 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(bacconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case BACPOPT_FPEER: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK2(*(p + 2), 4); ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(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, "[|bacp]")); 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_bacp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; 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(bacconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(bacconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case BACPOPT_FPEER: if (len != 6) { ND_PRINT((ndo, " (length bogus, should be = 6)")); return len; } ND_TCHECK_32BITS(p + 2); ND_PRINT((ndo, ": Magic-Num 0x%08x", EXTRACT_32BITS(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, "[|bacp]")); return 0; }
167,859
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { 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()); }
171,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *inpic) { KerndeintContext *kerndeint = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *outpic; const uint8_t *prvp; ///< Previous field's pixel line number n const uint8_t *prvpp; ///< Previous field's pixel line number (n - 1) const uint8_t *prvpn; ///< Previous field's pixel line number (n + 1) const uint8_t *prvppp; ///< Previous field's pixel line number (n - 2) const uint8_t *prvpnn; ///< Previous field's pixel line number (n + 2) const uint8_t *prvp4p; ///< Previous field's pixel line number (n - 4) const uint8_t *prvp4n; ///< Previous field's pixel line number (n + 4) const uint8_t *srcp; ///< Current field's pixel line number n const uint8_t *srcpp; ///< Current field's pixel line number (n - 1) const uint8_t *srcpn; ///< Current field's pixel line number (n + 1) const uint8_t *srcppp; ///< Current field's pixel line number (n - 2) const uint8_t *srcpnn; ///< Current field's pixel line number (n + 2) const uint8_t *srcp3p; ///< Current field's pixel line number (n - 3) const uint8_t *srcp3n; ///< Current field's pixel line number (n + 3) const uint8_t *srcp4p; ///< Current field's pixel line number (n - 4) const uint8_t *srcp4n; ///< Current field's pixel line number (n + 4) uint8_t *dstp, *dstp_saved; const uint8_t *srcp_saved; int src_linesize, psrc_linesize, dst_linesize, bwidth; int x, y, plane, val, hi, lo, g, h, n = kerndeint->frame++; double valf; const int thresh = kerndeint->thresh; const int order = kerndeint->order; const int map = kerndeint->map; const int sharp = kerndeint->sharp; const int twoway = kerndeint->twoway; const int is_packed_rgb = kerndeint->is_packed_rgb; outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!outpic) { av_frame_free(&inpic); return AVERROR(ENOMEM); } av_frame_copy_props(outpic, inpic); outpic->interlaced_frame = 0; for (plane = 0; inpic->data[plane] && plane < 4; plane++) { h = plane == 0 ? inlink->h : FF_CEIL_RSHIFT(inlink->h, kerndeint->vsub); bwidth = kerndeint->tmp_bwidth[plane]; srcp = srcp_saved = inpic->data[plane]; src_linesize = inpic->linesize[plane]; psrc_linesize = kerndeint->tmp_linesize[plane]; dstp = dstp_saved = outpic->data[plane]; dst_linesize = outpic->linesize[plane]; srcp = srcp_saved + (1 - order) * src_linesize; dstp = dstp_saved + (1 - order) * dst_linesize; for (y = 0; y < h; y += 2) { memcpy(dstp, srcp, bwidth); srcp += 2 * src_linesize; dstp += 2 * dst_linesize; } memcpy(dstp_saved + order * dst_linesize, srcp_saved + (1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (2 + order ) * dst_linesize, srcp_saved + (3 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 2 + order) * dst_linesize, srcp_saved + (h - 1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 4 + order) * dst_linesize, srcp_saved + (h - 3 - order) * src_linesize, bwidth); /* For the other field choose adaptively between using the previous field or the interpolant from the current field. */ prvp = kerndeint->tmp_data[plane] + 5 * psrc_linesize - (1 - order) * psrc_linesize; prvpp = prvp - psrc_linesize; prvppp = prvp - 2 * psrc_linesize; prvp4p = prvp - 4 * psrc_linesize; prvpn = prvp + psrc_linesize; prvpnn = prvp + 2 * psrc_linesize; prvp4n = prvp + 4 * psrc_linesize; srcp = srcp_saved + 5 * src_linesize - (1 - order) * src_linesize; srcpp = srcp - src_linesize; srcppp = srcp - 2 * src_linesize; srcp3p = srcp - 3 * src_linesize; srcp4p = srcp - 4 * src_linesize; srcpn = srcp + src_linesize; srcpnn = srcp + 2 * src_linesize; srcp3n = srcp + 3 * src_linesize; srcp4n = srcp + 4 * src_linesize; dstp = dstp_saved + 5 * dst_linesize - (1 - order) * dst_linesize; for (y = 5 - (1 - order); y <= h - 5 - (1 - order); y += 2) { for (x = 0; x < bwidth; x++) { if (thresh == 0 || n == 0 || (abs((int)prvp[x] - (int)srcp[x]) > thresh) || (abs((int)prvpp[x] - (int)srcpp[x]) > thresh) || (abs((int)prvpn[x] - (int)srcpn[x]) > thresh)) { if (map) { g = x & ~3; if (is_packed_rgb) { AV_WB32(dstp + g, 0xffffffff); x = g + 3; } else if (inlink->format == AV_PIX_FMT_YUYV422) { AV_WB32(dstp + g, 0xeb80eb80); x = g + 3; } else { dstp[x] = plane == 0 ? 235 : 128; } } else { if (is_packed_rgb) { hi = 255; lo = 0; } else if (inlink->format == AV_PIX_FMT_YUYV422) { hi = x & 1 ? 240 : 235; lo = 16; } else { hi = plane == 0 ? 235 : 240; lo = 16; } if (sharp) { if (twoway) { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)srcp[x] + (int)prvp[x]) - 0.116 * ((int)srcppp[x] + (int)srcpnn[x] + (int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)srcp4p[x] + (int)srcp4n[x] + (int)prvp4p[x] + (int)prvp4n[x]); } else { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)prvp[x]) - 0.116 * ((int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)prvp4p[x] + (int)prvp4p[x]); } dstp[x] = av_clip(valf, lo, hi); } else { if (twoway) { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)srcp[x] + (int)prvp[x]) - (int)(srcppp[x]) - (int)(srcpnn[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } else { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)prvp[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } dstp[x] = av_clip(val, lo, hi); } } } else { dstp[x] = srcp[x]; } } prvp += 2 * psrc_linesize; prvpp += 2 * psrc_linesize; prvppp += 2 * psrc_linesize; prvpn += 2 * psrc_linesize; prvpnn += 2 * psrc_linesize; prvp4p += 2 * psrc_linesize; prvp4n += 2 * psrc_linesize; srcp += 2 * src_linesize; srcpp += 2 * src_linesize; srcppp += 2 * src_linesize; srcp3p += 2 * src_linesize; srcp4p += 2 * src_linesize; srcpn += 2 * src_linesize; srcpnn += 2 * src_linesize; srcp3n += 2 * src_linesize; srcp4n += 2 * src_linesize; dstp += 2 * dst_linesize; } srcp = inpic->data[plane]; dstp = kerndeint->tmp_data[plane]; av_image_copy_plane(dstp, psrc_linesize, srcp, src_linesize, bwidth, h); } av_frame_free(&inpic); return ff_filter_frame(outlink, outpic); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *inpic) { KerndeintContext *kerndeint = inlink->dst->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *outpic; const uint8_t *prvp; ///< Previous field's pixel line number n const uint8_t *prvpp; ///< Previous field's pixel line number (n - 1) const uint8_t *prvpn; ///< Previous field's pixel line number (n + 1) const uint8_t *prvppp; ///< Previous field's pixel line number (n - 2) const uint8_t *prvpnn; ///< Previous field's pixel line number (n + 2) const uint8_t *prvp4p; ///< Previous field's pixel line number (n - 4) const uint8_t *prvp4n; ///< Previous field's pixel line number (n + 4) const uint8_t *srcp; ///< Current field's pixel line number n const uint8_t *srcpp; ///< Current field's pixel line number (n - 1) const uint8_t *srcpn; ///< Current field's pixel line number (n + 1) const uint8_t *srcppp; ///< Current field's pixel line number (n - 2) const uint8_t *srcpnn; ///< Current field's pixel line number (n + 2) const uint8_t *srcp3p; ///< Current field's pixel line number (n - 3) const uint8_t *srcp3n; ///< Current field's pixel line number (n + 3) const uint8_t *srcp4p; ///< Current field's pixel line number (n - 4) const uint8_t *srcp4n; ///< Current field's pixel line number (n + 4) uint8_t *dstp, *dstp_saved; const uint8_t *srcp_saved; int src_linesize, psrc_linesize, dst_linesize, bwidth; int x, y, plane, val, hi, lo, g, h, n = kerndeint->frame++; double valf; const int thresh = kerndeint->thresh; const int order = kerndeint->order; const int map = kerndeint->map; const int sharp = kerndeint->sharp; const int twoway = kerndeint->twoway; const int is_packed_rgb = kerndeint->is_packed_rgb; outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!outpic) { av_frame_free(&inpic); return AVERROR(ENOMEM); } av_frame_copy_props(outpic, inpic); outpic->interlaced_frame = 0; for (plane = 0; plane < 4 && inpic->data[plane] && inpic->linesize[plane]; plane++) { h = plane == 0 ? inlink->h : FF_CEIL_RSHIFT(inlink->h, kerndeint->vsub); bwidth = kerndeint->tmp_bwidth[plane]; srcp = srcp_saved = inpic->data[plane]; src_linesize = inpic->linesize[plane]; psrc_linesize = kerndeint->tmp_linesize[plane]; dstp = dstp_saved = outpic->data[plane]; dst_linesize = outpic->linesize[plane]; srcp = srcp_saved + (1 - order) * src_linesize; dstp = dstp_saved + (1 - order) * dst_linesize; for (y = 0; y < h; y += 2) { memcpy(dstp, srcp, bwidth); srcp += 2 * src_linesize; dstp += 2 * dst_linesize; } memcpy(dstp_saved + order * dst_linesize, srcp_saved + (1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (2 + order ) * dst_linesize, srcp_saved + (3 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 2 + order) * dst_linesize, srcp_saved + (h - 1 - order) * src_linesize, bwidth); memcpy(dstp_saved + (h - 4 + order) * dst_linesize, srcp_saved + (h - 3 - order) * src_linesize, bwidth); /* For the other field choose adaptively between using the previous field or the interpolant from the current field. */ prvp = kerndeint->tmp_data[plane] + 5 * psrc_linesize - (1 - order) * psrc_linesize; prvpp = prvp - psrc_linesize; prvppp = prvp - 2 * psrc_linesize; prvp4p = prvp - 4 * psrc_linesize; prvpn = prvp + psrc_linesize; prvpnn = prvp + 2 * psrc_linesize; prvp4n = prvp + 4 * psrc_linesize; srcp = srcp_saved + 5 * src_linesize - (1 - order) * src_linesize; srcpp = srcp - src_linesize; srcppp = srcp - 2 * src_linesize; srcp3p = srcp - 3 * src_linesize; srcp4p = srcp - 4 * src_linesize; srcpn = srcp + src_linesize; srcpnn = srcp + 2 * src_linesize; srcp3n = srcp + 3 * src_linesize; srcp4n = srcp + 4 * src_linesize; dstp = dstp_saved + 5 * dst_linesize - (1 - order) * dst_linesize; for (y = 5 - (1 - order); y <= h - 5 - (1 - order); y += 2) { for (x = 0; x < bwidth; x++) { if (thresh == 0 || n == 0 || (abs((int)prvp[x] - (int)srcp[x]) > thresh) || (abs((int)prvpp[x] - (int)srcpp[x]) > thresh) || (abs((int)prvpn[x] - (int)srcpn[x]) > thresh)) { if (map) { g = x & ~3; if (is_packed_rgb) { AV_WB32(dstp + g, 0xffffffff); x = g + 3; } else if (inlink->format == AV_PIX_FMT_YUYV422) { AV_WB32(dstp + g, 0xeb80eb80); x = g + 3; } else { dstp[x] = plane == 0 ? 235 : 128; } } else { if (is_packed_rgb) { hi = 255; lo = 0; } else if (inlink->format == AV_PIX_FMT_YUYV422) { hi = x & 1 ? 240 : 235; lo = 16; } else { hi = plane == 0 ? 235 : 240; lo = 16; } if (sharp) { if (twoway) { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)srcp[x] + (int)prvp[x]) - 0.116 * ((int)srcppp[x] + (int)srcpnn[x] + (int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)srcp4p[x] + (int)srcp4n[x] + (int)prvp4p[x] + (int)prvp4n[x]); } else { valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x]) + 0.170 * ((int)prvp[x]) - 0.116 * ((int)prvppp[x] + (int)prvpnn[x]) - 0.026 * ((int)srcp3p[x] + (int)srcp3n[x]) + 0.031 * ((int)prvp4p[x] + (int)prvp4p[x]); } dstp[x] = av_clip(valf, lo, hi); } else { if (twoway) { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)srcp[x] + (int)prvp[x]) - (int)(srcppp[x]) - (int)(srcpnn[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } else { val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)prvp[x]) - (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4; } dstp[x] = av_clip(val, lo, hi); } } } else { dstp[x] = srcp[x]; } } prvp += 2 * psrc_linesize; prvpp += 2 * psrc_linesize; prvppp += 2 * psrc_linesize; prvpn += 2 * psrc_linesize; prvpnn += 2 * psrc_linesize; prvp4p += 2 * psrc_linesize; prvp4n += 2 * psrc_linesize; srcp += 2 * src_linesize; srcpp += 2 * src_linesize; srcppp += 2 * src_linesize; srcp3p += 2 * src_linesize; srcp4p += 2 * src_linesize; srcpn += 2 * src_linesize; srcpnn += 2 * src_linesize; srcp3n += 2 * src_linesize; srcp4n += 2 * src_linesize; dstp += 2 * dst_linesize; } srcp = inpic->data[plane]; dstp = kerndeint->tmp_data[plane]; av_image_copy_plane(dstp, psrc_linesize, srcp, src_linesize, bwidth, h); } av_frame_free(&inpic); return ff_filter_frame(outlink, outpic); }
166,003
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[1024]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { sprintf (pathName, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; } Commit Message: CWE ID: CWE-119
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; }
164,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; } Commit Message: CWE ID: CWE-264
x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Is this being called after the refusal deadline? */ if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { verbose("Rejected X11 connection after ForwardX11Timeout " "expired"); return -1; } /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; }
164,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) continue; if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } } Commit Message: Fix #8813 - segfault in dwarf parser CWE ID: CWE-125
static void r_bin_dwarf_dump_debug_info(FILE *f, const RBinDwarfDebugInfo *inf) { size_t i, j, k; RBinDwarfDIE *dies; RBinDwarfAttrValue *values; if (!inf || !f) { return; } for (i = 0; i < inf->length; i++) { fprintf (f, " Compilation Unit @ offset 0x%"PFMT64x":\n", inf->comp_units [i].offset); fprintf (f, " Length: 0x%x\n", inf->comp_units [i].hdr.length); fprintf (f, " Version: %d\n", inf->comp_units [i].hdr.version); fprintf (f, " Abbrev Offset: 0x%x\n", inf->comp_units [i].hdr.abbrev_offset); fprintf (f, " Pointer Size: %d\n", inf->comp_units [i].hdr.pointer_size); dies = inf->comp_units[i].dies; for (j = 0; j < inf->comp_units[i].length; j++) { fprintf (f, " Abbrev Number: %"PFMT64u" ", dies[j].abbrev_code); if (dies[j].tag && dies[j].tag <= DW_TAG_volatile_type && dwarf_tag_name_encodings[dies[j].tag]) { fprintf (f, "(%s)\n", dwarf_tag_name_encodings[dies[j].tag]); } else { fprintf (f, "(Unknown abbrev tag)\n"); } if (!dies[j].abbrev_code) { continue; } values = dies[j].attr_values; for (k = 0; k < dies[j].length; k++) { if (!values[k].name) { continue; } if (values[k].name < DW_AT_vtable_elem_location && dwarf_attr_encodings[values[k].name]) { fprintf (f, " %-18s : ", dwarf_attr_encodings[values[k].name]); } else { fprintf (f, " TODO\t"); } r_bin_dwarf_dump_attr_value (&values[k], f); fprintf (f, "\n"); } } } }
167,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock * tcp_v6_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet6_request_sock *treq; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; struct ipv6_txoptions *opt; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst); if (newsk == NULL) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr); ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr); ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr); inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } treq = inet6_rsk(req); opt = np->opt; if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, req); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; __ip6_dst_store(newsk, dst, NULL, NULL); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_copy(&newnp->daddr, &treq->rmt_addr); ipv6_addr_copy(&newnp->saddr, &treq->loc_addr); ipv6_addr_copy(&newnp->rcv_saddr, &treq->loc_addr); newsk->sk_bound_dev_if = treq->iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->opt = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; /* Clone pktoptions received with SYN */ newnp->pktoptions = NULL; if (treq->pktopts != NULL) { newnp->pktoptions = skb_clone(treq->pktopts, GFP_ATOMIC); kfree_skb(treq->pktopts); treq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ if (opt) { newnp->opt = ipv6_dup_options(newsk, opt); if (opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ if ((key = tcp_v6_md5_do_lookup(sk, &newnp->daddr)) != NULL) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v6_md5_do_add(newsk, &newnp->daddr, newkey, key->keylen); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto out; } __inet6_hash(newsk, NULL); return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: if (opt && opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
static struct sock * tcp_v6_syn_recv_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet6_request_sock *treq; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct tcp6_sock *newtcp6sk; struct inet_sock *newinet; struct tcp_sock *newtp; struct sock *newsk; struct ipv6_txoptions *opt; #ifdef CONFIG_TCP_MD5SIG struct tcp_md5sig_key *key; #endif if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = tcp_v4_syn_recv_sock(sk, skb, req, dst); if (newsk == NULL) return NULL; newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newinet = inet_sk(newsk); newnp = inet6_sk(newsk); newtp = tcp_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr); ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr); ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr); inet_csk(newsk)->icsk_af_ops = &ipv6_mapped; newsk->sk_backlog_rcv = tcp_v4_do_rcv; #ifdef CONFIG_TCP_MD5SIG newtp->af_specific = &tcp_sock_ipv6_mapped_specific; #endif newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, tcp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ tcp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } treq = inet6_rsk(req); opt = np->opt; if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { dst = inet6_csk_route_req(sk, req); if (!dst) goto out; } newsk = tcp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, tcp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ newsk->sk_gso_type = SKB_GSO_TCPV6; __ip6_dst_store(newsk, dst, NULL, NULL); newtcp6sk = (struct tcp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newtcp6sk->inet6; newtp = tcp_sk(newsk); newinet = inet_sk(newsk); newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); ipv6_addr_copy(&newnp->daddr, &treq->rmt_addr); ipv6_addr_copy(&newnp->saddr, &treq->loc_addr); ipv6_addr_copy(&newnp->rcv_saddr, &treq->loc_addr); newsk->sk_bound_dev_if = treq->iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; newnp->ipv6_fl_list = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; /* Clone pktoptions received with SYN */ newnp->pktoptions = NULL; if (treq->pktopts != NULL) { newnp->pktoptions = skb_clone(treq->pktopts, GFP_ATOMIC); kfree_skb(treq->pktopts); treq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* Clone native IPv6 options from listening socket (if any) Yes, keeping reference count would be much more clever, but we make one more one thing there: reattach optmem to newsk. */ if (opt) { newnp->opt = ipv6_dup_options(newsk, opt); if (opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (newnp->opt) inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen + newnp->opt->opt_flen); tcp_mtup_init(newsk); tcp_sync_mss(newsk, dst_mtu(dst)); newtp->advmss = dst_metric_advmss(dst); tcp_initialize_rcv_mss(newsk); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; #ifdef CONFIG_TCP_MD5SIG /* Copy over the MD5 key from the original socket */ if ((key = tcp_v6_md5_do_lookup(sk, &newnp->daddr)) != NULL) { /* We're using one, so create a matching key * on the newsk structure. If we fail to get * memory, then we end up not copying the key * across. Shucks. */ char *newkey = kmemdup(key->key, key->keylen, GFP_ATOMIC); if (newkey != NULL) tcp_v6_md5_do_add(newsk, &newnp->daddr, newkey, key->keylen); } #endif if (__inet_inherit_port(sk, newsk) < 0) { sock_put(newsk); goto out; } __inet6_hash(newsk, NULL); return newsk; out_overflow: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: if (opt && opt != np->opt) sock_kfree_s(sk, opt, opt->tot_len); dst_release(dst); out: NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }
165,574
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int 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; }
170,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SkippedMBMotionComp( VideoDecData *video ) { Vop *prev = video->prevVop; Vop *comp; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int width, width_uv; int32 offset; #ifdef PV_POSTPROC_ON // 2/14/2001 int imv; int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; uint8 *pp_prev1; int mvwidth = video->nMBPerRow << 1; #endif width = video->width; width_uv = width >> 1; ypos = video->mbnum_row << 4 ; xpos = video->mbnum_col << 4 ; offset = (int32)ypos * width + xpos; /* zero motion compensation for previous frame */ /*mby*width + mbx;*/ c_prev = prev->yChan + offset; /*by*width_uv + bx;*/ cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2); /*by*width_uv + bx;*/ cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2); comp = video->currVop; c_comp = comp->yChan + offset; cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2); cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2); /* Copy previous reconstructed frame into the current frame */ PutSKIPPED_MB(c_comp, c_prev, width); PutSKIPPED_B(cu_comp, cu_prev, width_uv); PutSKIPPED_B(cv_comp, cv_prev, width_uv); /* 10/24/2000 post_processing semaphore generation */ #ifdef PV_POSTPROC_ON // 2/14/2001 if (video->postFilterType != PV_NO_POST_PROC) { imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); /* Post-processing mode (copy previous MB) */ pp_prev1 = video->pstprcTypPrv + imv; pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = *pp_prev1; *(pp_dec_y + 1) = *(pp_prev1 + 1); *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth); *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1); /* chrominance */ /*4*MB_in_width*MB_in_height*/ pp_prev1 = video->pstprcTypPrv + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = *pp_prev1; pp_dec_u[size>>8] = pp_prev1[size>>8]; } #endif /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/ return; } Commit Message: Fix NPDs in h263 decoder Bug: 35269635 Test: decoded PoC with and without patch Change-Id: I636a14360c7801cc5bca63c9cb44d1d235df8fd8 (cherry picked from commit 2ad2a92318a3b9daf78ebcdc597085adbf32600d) CWE ID:
void SkippedMBMotionComp( VideoDecData *video ) { Vop *prev = video->prevVop; Vop *comp; int ypos, xpos; PIXEL *c_comp, *c_prev; PIXEL *cu_comp, *cu_prev; PIXEL *cv_comp, *cv_prev; int width, width_uv; int32 offset; #ifdef PV_POSTPROC_ON // 2/14/2001 int imv; int32 size = (int32) video->nTotalMB << 8; uint8 *pp_dec_y, *pp_dec_u; uint8 *pp_prev1; int mvwidth = video->nMBPerRow << 1; #endif width = video->width; width_uv = width >> 1; ypos = video->mbnum_row << 4 ; xpos = video->mbnum_col << 4 ; offset = (int32)ypos * width + xpos; /* zero motion compensation for previous frame */ /*mby*width + mbx;*/ c_prev = prev->yChan; if (!c_prev) { ALOGE("b/35269635"); android_errorWriteLog(0x534e4554, "35269635"); return; } c_prev += offset; /*by*width_uv + bx;*/ cu_prev = prev->uChan + (offset >> 2) + (xpos >> 2); /*by*width_uv + bx;*/ cv_prev = prev->vChan + (offset >> 2) + (xpos >> 2); comp = video->currVop; c_comp = comp->yChan + offset; cu_comp = comp->uChan + (offset >> 2) + (xpos >> 2); cv_comp = comp->vChan + (offset >> 2) + (xpos >> 2); /* Copy previous reconstructed frame into the current frame */ PutSKIPPED_MB(c_comp, c_prev, width); PutSKIPPED_B(cu_comp, cu_prev, width_uv); PutSKIPPED_B(cv_comp, cv_prev, width_uv); /* 10/24/2000 post_processing semaphore generation */ #ifdef PV_POSTPROC_ON // 2/14/2001 if (video->postFilterType != PV_NO_POST_PROC) { imv = (offset >> 6) - (xpos >> 6) + (xpos >> 3); /* Post-processing mode (copy previous MB) */ pp_prev1 = video->pstprcTypPrv + imv; pp_dec_y = video->pstprcTypCur + imv; *pp_dec_y = *pp_prev1; *(pp_dec_y + 1) = *(pp_prev1 + 1); *(pp_dec_y + mvwidth) = *(pp_prev1 + mvwidth); *(pp_dec_y + mvwidth + 1) = *(pp_prev1 + mvwidth + 1); /* chrominance */ /*4*MB_in_width*MB_in_height*/ pp_prev1 = video->pstprcTypPrv + (size >> 6) + ((imv + (xpos >> 3)) >> 2); pp_dec_u = video->pstprcTypCur + (size >> 6) + ((imv + (xpos >> 3)) >> 2); *pp_dec_u = *pp_prev1; pp_dec_u[size>>8] = pp_prev1[size>>8]; } #endif /*---------------------------------------------------------------------------- ; Return nothing or data or data pointer ----------------------------------------------------------------------------*/ return; }
174,005
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index) { struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table; int i, err = 0; int free = -1; mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac); mutex_lock(&table->mutex); for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) { if (free < 0 && !table->refs[i]) { free = i; continue; } if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) { /* MAC already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } mlx4_dbg(dev, "Free MAC index is %d\n", free); if (table->total == table->max) { /* No free mac entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID); err = mlx4_set_port_mac_table(dev, port, table->entries); if (unlikely(err)) { mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; } Commit Message: mlx4_en: Fix out of bounds array access When searching for a free entry in either mlx4_register_vlan() or mlx4_register_mac(), and there is no free entry, the loop terminates without updating the local variable free thus causing out of array bounds access. Fix this by adding a proper check outside the loop. Signed-off-by: Eli Cohen <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
int mlx4_register_mac(struct mlx4_dev *dev, u8 port, u64 mac, int *index) { struct mlx4_mac_table *table = &mlx4_priv(dev)->port[port].mac_table; int i, err = 0; int free = -1; mlx4_dbg(dev, "Registering MAC: 0x%llx\n", (unsigned long long) mac); mutex_lock(&table->mutex); for (i = 0; i < MLX4_MAX_MAC_NUM - 1; i++) { if (free < 0 && !table->refs[i]) { free = i; continue; } if (mac == (MLX4_MAC_MASK & be64_to_cpu(table->entries[i]))) { /* MAC already registered, increase refernce count */ *index = i; ++table->refs[i]; goto out; } } if (free < 0) { err = -ENOMEM; goto out; } mlx4_dbg(dev, "Free MAC index is %d\n", free); if (table->total == table->max) { /* No free mac entries */ err = -ENOSPC; goto out; } /* Register new MAC */ table->refs[free] = 1; table->entries[free] = cpu_to_be64(mac | MLX4_MAC_VALID); err = mlx4_set_port_mac_table(dev, port, table->entries); if (unlikely(err)) { mlx4_err(dev, "Failed adding MAC: 0x%llx\n", (unsigned long long) mac); table->refs[free] = 0; table->entries[free] = 0; goto out; } *index = free; ++table->total; out: mutex_unlock(&table->mutex); return err; }
169,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, --, NULL */ const char *args[11]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } Commit Message: a-a-i-d-to-abrt-cache: make own random temporary directory The set-user-ID wrapper must use own new temporary directory in order to avoid security issues with unpacking specially crafted debuginfo packages that might be used to create files or symlinks anywhere on the file system as the abrt user. Withot the forking code the temporary directory would remain on the filesystem in the case where all debuginfo data are already available. This is caused by the fact that the underlying libreport functionality accepts path to a desired temporary directory and creates it only if necessary. Otherwise, the directory is not touched at all. This commit addresses CVE-2015-5273 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-59
int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-y] [-i BUILD_IDS_FILE|-i -] [-e PATH[:PATH]...]\n" "\t[-r REPO]\n" "\n" "Installs debuginfo packages for all build-ids listed in BUILD_IDS_FILE to\n" "ABRT system cache." ); enum { OPT_v = 1 << 0, OPT_y = 1 << 1, OPT_i = 1 << 2, OPT_e = 1 << 3, OPT_r = 1 << 4, OPT_s = 1 << 5, }; const char *build_ids = "build_ids"; const char *exact = NULL; const char *repo = NULL; const char *size_mb = NULL; struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_BOOL ('y', "yes", NULL, _("Noninteractive, assume 'Yes' to all questions")), OPT_STRING('i', "ids", &build_ids, "BUILD_IDS_FILE", _("- means STDIN, default: build_ids")), OPT_STRING('e', "exact", &exact, "EXACT", _("Download only specified files")), OPT_STRING('r', "repo", &repo, "REPO", _("Pattern to use when searching for repos, default: *debug*")), OPT_STRING('s', "size_mb", &size_mb, "SIZE_MB", _("Ignored option")), OPT_END() }; const unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); const gid_t egid = getegid(); const gid_t rgid = getgid(); const uid_t euid = geteuid(); const gid_t ruid = getuid(); /* We need to open the build ids file under the caller's UID/GID to avoid * information disclosures when reading files with changed UID. * Unfortunately, we cannot replace STDIN with the new fd because ABRT uses * STDIN to communicate with the caller. So, the following code opens a * dummy file descriptor to the build ids file and passes the new fd's proc * path to the wrapped program in the ids argument. * The new fd remains opened, the OS will close it for us. */ char *build_ids_self_fd = NULL; if (strcmp("-", build_ids) != 0) { if (setregid(egid, rgid) < 0) perror_msg_and_die("setregid(egid, rgid)"); if (setreuid(euid, ruid) < 0) perror_msg_and_die("setreuid(euid, ruid)"); const int build_ids_fd = open(build_ids, O_RDONLY); if (setregid(rgid, egid) < 0) perror_msg_and_die("setregid(rgid, egid)"); if (setreuid(ruid, euid) < 0 ) perror_msg_and_die("setreuid(ruid, euid)"); if (build_ids_fd < 0) perror_msg_and_die("Failed to open file '%s'", build_ids); /* We are not going to free this memory. There is no place to do so. */ build_ids_self_fd = xasprintf("/proc/self/fd/%d", build_ids_fd); } char tmp_directory[] = LARGE_DATA_TMP_DIR"/abrt-tmp-debuginfo.XXXXXX"; if (mkdtemp(tmp_directory) == NULL) perror_msg_and_die("Failed to create working directory"); log_info("Created working directory: %s", tmp_directory); /* name, -v, --ids, -, -y, -e, EXACT, -r, REPO, -t, PATH, --, NULL */ const char *args[13]; { const char *verbs[] = { "", "-v", "-vv", "-vvv" }; unsigned i = 0; args[i++] = EXECUTABLE; args[i++] = "--ids"; args[i++] = (build_ids_self_fd != NULL) ? build_ids_self_fd : "-"; if (g_verbose > 0) args[i++] = verbs[g_verbose <= 3 ? g_verbose : 3]; if ((opts & OPT_y)) args[i++] = "-y"; if ((opts & OPT_e)) { args[i++] = "--exact"; args[i++] = exact; } if ((opts & OPT_r)) { args[i++] = "--repo"; args[i++] = repo; } args[i++] = "--tmpdir"; args[i++] = tmp_directory; args[i++] = "--"; args[i] = NULL; } /* Switch real user/group to effective ones. * Otherwise yum library gets confused - gets EPERM (why??). */ /* do setregid only if we have to, to not upset selinux needlessly */ if (egid != rgid) IGNORE_RESULT(setregid(egid, egid)); if (euid != ruid) { IGNORE_RESULT(setreuid(euid, euid)); /* We are suid'ed! */ /* Prevent malicious user from messing up with suid'ed process: */ #if 1 static const char *whitelist[] = { "REPORT_CLIENT_SLAVE", // Check if the app is being run as a slave "LANG", }; const size_t wlsize = sizeof(whitelist)/sizeof(char*); char *setlist[sizeof(whitelist)/sizeof(char*)] = { 0 }; char *p = NULL; for (size_t i = 0; i < wlsize; i++) if ((p = getenv(whitelist[i])) != NULL) setlist[i] = xstrdup(p); clearenv(); for (size_t i = 0; i < wlsize; i++) if (setlist[i] != NULL) { xsetenv(whitelist[i], setlist[i]); free(setlist[i]); } #else /* Clear dangerous stuff from env */ static const char forbid[] = "LD_LIBRARY_PATH" "\0" "LD_PRELOAD" "\0" "LD_TRACE_LOADED_OBJECTS" "\0" "LD_BIND_NOW" "\0" "LD_AOUT_LIBRARY_PATH" "\0" "LD_AOUT_PRELOAD" "\0" "LD_NOWARN" "\0" "LD_KEEPDIR" "\0" ; const char *p = forbid; do { unsetenv(p); p += strlen(p) + 1; } while (*p); #endif /* Set safe PATH */ char path_env[] = "PATH=/usr/sbin:/sbin:/usr/bin:/bin:"BIN_DIR":"SBIN_DIR; if (euid != 0) strcpy(path_env, "PATH=/usr/bin:/bin:"BIN_DIR); putenv(path_env); /* Use safe umask */ umask(0022); } pid_t pid = fork(); if (pid < 0) perror_msg_and_die("fork"); if (pid == 0) { execvp(EXECUTABLE, (char **)args); error_msg_and_die("Can't execute %s", EXECUTABLE); } int status; if (safe_waitpid(pid, &status, 0) < 0) perror_msg_and_die("waitpid"); if (rmdir(tmp_directory) >= 0) log_info("Removed working directory: %s", tmp_directory); else if (errno != ENOENT) perror_msg("Failed to remove working directory"); /* Normal execution should exit here. */ if (WIFEXITED(status)) return WEXITSTATUS(status); if (WIFSIGNALED(status)) error_msg_and_die("Child terminated with signal %d", WTERMSIG(status)); error_msg_and_die("Child exit failed"); }
166,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA): JBIG2Segment(segNumA) { w = wA; h = hA; line = (wA + 7) >> 3; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); data[h * line] = 0; } Commit Message: CWE ID: CWE-189
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA): JBIG2Segment(segNumA) { w = wA; h = hA; line = (wA + 7) >> 3; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmallocn(h, line + 1); data[h * line] = 0; }
164,612
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_LINEARSIZE); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image, (unsigned int) (Max(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (Max(1,(image->columns+3)/4) * 16)); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) strcpy(software,"IMAGEMAGICK"); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static void WriteDDSInfo(Image *image, const size_t pixelFormat, const size_t compression, const size_t mipmaps) { char software[MaxTextExtent]; register ssize_t i; unsigned int format, caps, flags; flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_LINEARSIZE); caps=(unsigned int) DDSCAPS_TEXTURE; format=(unsigned int) pixelFormat; if (mipmaps > 0) { flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); } if (format != DDPF_FOURCC && image->matte) format=format | DDPF_ALPHAPIXELS; (void) WriteBlob(image,4,(unsigned char *) "DDS "); (void) WriteBlobLSBLong(image,124); (void) WriteBlobLSBLong(image,flags); (void) WriteBlobLSBLong(image,(unsigned int) image->rows); (void) WriteBlobLSBLong(image,(unsigned int) image->columns); if (compression == FOURCC_DXT1) (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16)); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); (void) ResetMagickMemory(software,0,sizeof(software)); (void) strcpy(software,"IMAGEMAGICK"); (void) WriteBlob(image,44,(unsigned char *) software); (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,format); if (pixelFormat == DDPF_FOURCC) { (void) WriteBlobLSBLong(image,(unsigned int) compression); for(i=0;i < 5;i++) // bitcount / masks (void) WriteBlobLSBLong(image,0x00); } else { (void) WriteBlobLSBLong(image,0x00); if (image->matte) { (void) WriteBlobLSBLong(image,32); (void) WriteBlobLSBLong(image,0xff0000); (void) WriteBlobLSBLong(image,0xff00); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0xff000000); } else { (void) WriteBlobLSBLong(image,24); (void) WriteBlobLSBLong(image,0xff); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); (void) WriteBlobLSBLong(image,0x00); } } (void) WriteBlobLSBLong(image,caps); for(i=0;i < 4;i++) // ddscaps2 + reserved region (void) WriteBlobLSBLong(image,0x00); }
168,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionScriptAndCaptureVisibleTest() : http_url("http://www.google.com"), http_url_with_path("http://www.google.com/index.html"), https_url("https://www.google.com"), example_com("https://example.com"), test_example_com("https://test.example.com"), sample_example_com("https://sample.example.com"), file_url("file:///foo/bar"), favicon_url("chrome://favicon/http://www.google.com"), extension_url("chrome-extension://" + crx_file::id_util::GenerateIdForPath( base::FilePath(FILE_PATH_LITERAL("foo")))), settings_url("chrome://settings"), about_url("about:flags") { urls_.insert(http_url); urls_.insert(http_url_with_path); urls_.insert(https_url); urls_.insert(example_com); urls_.insert(test_example_com); urls_.insert(sample_example_com); urls_.insert(file_url); urls_.insert(favicon_url); urls_.insert(extension_url); urls_.insert(settings_url); urls_.insert(about_url); PermissionsData::SetPolicyDelegate(NULL); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20
ExtensionScriptAndCaptureVisibleTest() : http_url("http://www.google.com"), http_url_with_path("http://www.google.com/index.html"), https_url("https://www.google.com"), example_com("https://example.com"), test_example_com("https://test.example.com"), sample_example_com("https://sample.example.com"), file_url("file:///foo/bar"), favicon_url("chrome://favicon/http://www.google.com"), extension_url("chrome-extension://" + crx_file::id_util::GenerateIdForPath( base::FilePath(FILE_PATH_LITERAL("foo")))), settings_url("chrome://settings"), about_flags_url("about:flags") { urls_.insert(http_url); urls_.insert(http_url_with_path); urls_.insert(https_url); urls_.insert(example_com); urls_.insert(test_example_com); urls_.insert(sample_example_com); urls_.insert(file_url); urls_.insert(favicon_url); urls_.insert(extension_url); urls_.insert(settings_url); urls_.insert(about_flags_url); PermissionsData::SetPolicyDelegate(NULL); }
173,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } Commit Message: xfrm_user: fix info leak in copy_to_user_state() The memory reserved to dump the xfrm state includes the padding bytes of struct xfrm_usersa_info added by the compiler for alignment (7 for amd64, 3 for i386). Add an explicit memset(0) before filling the buffer to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memset(p, 0, sizeof(*p)); memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; }
166,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); } Commit Message: Add OVERRIDE to ui::TreeModelObserver overridden methods. BUG=None TEST=None [email protected] Review URL: http://codereview.chromium.org/7046093 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88827 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void AssertObserverCount(int added_count, int removed_count, void AssertObserverCount(int added_count, int removed_count, int changed_count) { ASSERT_EQ(added_count, added_count_); ASSERT_EQ(removed_count, removed_count_); ASSERT_EQ(changed_count, changed_count_); }
170,468
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); } Commit Message: Issue #656: Fix CVE-2016-1541, VU#862384 When reading OS X metadata entries in Zip archives that were stored without compression, libarchive would use the uncompressed entry size to allocate a buffer but would use the compressed entry size to limit the amount of data copied into that buffer. Since the compressed and uncompressed sizes are provided by data in the archive itself, an attacker could manipulate these values to write data beyond the end of the allocated buffer. This fix provides three new checks to guard against such manipulation and to make libarchive generally more robust when handling this type of entry: 1. If an OS X metadata entry is stored without compression, abort the entire archive if the compressed and uncompressed data sizes do not match. 2. When sanity-checking the size of an OS X metadata entry, abort this entry if either the compressed or uncompressed size is larger than 4MB. 3. When copying data into the allocated buffer, check the copy size against both the compressed entry size and uncompressed entry size. CWE ID: CWE-20
zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, struct zip_entry *rsrc) { struct zip *zip = (struct zip *)a->format->data; unsigned char *metadata, *mp; int64_t offset = archive_filter_bytes(&a->archive, 0); size_t remaining_bytes, metadata_bytes; ssize_t hsize; int ret = ARCHIVE_OK, eof; switch(rsrc->compression) { case 0: /* No compression. */ if (rsrc->uncompressed_size != rsrc->compressed_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Malformed OS X metadata entry: inconsistent size"); return (ARCHIVE_FATAL); } #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ #endif break; default: /* Unsupported compression. */ /* Return a warning. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Unsupported ZIP compression method (%s)", compression_name(rsrc->compression)); /* We can't decompress this entry, but we will * be able to skip() it and try the next entry. */ return (ARCHIVE_WARN); } if (rsrc->uncompressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->uncompressed_size); return (ARCHIVE_WARN); } if (rsrc->compressed_size > (4 * 1024 * 1024)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Mac metadata is too large: %jd > 4M bytes", (intmax_t)rsrc->compressed_size); return (ARCHIVE_WARN); } metadata = malloc((size_t)rsrc->uncompressed_size); if (metadata == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for Mac metadata"); return (ARCHIVE_FATAL); } if (offset < rsrc->local_header_offset) __archive_read_consume(a, rsrc->local_header_offset - offset); else if (offset != rsrc->local_header_offset) { __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET); } hsize = zip_get_local_file_header_size(a, 0); __archive_read_consume(a, hsize); remaining_bytes = (size_t)rsrc->compressed_size; metadata_bytes = (size_t)rsrc->uncompressed_size; mp = metadata; eof = 0; while (!eof && remaining_bytes) { const unsigned char *p; ssize_t bytes_avail; size_t bytes_used; p = __archive_read_ahead(a, 1, &bytes_avail); if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated ZIP file header"); ret = ARCHIVE_WARN; goto exit_mac_metadata; } if ((size_t)bytes_avail > remaining_bytes) bytes_avail = remaining_bytes; switch(rsrc->compression) { case 0: /* No compression. */ if ((size_t)bytes_avail > metadata_bytes) bytes_avail = metadata_bytes; memcpy(mp, p, bytes_avail); bytes_used = (size_t)bytes_avail; metadata_bytes -= bytes_used; mp += bytes_used; if (metadata_bytes == 0) eof = 1; break; #ifdef HAVE_ZLIB_H case 8: /* Deflate compression. */ { int r; ret = zip_deflate_init(a, zip); if (ret != ARCHIVE_OK) goto exit_mac_metadata; zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; zip->stream.avail_in = (uInt)bytes_avail; zip->stream.total_in = 0; zip->stream.next_out = mp; zip->stream.avail_out = (uInt)metadata_bytes; zip->stream.total_out = 0; r = inflate(&zip->stream, 0); switch (r) { case Z_OK: break; case Z_STREAM_END: eof = 1; break; case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Out of memory for ZIP decompression"); ret = ARCHIVE_FATAL; goto exit_mac_metadata; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "ZIP decompression failed (%d)", r); ret = ARCHIVE_FATAL; goto exit_mac_metadata; } bytes_used = zip->stream.total_in; metadata_bytes -= zip->stream.total_out; mp += zip->stream.total_out; break; } #endif default: bytes_used = 0; break; } __archive_read_consume(a, bytes_used); remaining_bytes -= bytes_used; } archive_entry_copy_mac_metadata(entry, metadata, (size_t)rsrc->uncompressed_size - metadata_bytes); exit_mac_metadata: __archive_read_seek(a, offset, SEEK_SET); zip->decompress_init = 0; free(metadata); return (ret); }
167,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) { for (int page_index : visible_pages_) { if (pages_[page_index]->GetPage() == page) return page_index; } return -1; } Commit Message: Copy visible_pages_ when iterating over it. On this case, a call inside the loop may cause visible_pages_ to change. Bug: 822091 Change-Id: I41b0715faa6fe3e39203cd9142cf5ea38e59aefb Reviewed-on: https://chromium-review.googlesource.com/964592 Reviewed-by: dsinclair <[email protected]> Commit-Queue: Henrique Nakashima <[email protected]> Cr-Commit-Position: refs/heads/master@{#543494} CWE ID: CWE-20
int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) { // Copy visible_pages_ since it can change as a result of loading the page in // GetPage(). See https://crbug.com/822091. std::vector<int> visible_pages_copy(visible_pages_); for (int page_index : visible_pages_copy) { if (pages_[page_index]->GetPage() == page) return page_index; } return -1; }
172,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sclp_ctl_ioctl_sccb(void __user *user_area) { struct sclp_ctl_sccb ctl_sccb; struct sccb_header *sccb; int rc; if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb))) return -EFAULT; if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw)) return -EOPNOTSUPP; sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA); if (!sccb) return -ENOMEM; if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) { rc = -EFAULT; goto out_free; } if (sccb->length > PAGE_SIZE || sccb->length < 8) return -EINVAL; if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) { rc = -EFAULT; goto out_free; } rc = sclp_sync_request(ctl_sccb.cmdw, sccb); if (rc) goto out_free; if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length)) rc = -EFAULT; out_free: free_page((unsigned long) sccb); return rc; } Commit Message: s390/sclp_ctl: fix potential information leak with /dev/sclp The sclp_ctl_ioctl_sccb function uses two copy_from_user calls to retrieve the sclp request from user space. The first copy_from_user fetches the length of the request which is stored in the first two bytes of the request. The second copy_from_user gets the complete sclp request, but this copies the length field a second time. A malicious user may have changed the length in the meantime. Reported-by: Pengfei Wang <[email protected]> Reviewed-by: Michael Holzheu <[email protected]> Signed-off-by: Martin Schwidefsky <[email protected]> CWE ID: CWE-362
static int sclp_ctl_ioctl_sccb(void __user *user_area) { struct sclp_ctl_sccb ctl_sccb; struct sccb_header *sccb; unsigned long copied; int rc; if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb))) return -EFAULT; if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw)) return -EOPNOTSUPP; sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA); if (!sccb) return -ENOMEM; copied = PAGE_SIZE - copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), PAGE_SIZE); if (offsetof(struct sccb_header, length) + sizeof(sccb->length) > copied || sccb->length > copied) { rc = -EFAULT; goto out_free; } if (sccb->length < 8) { rc = -EINVAL; goto out_free; } rc = sclp_sync_request(ctl_sccb.cmdw, sccb); if (rc) goto out_free; if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length)) rc = -EFAULT; out_free: free_page((unsigned long) sccb); return rc; }
167,020
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5]; int nbchar = 0; int cur, l; int count = 0; SHRINK; GROW; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && (IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ { if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (cdata) break; else { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); } } COPY_BUF(l,buf,nbchar,cur); if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } nbchar = 0; /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } count++; if (count > 50) { GROW; count = 0; } NEXTL(l); cur = CUR_CHAR(l); } if (nbchar != 0) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } } if ((cur != 0) && (!IS_CHAR(cur))) { /* Generate the error and skip the offending character */ xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "PCDATA invalid Char value %d\n", cur); NEXTL(l); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { xmlChar buf[XML_PARSER_BIG_BUFFER_SIZE + 5]; int nbchar = 0; int cur, l; int count = 0; SHRINK; GROW; cur = CUR_CHAR(l); while ((cur != '<') && /* checked */ (cur != '&') && (IS_CHAR(cur))) /* test also done in xmlCurrentChar() */ { if ((cur == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (cdata) break; else { xmlFatalErr(ctxt, XML_ERR_MISPLACED_CDATA_END, NULL); } } COPY_BUF(l,buf,nbchar,cur); if (nbchar >= XML_PARSER_BIG_BUFFER_SIZE) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } nbchar = 0; /* something really bad happened in the SAX callback */ if (ctxt->instate != XML_PARSER_CONTENT) return; } count++; if (count > 50) { GROW; count = 0; if (ctxt->instate == XML_PARSER_EOF) return; } NEXTL(l); cur = CUR_CHAR(l); } if (nbchar != 0) { buf[nbchar] = 0; /* * OK the segment is to be consumed as chars. */ if ((ctxt->sax != NULL) && (!ctxt->disableSAX)) { if (areBlanks(ctxt, buf, nbchar, 0)) { if (ctxt->sax->ignorableWhitespace != NULL) ctxt->sax->ignorableWhitespace(ctxt->userData, buf, nbchar); } else { if (ctxt->sax->characters != NULL) ctxt->sax->characters(ctxt->userData, buf, nbchar); if ((ctxt->sax->characters != ctxt->sax->ignorableWhitespace) && (*ctxt->space == -1)) *ctxt->space = -2; } } } if ((cur != 0) && (!IS_CHAR(cur))) { /* Generate the error and skip the offending character */ xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "PCDATA invalid Char value %d\n", cur); NEXTL(l); } }
171,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int cg_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { struct fuse_context *fc = fuse_get_context(); char *localbuf = NULL; struct cgfs_files *k = NULL; struct file_info *f = (struct file_info *)fi->fh; bool r; if (f->type != LXC_TYPE_CGFILE) { fprintf(stderr, "Internal error: directory cache info used in cg_write\n"); return -EIO; } if (offset) return 0; if (!fc) return -EIO; localbuf = alloca(size+1); localbuf[size] = '\0'; memcpy(localbuf, buf, size); if ((k = cgfs_get_key(f->controller, f->cgroup, f->file)) == NULL) { size = -EINVAL; goto out; } if (!fc_may_access(fc, f->controller, f->cgroup, f->file, O_WRONLY)) { size = -EACCES; goto out; } if (strcmp(f->file, "tasks") == 0 || strcmp(f->file, "/tasks") == 0 || strcmp(f->file, "/cgroup.procs") == 0 || strcmp(f->file, "cgroup.procs") == 0) r = do_write_pids(fc->pid, f->controller, f->cgroup, f->file, localbuf); else r = cgfs_set_value(f->controller, f->cgroup, f->file, localbuf); if (!r) size = -EINVAL; out: free_key(k); return size; } Commit Message: Implement privilege check when moving tasks When writing pids to a tasks file in lxcfs, lxcfs was checking for privilege over the tasks file but not over the pid being moved. Since the cgm_movepid request is done as root on the host, not with the requestor's credentials, we must copy the check which cgmanager was doing to ensure that the requesting task is allowed to change the victim task's cgroup membership. This is CVE-2015-1344 https://bugs.launchpad.net/ubuntu/+source/lxcfs/+bug/1512854 Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
int cg_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { struct fuse_context *fc = fuse_get_context(); char *localbuf = NULL; struct cgfs_files *k = NULL; struct file_info *f = (struct file_info *)fi->fh; bool r; if (f->type != LXC_TYPE_CGFILE) { fprintf(stderr, "Internal error: directory cache info used in cg_write\n"); return -EIO; } if (offset) return 0; if (!fc) return -EIO; localbuf = alloca(size+1); localbuf[size] = '\0'; memcpy(localbuf, buf, size); if ((k = cgfs_get_key(f->controller, f->cgroup, f->file)) == NULL) { size = -EINVAL; goto out; } if (!fc_may_access(fc, f->controller, f->cgroup, f->file, O_WRONLY)) { size = -EACCES; goto out; } if (strcmp(f->file, "tasks") == 0 || strcmp(f->file, "/tasks") == 0 || strcmp(f->file, "/cgroup.procs") == 0 || strcmp(f->file, "cgroup.procs") == 0) r = do_write_pids(fc->pid, fc->uid, f->controller, f->cgroup, f->file, localbuf); else r = cgfs_set_value(f->controller, f->cgroup, f->file, localbuf); if (!r) size = -EINVAL; out: free_key(k); return size; }
166,701