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: static int accept_server_socket(int sfd)
{
struct sockaddr_un remote;
struct pollfd pfd;
int fd;
socklen_t len = sizeof(struct sockaddr_un);
BTIF_TRACE_EVENT("accept fd %d", sfd);
/* make sure there is data to process */
pfd.fd = sfd;
pfd.events = POLLIN;
if (poll(&pfd, 1, 0) == 0)
{
BTIF_TRACE_EVENT("accept poll timeout");
return -1;
}
if ((fd = accept(sfd, (struct sockaddr *)&remote, &len)) == -1)
{
BTIF_TRACE_ERROR("sock accept failed (%s)", strerror(errno));
return -1;
}
return fd;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | static int accept_server_socket(int sfd)
{
struct sockaddr_un remote;
struct pollfd pfd;
int fd;
socklen_t len = sizeof(struct sockaddr_un);
BTIF_TRACE_EVENT("accept fd %d", sfd);
/* make sure there is data to process */
pfd.fd = sfd;
pfd.events = POLLIN;
if (TEMP_FAILURE_RETRY(poll(&pfd, 1, 0)) == 0)
{
BTIF_TRACE_EVENT("accept poll timeout");
return -1;
}
if ((fd = TEMP_FAILURE_RETRY(accept(sfd, (struct sockaddr *)&remote, &len))) == -1)
{
BTIF_TRACE_ERROR("sock accept failed (%s)", strerror(errno));
return -1;
}
return fd;
}
| 173,495 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UrlData::MergeFrom(const scoped_refptr<UrlData>& other) {
if (ValidateDataOrigin(other->data_origin_)) {
DCHECK(thread_checker_.CalledOnValidThread());
valid_until_ = std::max(valid_until_, other->valid_until_);
set_length(other->length_);
cacheable_ |= other->cacheable_;
range_supported_ |= other->range_supported_;
if (last_modified_.is_null()) {
last_modified_ = other->last_modified_;
}
bytes_read_from_cache_ += other->bytes_read_from_cache_;
set_has_opaque_data(other->has_opaque_data_);
multibuffer()->MergeFrom(other->multibuffer());
}
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | void UrlData::MergeFrom(const scoped_refptr<UrlData>& other) {
if (ValidateDataOrigin(other->data_origin_)) {
DCHECK(thread_checker_.CalledOnValidThread());
valid_until_ = std::max(valid_until_, other->valid_until_);
set_length(other->length_);
cacheable_ |= other->cacheable_;
range_supported_ |= other->range_supported_;
if (last_modified_.is_null()) {
last_modified_ = other->last_modified_;
}
bytes_read_from_cache_ += other->bytes_read_from_cache_;
// is_cors_corss_origin_ will not relax from true to false.
set_is_cors_cross_origin(other->is_cors_cross_origin_);
multibuffer()->MergeFrom(other->multibuffer());
}
}
| 172,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
Commit Message:
CWE ID: CWE-189 | void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename_len TSRMLS_DC) /* {{{ */
{
const char *s;
while ((s = zend_memrchr(filename, '/', filename_len))) {
filename_len = s - filename;
if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) {
break;
}
}
}
/* }}} */
| 164,572 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(SplFileObject, fgetcsv)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, fgetcsv)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape;
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC);
}
}
| 167,061 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster::GetPosition() const
{
const long long pos = m_element_start - m_pSegment->m_start;
assert(pos >= 0);
return pos;
}
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 Cluster::GetPosition() const
long Cluster::GetIndex() const { return m_index; }
long long Cluster::GetPosition() const {
const long long pos = m_element_start - m_pSegment->m_start;
assert(pos >= 0);
return pos;
}
| 174,350 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid = ARR_SIZE(insn_regs_intel) / 2;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
while (first <= last) {
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
mid = (first + last) / 2;
}
return 0;
}
Commit Message: x86: fast path checking for X86_insn_reg_intel()
CWE ID: CWE-125 | x86_reg X86_insn_reg_intel(unsigned int id, enum cs_ac_type *access)
{
static bool intel_regs_sorted = false;
unsigned int first = 0;
unsigned int last = ARR_SIZE(insn_regs_intel) - 1;
unsigned int mid;
if (!intel_regs_sorted) {
memcpy(insn_regs_intel_sorted, insn_regs_intel,
sizeof(insn_regs_intel_sorted));
qsort(insn_regs_intel_sorted,
ARR_SIZE(insn_regs_intel_sorted),
sizeof(struct insn_reg), regs_cmp);
intel_regs_sorted = true;
}
if (insn_regs_intel_sorted[0].insn > id ||
insn_regs_intel_sorted[last].insn < id) {
return 0;
}
while (first <= last) {
mid = (first + last) / 2;
if (insn_regs_intel_sorted[mid].insn < id) {
first = mid + 1;
} else if (insn_regs_intel_sorted[mid].insn == id) {
if (access) {
*access = insn_regs_intel_sorted[mid].access;
}
return insn_regs_intel_sorted[mid].reg;
} else {
if (mid == 0)
break;
last = mid - 1;
}
}
return 0;
}
| 169,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::ParseContentEncAESSettingsEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; //consume payload
assert(pos <= stop);
}
return 0;
}
Commit Message: 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 ContentEncoding::ParseContentEncAESSettingsEntry(
long long start, long long size, IMkvReader* pReader,
ContentEncAESSettings* aes) {
assert(pReader);
assert(aes);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E8) {
aes->cipher_mode = UnserializeUInt(pReader, pos, size);
if (aes->cipher_mode != 1)
return E_FILE_FORMAT_INVALID;
}
pos += size; // consume payload
assert(pos <= stop);
}
return 0;
}
| 174,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: void Navigate(NavigateParams* params) {
Browser* source_browser = params->browser;
if (source_browser)
params->initiating_profile = source_browser->profile();
DCHECK(params->initiating_profile);
if (!AdjustNavigateParamsForURL(params))
return;
#if BUILDFLAG(ENABLE_EXTENSIONS)
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(params->initiating_profile)->
enabled_extensions().GetExtensionOrAppByURL(params->url);
if (extension && extension->is_platform_app())
params->url = GURL(chrome::kExtensionInvalidRequestURL);
#endif
if (params->disposition == WindowOpenDisposition::NEW_POPUP &&
source_browser && source_browser->window()) {
params->disposition =
source_browser->window()->GetDispositionForPopupBounds(
params->window_bounds);
}
if (source_browser && source_browser->is_app() &&
params->disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) {
params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
if (!params->source_contents && params->browser) {
params->source_contents =
params->browser->tab_strip_model()->GetActiveWebContents();
}
WebContents* contents_to_navigate_or_insert =
params->contents_to_insert.get();
if (params->switch_to_singleton_tab) {
DCHECK_EQ(params->disposition, WindowOpenDisposition::SINGLETON_TAB);
contents_to_navigate_or_insert = params->switch_to_singleton_tab;
}
int singleton_index;
std::tie(params->browser, singleton_index) =
GetBrowserAndTabForDisposition(*params);
if (!params->browser)
return;
if (singleton_index != -1) {
contents_to_navigate_or_insert =
params->browser->tab_strip_model()->GetWebContentsAt(singleton_index);
}
#if defined(OS_CHROMEOS)
if (source_browser && source_browser != params->browser) {
MultiUserWindowManager* manager = MultiUserWindowManager::GetInstance();
if (manager) {
aura::Window* src_window = source_browser->window()->GetNativeWindow();
aura::Window* new_window = params->browser->window()->GetNativeWindow();
const AccountId& src_account_id =
manager->GetUserPresentingWindow(src_window);
if (src_account_id != manager->GetUserPresentingWindow(new_window)) {
manager->ShowWindowForUser(new_window, src_account_id);
}
}
}
#endif
if (GetSourceProfile(params) != params->browser->profile()) {
params->opener = nullptr;
params->source_contents = nullptr;
params->source_site_instance = nullptr;
params->referrer = content::Referrer();
}
ScopedBrowserShower shower(params, &contents_to_navigate_or_insert);
std::unique_ptr<WebContents> contents_to_insert =
std::move(params->contents_to_insert);
NormalizeDisposition(params);
if (params->window_action == NavigateParams::NO_ACTION &&
source_browser != params->browser &&
params->browser->tab_strip_model()->empty()) {
params->window_action = NavigateParams::SHOW_WINDOW;
}
if (params->window_action == NavigateParams::SHOW_WINDOW &&
params->disposition == WindowOpenDisposition::NEW_POPUP &&
params->user_gesture == false) {
params->window_action = NavigateParams::SHOW_WINDOW_INACTIVE;
}
bool user_initiated =
params->transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_TYPED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_BOOKMARK) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_GENERATED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_RELOAD) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_KEYWORD);
bool swapped_in_prerender = false;
if (!contents_to_navigate_or_insert) {
DCHECK(!params->url.is_empty());
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
contents_to_insert = CreateTargetContents(*params, params->url);
contents_to_navigate_or_insert = contents_to_insert.get();
} else {
DCHECK(params->source_contents);
contents_to_navigate_or_insert = params->source_contents;
prerender::PrerenderManager::Params prerender_params(
params, params->source_contents);
swapped_in_prerender = SwapInPrerender(params->url, &prerender_params);
if (swapped_in_prerender)
contents_to_navigate_or_insert = prerender_params.replaced_contents;
}
if (user_initiated)
contents_to_navigate_or_insert->NavigatedByUser();
if (!swapped_in_prerender) {
if (!HandleNonNavigationAboutURL(params->url)) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
}
} else {
}
if (params->source_contents &&
(params->disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB ||
params->disposition == WindowOpenDisposition::NEW_WINDOW) &&
(params->tabstrip_add_types & TabStripModel::ADD_INHERIT_OPENER))
params->source_contents->Focus();
if (params->source_contents == contents_to_navigate_or_insert ||
(swapped_in_prerender &&
params->disposition == WindowOpenDisposition::CURRENT_TAB)) {
params->browser->UpdateUIForNavigationInTab(
contents_to_navigate_or_insert, params->transition,
params->window_action, user_initiated);
} else if (singleton_index == -1) {
if (params->tabstrip_index != -1)
params->tabstrip_add_types |= TabStripModel::ADD_FORCE_INDEX;
DCHECK(contents_to_insert);
params->browser->tab_strip_model()->AddWebContents(
std::move(contents_to_insert), params->tabstrip_index,
params->transition, params->tabstrip_add_types);
}
if (singleton_index >= 0) {
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB &&
params->browser != source_browser)
params->window_action = NavigateParams::SHOW_WINDOW;
if (contents_to_navigate_or_insert->IsCrashed()) {
contents_to_navigate_or_insert->GetController().Reload(
content::ReloadType::NORMAL, true);
} else if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE &&
contents_to_navigate_or_insert->GetURL() != params->url) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
if (params->source_contents != contents_to_navigate_or_insert) {
params->browser->tab_strip_model()->ActivateTabAt(singleton_index,
user_initiated);
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB) {
if (params->source_contents->GetController().CanGoBack() ||
(params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeUINewTabURL &&
params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeSearchLocalNtpUrl &&
params->source_contents->GetLastCommittedURL().spec() !=
url::kAboutBlankURL))
params->source_contents->Focus();
else
params->source_contents->Close();
}
}
}
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(params->browser),
content::Details<WebContents>(contents_to_navigate_or_insert));
}
params->navigated_or_inserted_contents = contents_to_navigate_or_insert;
}
Commit Message: Mac: turn popups into new tabs while in fullscreen.
It's platform convention to show popups as new tabs while in
non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.)
This was implemented for Cocoa in a BrowserWindow override, but
it makes sense to just stick it into Browser and remove a ton
of override code put in just to support this.
BUG=858929, 868416
TEST=as in bugs
Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d
Reviewed-on: https://chromium-review.googlesource.com/1153455
Reviewed-by: Sidney San Martín <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#578755}
CWE ID: CWE-20 | void Navigate(NavigateParams* params) {
Browser* source_browser = params->browser;
if (source_browser)
params->initiating_profile = source_browser->profile();
DCHECK(params->initiating_profile);
if (!AdjustNavigateParamsForURL(params))
return;
#if BUILDFLAG(ENABLE_EXTENSIONS)
const extensions::Extension* extension =
extensions::ExtensionRegistry::Get(params->initiating_profile)->
enabled_extensions().GetExtensionOrAppByURL(params->url);
if (extension && extension->is_platform_app())
params->url = GURL(chrome::kExtensionInvalidRequestURL);
#endif
if (source_browser && source_browser->is_app() &&
params->disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) {
params->disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB;
}
if (!params->source_contents && params->browser) {
params->source_contents =
params->browser->tab_strip_model()->GetActiveWebContents();
}
WebContents* contents_to_navigate_or_insert =
params->contents_to_insert.get();
if (params->switch_to_singleton_tab) {
DCHECK_EQ(params->disposition, WindowOpenDisposition::SINGLETON_TAB);
contents_to_navigate_or_insert = params->switch_to_singleton_tab;
}
int singleton_index;
std::tie(params->browser, singleton_index) =
GetBrowserAndTabForDisposition(*params);
if (!params->browser)
return;
if (singleton_index != -1) {
contents_to_navigate_or_insert =
params->browser->tab_strip_model()->GetWebContentsAt(singleton_index);
}
#if defined(OS_CHROMEOS)
if (source_browser && source_browser != params->browser) {
MultiUserWindowManager* manager = MultiUserWindowManager::GetInstance();
if (manager) {
aura::Window* src_window = source_browser->window()->GetNativeWindow();
aura::Window* new_window = params->browser->window()->GetNativeWindow();
const AccountId& src_account_id =
manager->GetUserPresentingWindow(src_window);
if (src_account_id != manager->GetUserPresentingWindow(new_window)) {
manager->ShowWindowForUser(new_window, src_account_id);
}
}
}
#endif
if (GetSourceProfile(params) != params->browser->profile()) {
params->opener = nullptr;
params->source_contents = nullptr;
params->source_site_instance = nullptr;
params->referrer = content::Referrer();
}
ScopedBrowserShower shower(params, &contents_to_navigate_or_insert);
std::unique_ptr<WebContents> contents_to_insert =
std::move(params->contents_to_insert);
NormalizeDisposition(params);
if (params->window_action == NavigateParams::NO_ACTION &&
source_browser != params->browser &&
params->browser->tab_strip_model()->empty()) {
params->window_action = NavigateParams::SHOW_WINDOW;
}
if (params->window_action == NavigateParams::SHOW_WINDOW &&
params->disposition == WindowOpenDisposition::NEW_POPUP &&
params->user_gesture == false) {
params->window_action = NavigateParams::SHOW_WINDOW_INACTIVE;
}
bool user_initiated =
params->transition & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_TYPED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_BOOKMARK) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_GENERATED) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_AUTO_TOPLEVEL) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_RELOAD) ||
ui::PageTransitionCoreTypeIs(params->transition,
ui::PAGE_TRANSITION_KEYWORD);
bool swapped_in_prerender = false;
if (!contents_to_navigate_or_insert) {
DCHECK(!params->url.is_empty());
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
contents_to_insert = CreateTargetContents(*params, params->url);
contents_to_navigate_or_insert = contents_to_insert.get();
} else {
DCHECK(params->source_contents);
contents_to_navigate_or_insert = params->source_contents;
prerender::PrerenderManager::Params prerender_params(
params, params->source_contents);
swapped_in_prerender = SwapInPrerender(params->url, &prerender_params);
if (swapped_in_prerender)
contents_to_navigate_or_insert = prerender_params.replaced_contents;
}
if (user_initiated)
contents_to_navigate_or_insert->NavigatedByUser();
if (!swapped_in_prerender) {
if (!HandleNonNavigationAboutURL(params->url)) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
}
} else {
}
if (params->source_contents &&
(params->disposition == WindowOpenDisposition::NEW_FOREGROUND_TAB ||
params->disposition == WindowOpenDisposition::NEW_WINDOW) &&
(params->tabstrip_add_types & TabStripModel::ADD_INHERIT_OPENER))
params->source_contents->Focus();
if (params->source_contents == contents_to_navigate_or_insert ||
(swapped_in_prerender &&
params->disposition == WindowOpenDisposition::CURRENT_TAB)) {
params->browser->UpdateUIForNavigationInTab(
contents_to_navigate_or_insert, params->transition,
params->window_action, user_initiated);
} else if (singleton_index == -1) {
if (params->tabstrip_index != -1)
params->tabstrip_add_types |= TabStripModel::ADD_FORCE_INDEX;
DCHECK(contents_to_insert);
params->browser->tab_strip_model()->AddWebContents(
std::move(contents_to_insert), params->tabstrip_index,
params->transition, params->tabstrip_add_types);
}
if (singleton_index >= 0) {
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB &&
params->browser != source_browser)
params->window_action = NavigateParams::SHOW_WINDOW;
if (contents_to_navigate_or_insert->IsCrashed()) {
contents_to_navigate_or_insert->GetController().Reload(
content::ReloadType::NORMAL, true);
} else if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE &&
contents_to_navigate_or_insert->GetURL() != params->url) {
LoadURLInContents(contents_to_navigate_or_insert, params->url, params);
}
if (params->source_contents != contents_to_navigate_or_insert) {
params->browser->tab_strip_model()->ActivateTabAt(singleton_index,
user_initiated);
if (params->disposition == WindowOpenDisposition::SWITCH_TO_TAB) {
if (params->source_contents->GetController().CanGoBack() ||
(params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeUINewTabURL &&
params->source_contents->GetLastCommittedURL().spec() !=
chrome::kChromeSearchLocalNtpUrl &&
params->source_contents->GetLastCommittedURL().spec() !=
url::kAboutBlankURL))
params->source_contents->Focus();
else
params->source_contents->Close();
}
}
}
if (params->disposition != WindowOpenDisposition::CURRENT_TAB) {
content::NotificationService::current()->Notify(
chrome::NOTIFICATION_TAB_ADDED,
content::Source<content::WebContentsDelegate>(params->browser),
content::Details<WebContents>(contents_to_navigate_or_insert));
}
params->navigated_or_inserted_contents = contents_to_navigate_or_insert;
}
| 173,206 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CrosMock::SetSpeechSynthesisLibraryExpectations() {
InSequence s;
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.Times(AnyNumber())
.WillRepeatedly(Return(true));
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false))
.RetiresOnSaturation();
}
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 | void CrosMock::SetSpeechSynthesisLibraryExpectations() {
InSequence s;
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, StopSpeaking())
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, SetSpeakProperties(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, Speak(_))
.WillOnce(Return(true))
.RetiresOnSaturation();
EXPECT_CALL(*mock_speech_synthesis_library_, IsSpeaking())
.WillOnce(Return(true))
.WillOnce(Return(true))
.WillOnce(Return(false))
.RetiresOnSaturation();
}
| 170,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MockContentSettingsClient::allowAutoplay(bool default_value) {
return default_value || flags_->autoplay_allowed();
}
Commit Message: [Blink>Media] Allow autoplay muted on Android by default
There was a mistake causing autoplay muted is shipped on Android
but it will be disabled if the chromium embedder doesn't specify
content setting for "AllowAutoplay" preference. This CL makes the
AllowAutoplay preference true by default so that it is allowed by
embedders (including AndroidWebView) unless they explicitly
disable it.
Intent to ship:
https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ
BUG=689018
Review-Url: https://codereview.chromium.org/2677173002
Cr-Commit-Position: refs/heads/master@{#448423}
CWE ID: CWE-119 | bool MockContentSettingsClient::allowAutoplay(bool default_value) {
return flags_->autoplay_allowed();
}
| 172,015 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CairoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
cairo_surface_t *image;
cairo_pattern_t *pattern;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
cairo_matrix_t matrix;
int is_identity_transform;
buffer = (unsigned char *)gmalloc (width * height * 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_ARGB32,
width, height, width * 4);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24,
width, height, width * 4);
}
if (image == NULL) {
delete imgStr;
return;
}
pattern = cairo_pattern_create_for_surface (image);
if (pattern == NULL) {
delete imgStr;
return;
}
LOG (printf ("drawImageMask %dx%d\n", width, height));
cairo_matrix_init_translate (&matrix, 0, height);
cairo_matrix_scale (&matrix, width, -height);
cairo_pattern_set_matrix (pattern, &matrix);
cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR);
cairo_set_source (cairo, pattern);
cairo_paint (cairo);
if (cairo_shape) {
#if 0
cairo_rectangle (cairo_shape, 0., 0., width, height);
cairo_fill (cairo_shape);
#else
cairo_save (cairo_shape);
/* this should draw a rectangle the size of the image
* we use this instead of rect,fill because of the lack
* of EXTEND_PAD */
/* NOTE: this will multiply the edges of the image twice */
cairo_set_source (cairo_shape, pattern);
cairo_paint(cairo_shape);
cairo_restore (cairo_shape);
#endif
}
cairo_pattern_destroy (pattern);
cairo_surface_destroy (image);
free (buffer);
delete imgStr;
}
Commit Message:
CWE ID: CWE-189 | void CairoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
cairo_surface_t *image;
cairo_pattern_t *pattern;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
cairo_matrix_t matrix;
int is_identity_transform;
buffer = (unsigned char *)gmallocn3 (width, height, 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_ARGB32,
width, height, width * 4);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
image = cairo_image_surface_create_for_data (buffer, CAIRO_FORMAT_RGB24,
width, height, width * 4);
}
if (image == NULL) {
delete imgStr;
return;
}
pattern = cairo_pattern_create_for_surface (image);
if (pattern == NULL) {
delete imgStr;
return;
}
LOG (printf ("drawImageMask %dx%d\n", width, height));
cairo_matrix_init_translate (&matrix, 0, height);
cairo_matrix_scale (&matrix, width, -height);
cairo_pattern_set_matrix (pattern, &matrix);
cairo_pattern_set_filter (pattern, CAIRO_FILTER_BILINEAR);
cairo_set_source (cairo, pattern);
cairo_paint (cairo);
if (cairo_shape) {
#if 0
cairo_rectangle (cairo_shape, 0., 0., width, height);
cairo_fill (cairo_shape);
#else
cairo_save (cairo_shape);
/* this should draw a rectangle the size of the image
* we use this instead of rect,fill because of the lack
* of EXTEND_PAD */
/* NOTE: this will multiply the edges of the image twice */
cairo_set_source (cairo_shape, pattern);
cairo_paint(cairo_shape);
cairo_restore (cairo_shape);
#endif
}
cairo_pattern_destroy (pattern);
cairo_surface_destroy (image);
free (buffer);
delete imgStr;
}
| 164,605 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) {
ND_PRINT((ndo, "S"));
}
}
Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length.
It's not good enough to check whether all the data specified by the AVP
length was captured - you also have to check whether that length is
large enough for all the required data in the AVP.
This fixes a buffer over-read discovered by Yannick Formaggio.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat)
l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat, u_int length)
{
const uint32_t *ptr = (const uint32_t *)dat;
if (length < 4) {
ND_PRINT((ndo, "AVP too short"));
return;
}
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) {
ND_PRINT((ndo, "A"));
}
if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) {
ND_PRINT((ndo, "S"));
}
}
| 167,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 amd_gpio_probe(struct platform_device *pdev)
{
int ret = 0;
int irq_base;
struct resource *res;
struct amd_gpio *gpio_dev;
gpio_dev = devm_kzalloc(&pdev->dev,
sizeof(struct amd_gpio), GFP_KERNEL);
if (!gpio_dev)
return -ENOMEM;
spin_lock_init(&gpio_dev->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "Failed to get gpio io resource.\n");
return -EINVAL;
}
gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (!gpio_dev->base)
return -ENOMEM;
irq_base = platform_get_irq(pdev, 0);
if (irq_base < 0) {
dev_err(&pdev->dev, "Failed to get gpio IRQ.\n");
return -EINVAL;
}
gpio_dev->pdev = pdev;
gpio_dev->gc.direction_input = amd_gpio_direction_input;
gpio_dev->gc.direction_output = amd_gpio_direction_output;
gpio_dev->gc.get = amd_gpio_get_value;
gpio_dev->gc.set = amd_gpio_set_value;
gpio_dev->gc.set_debounce = amd_gpio_set_debounce;
gpio_dev->gc.dbg_show = amd_gpio_dbg_show;
gpio_dev->gc.base = 0;
gpio_dev->gc.label = pdev->name;
gpio_dev->gc.owner = THIS_MODULE;
gpio_dev->gc.parent = &pdev->dev;
gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS;
#if defined(CONFIG_OF_GPIO)
gpio_dev->gc.of_node = pdev->dev.of_node;
#endif
gpio_dev->groups = kerncz_groups;
gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups);
amd_pinctrl_desc.name = dev_name(&pdev->dev);
gpio_dev->pctrl = pinctrl_register(&amd_pinctrl_desc,
&pdev->dev, gpio_dev);
if (IS_ERR(gpio_dev->pctrl)) {
dev_err(&pdev->dev, "Couldn't register pinctrl driver\n");
return PTR_ERR(gpio_dev->pctrl);
}
ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev);
if (ret)
goto out1;
ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev),
0, 0, TOTAL_NUMBER_OF_PINS);
if (ret) {
dev_err(&pdev->dev, "Failed to add pin range\n");
goto out2;
}
ret = gpiochip_irqchip_add(&gpio_dev->gc,
&amd_gpio_irqchip,
0,
handle_simple_irq,
IRQ_TYPE_NONE);
if (ret) {
dev_err(&pdev->dev, "could not add irqchip\n");
ret = -ENODEV;
goto out2;
}
gpiochip_set_chained_irqchip(&gpio_dev->gc,
&amd_gpio_irqchip,
irq_base,
amd_gpio_irq_handler);
platform_set_drvdata(pdev, gpio_dev);
dev_dbg(&pdev->dev, "amd gpio driver loaded\n");
return ret;
out2:
gpiochip_remove(&gpio_dev->gc);
out1:
pinctrl_unregister(gpio_dev->pctrl);
return ret;
}
Commit Message: pinctrl: amd: Use devm_pinctrl_register() for pinctrl registration
Use devm_pinctrl_register() for pin control registration and clean
error path.
Signed-off-by: Laxman Dewangan <[email protected]>
Signed-off-by: Linus Walleij <[email protected]>
CWE ID: CWE-415 | static int amd_gpio_probe(struct platform_device *pdev)
{
int ret = 0;
int irq_base;
struct resource *res;
struct amd_gpio *gpio_dev;
gpio_dev = devm_kzalloc(&pdev->dev,
sizeof(struct amd_gpio), GFP_KERNEL);
if (!gpio_dev)
return -ENOMEM;
spin_lock_init(&gpio_dev->lock);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "Failed to get gpio io resource.\n");
return -EINVAL;
}
gpio_dev->base = devm_ioremap_nocache(&pdev->dev, res->start,
resource_size(res));
if (!gpio_dev->base)
return -ENOMEM;
irq_base = platform_get_irq(pdev, 0);
if (irq_base < 0) {
dev_err(&pdev->dev, "Failed to get gpio IRQ.\n");
return -EINVAL;
}
gpio_dev->pdev = pdev;
gpio_dev->gc.direction_input = amd_gpio_direction_input;
gpio_dev->gc.direction_output = amd_gpio_direction_output;
gpio_dev->gc.get = amd_gpio_get_value;
gpio_dev->gc.set = amd_gpio_set_value;
gpio_dev->gc.set_debounce = amd_gpio_set_debounce;
gpio_dev->gc.dbg_show = amd_gpio_dbg_show;
gpio_dev->gc.base = 0;
gpio_dev->gc.label = pdev->name;
gpio_dev->gc.owner = THIS_MODULE;
gpio_dev->gc.parent = &pdev->dev;
gpio_dev->gc.ngpio = TOTAL_NUMBER_OF_PINS;
#if defined(CONFIG_OF_GPIO)
gpio_dev->gc.of_node = pdev->dev.of_node;
#endif
gpio_dev->groups = kerncz_groups;
gpio_dev->ngroups = ARRAY_SIZE(kerncz_groups);
amd_pinctrl_desc.name = dev_name(&pdev->dev);
gpio_dev->pctrl = devm_pinctrl_register(&pdev->dev, &amd_pinctrl_desc,
gpio_dev);
if (IS_ERR(gpio_dev->pctrl)) {
dev_err(&pdev->dev, "Couldn't register pinctrl driver\n");
return PTR_ERR(gpio_dev->pctrl);
}
ret = gpiochip_add_data(&gpio_dev->gc, gpio_dev);
if (ret)
return ret;
ret = gpiochip_add_pin_range(&gpio_dev->gc, dev_name(&pdev->dev),
0, 0, TOTAL_NUMBER_OF_PINS);
if (ret) {
dev_err(&pdev->dev, "Failed to add pin range\n");
goto out2;
}
ret = gpiochip_irqchip_add(&gpio_dev->gc,
&amd_gpio_irqchip,
0,
handle_simple_irq,
IRQ_TYPE_NONE);
if (ret) {
dev_err(&pdev->dev, "could not add irqchip\n");
ret = -ENODEV;
goto out2;
}
gpiochip_set_chained_irqchip(&gpio_dev->gc,
&amd_gpio_irqchip,
irq_base,
amd_gpio_irq_handler);
platform_set_drvdata(pdev, gpio_dev);
dev_dbg(&pdev->dev, "amd gpio driver loaded\n");
return ret;
out2:
gpiochip_remove(&gpio_dev->gc);
return ret;
}
| 170,172 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int regset_tls_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES];
const struct user_desc *info;
if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) ||
(pos % sizeof(struct user_desc)) != 0 ||
(count % sizeof(struct user_desc)) != 0)
return -EINVAL;
if (kbuf)
info = kbuf;
else if (__copy_from_user(infobuf, ubuf, count))
return -EFAULT;
else
info = infobuf;
set_tls_desc(target,
GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)),
info, count / sizeof(struct user_desc));
return 0;
}
Commit Message: x86/tls: Validate TLS entries to protect espfix
Installing a 16-bit RW data segment into the GDT defeats espfix.
AFAICT this will not affect glibc, Wine, or dosemu at all.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: H. Peter Anvin <[email protected]>
Cc: [email protected]
Cc: Konrad Rzeszutek Wilk <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: [email protected] <[email protected]>
Cc: Willy Tarreau <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | int regset_tls_set(struct task_struct *target, const struct user_regset *regset,
unsigned int pos, unsigned int count,
const void *kbuf, const void __user *ubuf)
{
struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES];
const struct user_desc *info;
int i;
if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) ||
(pos % sizeof(struct user_desc)) != 0 ||
(count % sizeof(struct user_desc)) != 0)
return -EINVAL;
if (kbuf)
info = kbuf;
else if (__copy_from_user(infobuf, ubuf, count))
return -EFAULT;
else
info = infobuf;
for (i = 0; i < count / sizeof(struct user_desc); i++)
if (!tls_desc_okay(info + i))
return -EINVAL;
set_tls_desc(target,
GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)),
info, count / sizeof(struct user_desc));
return 0;
}
| 166,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv,
int listener)
{
struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL);
if (!cma_xprt)
return NULL;
svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv);
INIT_LIST_HEAD(&cma_xprt->sc_accept_q);
INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q);
INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q);
INIT_LIST_HEAD(&cma_xprt->sc_frmr_q);
INIT_LIST_HEAD(&cma_xprt->sc_ctxts);
INIT_LIST_HEAD(&cma_xprt->sc_maps);
init_waitqueue_head(&cma_xprt->sc_send_wait);
spin_lock_init(&cma_xprt->sc_lock);
spin_lock_init(&cma_xprt->sc_rq_dto_lock);
spin_lock_init(&cma_xprt->sc_frmr_q_lock);
spin_lock_init(&cma_xprt->sc_ctxt_lock);
spin_lock_init(&cma_xprt->sc_map_lock);
/*
* Note that this implies that the underlying transport support
* has some form of congestion control (see RFC 7530 section 3.1
* paragraph 2). For now, we assume that all supported RDMA
* transports are suitable here.
*/
set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags);
if (listener)
set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags);
return cma_xprt;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static struct svcxprt_rdma *rdma_create_xprt(struct svc_serv *serv,
int listener)
{
struct svcxprt_rdma *cma_xprt = kzalloc(sizeof *cma_xprt, GFP_KERNEL);
if (!cma_xprt)
return NULL;
svc_xprt_init(&init_net, &svc_rdma_class, &cma_xprt->sc_xprt, serv);
INIT_LIST_HEAD(&cma_xprt->sc_accept_q);
INIT_LIST_HEAD(&cma_xprt->sc_rq_dto_q);
INIT_LIST_HEAD(&cma_xprt->sc_read_complete_q);
INIT_LIST_HEAD(&cma_xprt->sc_frmr_q);
INIT_LIST_HEAD(&cma_xprt->sc_ctxts);
INIT_LIST_HEAD(&cma_xprt->sc_rw_ctxts);
init_waitqueue_head(&cma_xprt->sc_send_wait);
spin_lock_init(&cma_xprt->sc_lock);
spin_lock_init(&cma_xprt->sc_rq_dto_lock);
spin_lock_init(&cma_xprt->sc_frmr_q_lock);
spin_lock_init(&cma_xprt->sc_ctxt_lock);
spin_lock_init(&cma_xprt->sc_rw_ctxt_lock);
/*
* Note that this implies that the underlying transport support
* has some form of congestion control (see RFC 7530 section 3.1
* paragraph 2). For now, we assume that all supported RDMA
* transports are suitable here.
*/
set_bit(XPT_CONG_CTRL, &cma_xprt->sc_xprt.xpt_flags);
if (listener)
set_bit(XPT_LISTENER, &cma_xprt->sc_xprt.xpt_flags);
return cma_xprt;
}
| 168,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
qemu_vfree(r->iov.iov_base);
}
Commit Message: scsi-disk: lazily allocate bounce buffer
It will not be needed for reads and writes if the HBA provides a sglist.
In addition, this lets scsi-disk refuse commands with an excessive
allocation length, as well as limit memory on usual well-behaved guests.
Signed-off-by: Paolo Bonzini <[email protected]>
Signed-off-by: Kevin Wolf <[email protected]>
CWE ID: CWE-119 | static void scsi_free_request(SCSIRequest *req)
{
SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);
if (r->iov.iov_base) {
qemu_vfree(r->iov.iov_base);
}
}
| 166,553 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Resource::LastPluginRefWasDeleted(bool instance_destroyed) {
DCHECK(resource_id_ != 0);
instance()->module()->GetCallbackTracker()->PostAbortForResource(
resource_id_);
resource_id_ = 0;
if (instance_destroyed)
instance_ = NULL;
}
Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed,
BUG=85808
Review URL: http://codereview.chromium.org/7196001
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void Resource::LastPluginRefWasDeleted(bool instance_destroyed) {
void Resource::LastPluginRefWasDeleted() {
DCHECK(resource_id_ != 0);
instance()->module()->GetCallbackTracker()->PostAbortForResource(
resource_id_);
resource_id_ = 0;
}
| 170,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
Commit Message: Fix security vulnerability: Effect command might allow negative indexes
Bug: 32448258
Bug: 32095626
Test: Use POC bug or cts security test
Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df
(cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
CWE ID: CWE-200 | int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band < 0 || band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (band < 0) {
android_errorWriteLog(0x534e4554, "32095626");
ALOGE("\tERROR Equalizer_setParameter() EQ_PARAM_BAND_LEVEL band %d", band);
}
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
| 174,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 0;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 0;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
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 | _exsltDateTruncateDate (exsltDateValPtr dt, exsltDateType type)
{
if (dt == NULL)
return 1;
if ((type & XS_TIME) != XS_TIME) {
dt->value.date.hour = 0;
dt->value.date.min = 0;
dt->value.date.sec = 0.0;
}
if ((type & XS_GDAY) != XS_GDAY)
dt->value.date.day = 1;
if ((type & XS_GMONTH) != XS_GMONTH)
dt->value.date.mon = 1;
if ((type & XS_GYEAR) != XS_GYEAR)
dt->value.date.year = 0;
dt->type = type;
return 0;
}
| 173,290 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
if (pending_entry_index_ == -1)
delete pending_entry_;
pending_entry_ = NULL;
pending_entry_index_ = -1;
DiscardTransientEntry();
}
Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof.
BUG=280512
BUG=278899
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/23978003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
DiscardPendingEntry();
DiscardTransientEntry();
}
void NavigationControllerImpl::DiscardPendingEntry() {
if (pending_entry_index_ == -1)
delete pending_entry_;
pending_entry_ = NULL;
pending_entry_index_ = -1;
}
| 171,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: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
if (pkt->data.psnr.psnr[0] < min_psnr_)
min_psnr_ = pkt->data.psnr.psnr[0];
}
| 174,512 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: varbit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
bit_not_hex = true;
sp = input_string;
}
slen = strlen(sp);
/* Determine bitlength from input string */
if (bit_not_hex)
bitlen = slen;
else
bitlen = slen * 4;
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen > atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("bit string too long for type bit varying(%d)",
atttypmod)));
len = VARBITTOTALLEN(bitlen);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = Min(bitlen, atttypmod);
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | varbit_in(PG_FUNCTION_ARGS)
{
char *input_string = PG_GETARG_CSTRING(0);
#ifdef NOT_USED
Oid typelem = PG_GETARG_OID(1);
#endif
int32 atttypmod = PG_GETARG_INT32(2);
VarBit *result; /* The resulting bit string */
char *sp; /* pointer into the character string */
bits8 *r; /* pointer into the result */
int len, /* Length of the whole data structure */
bitlen, /* Number of bits in the bit string */
slen; /* Length of the input string */
bool bit_not_hex; /* false = hex string true = bit string */
int bc;
bits8 x = 0;
/* Check that the first character is a b or an x */
if (input_string[0] == 'b' || input_string[0] == 'B')
{
bit_not_hex = true;
sp = input_string + 1;
}
else if (input_string[0] == 'x' || input_string[0] == 'X')
{
bit_not_hex = false;
sp = input_string + 1;
}
else
{
bit_not_hex = true;
sp = input_string;
}
/*
* Determine bitlength from input string. MaxAllocSize ensures a regular
* input is small enough, but we must check hex input.
*/
slen = strlen(sp);
if (bit_not_hex)
bitlen = slen;
else
{
if (slen > VARBITMAXLEN / 4)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("bit string length exceeds the maximum allowed (%d)",
VARBITMAXLEN)));
bitlen = slen * 4;
}
/*
* Sometimes atttypmod is not supplied. If it is supplied we need to make
* sure that the bitstring fits.
*/
if (atttypmod <= 0)
atttypmod = bitlen;
else if (bitlen > atttypmod)
ereport(ERROR,
(errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
errmsg("bit string too long for type bit varying(%d)",
atttypmod)));
len = VARBITTOTALLEN(bitlen);
/* set to 0 so that *r is always initialised and string is zero-padded */
result = (VarBit *) palloc0(len);
SET_VARSIZE(result, len);
VARBITLEN(result) = Min(bitlen, atttypmod);
r = VARBITS(result);
if (bit_not_hex)
{
/* Parse the bit representation of the string */
/* We know it fits, as bitlen was compared to atttypmod */
x = HIGHBIT;
for (; *sp; sp++)
{
if (*sp == '1')
*r |= x;
else if (*sp != '0')
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid binary digit",
*sp)));
x >>= 1;
if (x == 0)
{
x = HIGHBIT;
r++;
}
}
}
else
{
/* Parse the hex representation of the string */
for (bc = 0; *sp; sp++)
{
if (*sp >= '0' && *sp <= '9')
x = (bits8) (*sp - '0');
else if (*sp >= 'A' && *sp <= 'F')
x = (bits8) (*sp - 'A') + 10;
else if (*sp >= 'a' && *sp <= 'f')
x = (bits8) (*sp - 'a') + 10;
else
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("\"%c\" is not a valid hexadecimal digit",
*sp)));
if (bc)
{
*r++ |= x;
bc = 0;
}
else
{
*r = x << 4;
bc = 1;
}
}
}
PG_RETURN_VARBIT_P(result);
}
| 166,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ContextualSearchDelegate::DecodeSearchTermFromJsonResponse(
const std::string& response,
std::string* search_term,
std::string* display_text,
std::string* alternate_term,
std::string* mid,
std::string* prevent_preload,
int* mention_start,
int* mention_end,
std::string* lang,
std::string* thumbnail_url,
std::string* caption) {
bool contains_xssi_escape =
base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE);
const std::string& proper_json =
contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1)
: response;
JSONStringValueDeserializer deserializer(proper_json);
std::unique_ptr<base::Value> root =
deserializer.Deserialize(nullptr, nullptr);
const std::unique_ptr<base::DictionaryValue> dict =
base::DictionaryValue::From(std::move(root));
if (!dict)
return;
dict->GetString(kContextualSearchPreventPreload, prevent_preload);
dict->GetString(kContextualSearchResponseSearchTermParam, search_term);
dict->GetString(kContextualSearchResponseLanguageParam, lang);
if (!dict->GetString(kContextualSearchResponseDisplayTextParam,
display_text)) {
*display_text = *search_term;
}
dict->GetString(kContextualSearchResponseMidParam, mid);
if (!field_trial_->IsDecodeMentionsDisabled()) {
base::ListValue* mentions_list = nullptr;
dict->GetList(kContextualSearchMentions, &mentions_list);
if (mentions_list && mentions_list->GetSize() >= 2)
ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end);
}
std::string selected_text;
dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text);
if (selected_text != *search_term) {
*alternate_term = selected_text;
} else {
std::string resolved_term;
dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term);
if (resolved_term != *search_term) {
*alternate_term = resolved_term;
}
}
if (field_trial_->IsNowOnTapBarIntegrationEnabled()) {
dict->GetString(kContextualSearchCaption, caption);
dict->GetString(kContextualSearchThumbnail, thumbnail_url);
}
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | void ContextualSearchDelegate::DecodeSearchTermFromJsonResponse(
const std::string& response,
std::string* search_term,
std::string* display_text,
std::string* alternate_term,
std::string* mid,
std::string* prevent_preload,
int* mention_start,
int* mention_end,
std::string* lang,
std::string* thumbnail_url,
std::string* caption) {
bool contains_xssi_escape =
base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE);
const std::string& proper_json =
contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1)
: response;
JSONStringValueDeserializer deserializer(proper_json);
std::unique_ptr<base::Value> root =
deserializer.Deserialize(nullptr, nullptr);
const std::unique_ptr<base::DictionaryValue> dict =
base::DictionaryValue::From(std::move(root));
if (!dict)
return;
dict->GetString(kContextualSearchPreventPreload, prevent_preload);
dict->GetString(kContextualSearchResponseSearchTermParam, search_term);
dict->GetString(kContextualSearchResponseLanguageParam, lang);
if (!dict->GetString(kContextualSearchResponseDisplayTextParam,
display_text)) {
*display_text = *search_term;
}
dict->GetString(kContextualSearchResponseMidParam, mid);
if (!field_trial_->IsDecodeMentionsDisabled()) {
base::ListValue* mentions_list = nullptr;
dict->GetList(kContextualSearchMentions, &mentions_list);
if (mentions_list && mentions_list->GetSize() >= 2)
ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end);
}
std::string selected_text;
dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text);
if (selected_text != *search_term) {
*alternate_term = selected_text;
} else {
std::string resolved_term;
dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term);
if (resolved_term != *search_term) {
*alternate_term = resolved_term;
}
}
if (field_trial_->IsContextualCardsBarIntegrationEnabled()) {
// Get the basic Bar data for Contextual Cards integration directly
// from the root.
dict->GetString(kContextualSearchCaption, caption);
dict->GetString(kContextualSearchThumbnail, thumbnail_url);
}
}
| 171,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string MakeMediaAccessRequest(int index) {
const int render_process_id = 1;
const int render_frame_id = 1;
const int page_request_id = 1;
const url::Origin security_origin;
MediaStreamManager::MediaAccessRequestCallback callback =
base::BindOnce(&MediaStreamManagerTest::ResponseCallback,
base::Unretained(this), index);
StreamControls controls(true, true);
return media_stream_manager_->MakeMediaAccessRequest(
render_process_id, render_frame_id, page_request_id, controls,
security_origin, std::move(callback));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | std::string MakeMediaAccessRequest(int index) {
const int render_process_id = 1;
const int render_frame_id = 1;
const int requester_id = 1;
const int page_request_id = 1;
const url::Origin security_origin;
MediaStreamManager::MediaAccessRequestCallback callback =
base::BindOnce(&MediaStreamManagerTest::ResponseCallback,
base::Unretained(this), index);
StreamControls controls(true, true);
return media_stream_manager_->MakeMediaAccessRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
controls, security_origin, std::move(callback));
}
| 173,107 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct vm_area_struct *vma_to_resize(unsigned long addr,
unsigned long old_len, unsigned long new_len, unsigned long *p)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = find_vma(mm, addr);
if (!vma || vma->vm_start > addr)
goto Efault;
if (is_vm_hugetlb_page(vma))
goto Einval;
/* We can't remap across vm area boundaries */
if (old_len > vma->vm_end - addr)
goto Efault;
if (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP)) {
if (new_len > old_len)
goto Efault;
}
if (vma->vm_flags & VM_LOCKED) {
unsigned long locked, lock_limit;
locked = mm->locked_vm << PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
locked += new_len - old_len;
if (locked > lock_limit && !capable(CAP_IPC_LOCK))
goto Eagain;
}
if (!may_expand_vm(mm, (new_len - old_len) >> PAGE_SHIFT))
goto Enomem;
if (vma->vm_flags & VM_ACCOUNT) {
unsigned long charged = (new_len - old_len) >> PAGE_SHIFT;
if (security_vm_enough_memory(charged))
goto Efault;
*p = charged;
}
return vma;
Efault: /* very odd choice for most of the cases, but... */
return ERR_PTR(-EFAULT);
Einval:
return ERR_PTR(-EINVAL);
Enomem:
return ERR_PTR(-ENOMEM);
Eagain:
return ERR_PTR(-EAGAIN);
}
Commit Message: mm: avoid wrapping vm_pgoff in mremap()
The normal mmap paths all avoid creating a mapping where the pgoff
inside the mapping could wrap around due to overflow. However, an
expanding mremap() can take such a non-wrapping mapping and make it
bigger and cause a wrapping condition.
Noticed by Robert Swiecki when running a system call fuzzer, where it
caused a BUG_ON() due to terminally confusing the vma_prio_tree code. A
vma dumping patch by Hugh then pinpointed the crazy wrapped case.
Reported-and-tested-by: Robert Swiecki <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static struct vm_area_struct *vma_to_resize(unsigned long addr,
unsigned long old_len, unsigned long new_len, unsigned long *p)
{
struct mm_struct *mm = current->mm;
struct vm_area_struct *vma = find_vma(mm, addr);
if (!vma || vma->vm_start > addr)
goto Efault;
if (is_vm_hugetlb_page(vma))
goto Einval;
/* We can't remap across vm area boundaries */
if (old_len > vma->vm_end - addr)
goto Efault;
/* Need to be careful about a growing mapping */
if (new_len > old_len) {
unsigned long pgoff;
if (vma->vm_flags & (VM_DONTEXPAND | VM_PFNMAP))
goto Efault;
pgoff = (addr - vma->vm_start) >> PAGE_SHIFT;
pgoff += vma->vm_pgoff;
if (pgoff + (new_len >> PAGE_SHIFT) < pgoff)
goto Einval;
}
if (vma->vm_flags & VM_LOCKED) {
unsigned long locked, lock_limit;
locked = mm->locked_vm << PAGE_SHIFT;
lock_limit = rlimit(RLIMIT_MEMLOCK);
locked += new_len - old_len;
if (locked > lock_limit && !capable(CAP_IPC_LOCK))
goto Eagain;
}
if (!may_expand_vm(mm, (new_len - old_len) >> PAGE_SHIFT))
goto Enomem;
if (vma->vm_flags & VM_ACCOUNT) {
unsigned long charged = (new_len - old_len) >> PAGE_SHIFT;
if (security_vm_enough_memory(charged))
goto Efault;
*p = charged;
}
return vma;
Efault: /* very odd choice for most of the cases, but... */
return ERR_PTR(-EFAULT);
Einval:
return ERR_PTR(-EINVAL);
Enomem:
return ERR_PTR(-ENOMEM);
Eagain:
return ERR_PTR(-EAGAIN);
}
| 165,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: static int pvc_getname(struct socket *sock, struct sockaddr *sockaddr,
int *sockaddr_len, int peer)
{
struct sockaddr_atmpvc *addr;
struct atm_vcc *vcc = ATM_SD(sock);
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
*sockaddr_len = sizeof(struct sockaddr_atmpvc);
addr = (struct sockaddr_atmpvc *)sockaddr;
addr->sap_family = AF_ATMPVC;
addr->sap_addr.itf = vcc->dev->number;
addr->sap_addr.vpi = vcc->vpi;
addr->sap_addr.vci = vcc->vci;
return 0;
}
Commit Message: atm: fix info leak via getsockname()
The ATM code fails to initialize the two padding bytes of struct
sockaddr_atmpvc inserted for alignment. Add an explicit memset(0)
before filling the structure to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int pvc_getname(struct socket *sock, struct sockaddr *sockaddr,
int *sockaddr_len, int peer)
{
struct sockaddr_atmpvc *addr;
struct atm_vcc *vcc = ATM_SD(sock);
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
*sockaddr_len = sizeof(struct sockaddr_atmpvc);
addr = (struct sockaddr_atmpvc *)sockaddr;
memset(addr, 0, sizeof(*addr));
addr->sap_family = AF_ATMPVC;
addr->sap_addr.itf = vcc->dev->number;
addr->sap_addr.vpi = vcc->vpi;
addr->sap_addr.vci = vcc->vci;
return 0;
}
| 169,896 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PageSerializer::PageSerializer(Vector<SerializedResource>* resources, LinkLocalPathMap* urls, String directory)
: m_resources(resources)
, m_URLs(urls)
, m_directory(directory)
, m_blankFrameCounter(0)
{
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | PageSerializer::PageSerializer(Vector<SerializedResource>* resources, LinkLocalPathMap* urls, String directory)
PageSerializer::PageSerializer(Vector<SerializedResource>* resources)
: m_resources(resources)
, m_blankFrameCounter(0)
{
}
| 171,563 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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)
{
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
appendImages( &appended, imageList.begin(), imageList.end() );
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
}
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "0909f7ffa7c6ea410fb2ebfdbcb19d61b19c4bd271851ce3bd51662519dc2b58" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
Commit Message: Fix signature mismatch
CWE ID: CWE-369 | int main( int /*argc*/, char ** argv)
{
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
appendImages( &appended, imageList.begin(), imageList.end() );
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
}
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "f3590c183018757da798613a23505ab9600b35935988eee12f096cb6219f2bc3" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
| 170,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) {
gfx::Point location_in_bar(event->location());
ConvertPointToTarget(this, this->progress_bar_, &location_in_bar);
if (event->type() != ui::ET_GESTURE_TAP ||
!progress_bar_->GetLocalBounds().Contains(location_in_bar)) {
return;
}
HandleSeeking(location_in_bar);
event->SetHandled();
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | void MediaControlsProgressView::OnGestureEvent(ui::GestureEvent* event) {
if (event->type() != ui::ET_GESTURE_TAP || event->y() < kMinClickHeight ||
event->y() > kMaxClickHeight) {
return;
}
HandleSeeking(event->location());
event->SetHandled();
}
| 172,347 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 V8RecursionScope::didLeaveScriptContext()
{
Microtask::performCheckpoint();
V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks();
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254 | void V8RecursionScope::didLeaveScriptContext()
{
Microtask::performCheckpoint(m_isolate);
V8PerIsolateData::from(m_isolate)->runEndOfScopeTasks();
}
| 171,943 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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* H264SwDecMalloc(u32 size)
{
return malloc(size);
}
Commit Message: h264dec: check for overflows when calculating allocation size.
Bug: 27855419
Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd
CWE ID: CWE-119 | void* H264SwDecMalloc(u32 size)
void* H264SwDecMalloc(u32 size, u32 num)
{
if (size > UINT32_MAX / num) {
return NULL;
}
return malloc(size * num);
}
| 173,872 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
panel_(panel) {
const Extension* extension = panel_->GetExtension();
DCHECK(extension);
AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE));
AddItem(COMMAND_UNINSTALL,
l10n_util::GetStringFUTF16(IDS_EXTENSIONS_UNINSTALL,
l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME)));
AddSeparator();
AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS));
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | PanelSettingsMenuModel::PanelSettingsMenuModel(Panel* panel)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
panel_(panel) {
const Extension* extension = panel_->GetExtension();
DCHECK(extension);
AddItem(COMMAND_NAME, UTF8ToUTF16(extension->name()));
AddSeparator();
AddItem(COMMAND_CONFIGURE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS));
AddItem(COMMAND_DISABLE, l10n_util::GetStringUTF16(IDS_EXTENSIONS_DISABLE));
AddItem(COMMAND_UNINSTALL,
l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL));
AddSeparator();
AddItem(COMMAND_MANAGE, l10n_util::GetStringUTF16(IDS_MANAGE_EXTENSIONS));
}
| 170,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: static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
Commit Message: udf: Fortify loading of sparing table
Add sanity checks when loading sparing table from disk to avoid accessing
unallocated memory or writing to it.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-119 | static int udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
if (udf_load_sparable_map(sb, map,
(struct sparablePartitionMap *)gpm) < 0)
goto out_bh;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
| 169,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 P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
quic::QuicStream::OnStreamReset(frame);
delegate_->OnRemoteReset();
}
Commit Message: P2PQuicStream write functionality.
This adds the P2PQuicStream::WriteData function and adds tests. It also
adds the concept of a write buffered amount, enforcing this at the
P2PQuicStreamImpl.
Bug: 874296
Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131
Reviewed-on: https://chromium-review.googlesource.com/c/1315534
Commit-Queue: Seth Hampson <[email protected]>
Reviewed-by: Henrik Boström <[email protected]>
Cr-Commit-Position: refs/heads/master@{#605766}
CWE ID: CWE-284 | void P2PQuicStreamImpl::OnStreamReset(const quic::QuicRstStreamFrame& frame) {
quic::QuicStream::OnStreamReset(frame);
delegate_->OnRemoteReset();
}
| 172,262 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 on_header_cb(nghttp2_session *ngh2, const nghttp2_frame *frame,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
void *userp)
{
h2_session *session = (h2_session *)userp;
h2_stream * stream;
apr_status_t status;
(void)flags;
stream = get_stream(session, frame->hd.stream_id);
if (!stream) {
ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, session->c,
APLOGNO(02920)
"h2_session: stream(%ld-%d): on_header unknown stream",
session->id, (int)frame->hd.stream_id);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
status = h2_stream_add_header(stream, (const char *)name, namelen,
(const char *)value, valuelen);
if (status != APR_SUCCESS && !h2_stream_is_ready(stream)) {
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
return 0;
}
Commit Message: SECURITY: CVE-2016-8740
mod_http2: properly crafted, endless HTTP/2 CONTINUATION frames could be used to exhaust all server's memory.
Reported by: Naveen Tiwari <[email protected]> and CDF/SEFCOM at Arizona State University
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1772576 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20 | static int on_header_cb(nghttp2_session *ngh2, const nghttp2_frame *frame,
const uint8_t *name, size_t namelen,
const uint8_t *value, size_t valuelen,
uint8_t flags,
void *userp)
{
h2_session *session = (h2_session *)userp;
h2_stream * stream;
apr_status_t status;
(void)flags;
stream = get_stream(session, frame->hd.stream_id);
if (!stream) {
ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, session->c,
APLOGNO(02920)
"h2_session: stream(%ld-%d): on_header unknown stream",
session->id, (int)frame->hd.stream_id);
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
status = h2_stream_add_header(stream, (const char *)name, namelen,
(const char *)value, valuelen);
if (status == APR_ECONNRESET) {
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, status, session->c,
"h2-stream(%ld-%d): on_header, reset stream",
session->id, stream->id);
nghttp2_submit_rst_stream(ngh2, NGHTTP2_FLAG_NONE, stream->id,
NGHTTP2_INTERNAL_ERROR);
}
else if (status != APR_SUCCESS && !h2_stream_is_ready(stream)) {
return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE;
}
return 0;
}
| 166,903 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
Commit Message:
CWE ID: CWE-399 | parse_encoding( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
PSAux_Service psaux = (PSAux_Service)face->psaux;
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
{
FT_ERROR(( "parse_encoding: out of bounds\n" ));
parser->root.error = FT_THROW( Invalid_File_Format );
return;
}
/* if we have a number or `[', the encoding is an array, */
/* and we must load it now */
if ( ft_isdigit( *cur ) || *cur == '[' )
{
T1_Encoding encode = &face->type1.encoding;
FT_Int count, n;
PS_Table char_table = &loader->encoding_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
FT_Bool only_immediates = 0;
/* read the number of entries in the encoding; should be 256 */
if ( *cur == '[' )
{
count = 256;
only_immediates = 1;
parser->root.cursor++;
}
else
count = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
if ( parser->root.cursor >= limit )
return;
/* we use a T1_Table to store our charnames */
loader->num_chars = encode->num_chars = count;
if ( FT_NEW_ARRAY( encode->char_index, count ) ||
FT_NEW_ARRAY( encode->char_name, count ) ||
FT_SET_ERROR( psaux->ps_table_funcs->init(
char_table, count, memory ) ) )
{
parser->root.error = error;
return;
}
/* We need to `zero' out encoding_table.elements */
for ( n = 0; n < count; n++ )
{
char* notdef = (char *)".notdef";
T1_Add_Table( char_table, n, notdef, 8 );
}
/* Now we need to read records of the form */
/* */
/* ... charcode /charname ... */
/* */
/* for each entry in our table. */
/* */
/* We simply look for a number followed by an immediate */
/* name. Note that this ignores correctly the sequence */
/* that is often seen in type1 fonts: */
/* */
/* 0 1 255 { 1 index exch /.notdef put } for dup */
/* */
/* used to clean the encoding array before anything else. */
/* */
/* Alternatively, if the array is directly given as */
/* */
/* /Encoding [ ... ] */
/* */
/* we only read immediates. */
n = 0;
T1_Skip_Spaces( parser );
while ( parser->root.cursor < limit )
{
cur = parser->root.cursor;
/* we stop when we encounter a `def' or `]' */
if ( *cur == 'd' && cur + 3 < limit )
{
if ( cur[1] == 'e' &&
cur[2] == 'f' &&
IS_PS_DELIM( cur[3] ) )
{
FT_TRACE6(( "encoding end\n" ));
cur += 3;
break;
}
}
if ( *cur == ']' )
{
FT_TRACE6(( "encoding end\n" ));
cur++;
break;
}
/* check whether we've found an entry */
if ( ft_isdigit( *cur ) || only_immediates )
{
FT_Int charcode;
if ( only_immediates )
charcode = n;
else
{
charcode = (FT_Int)T1_ToInt( parser );
T1_Skip_Spaces( parser );
/* protect against invalid charcode */
if ( cur == parser->root.cursor )
{
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
cur = parser->root.cursor;
parser->root.cursor = cur;
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
return;
if ( parser->root.error )
return;
len = parser->root.cursor - cur;
parser->root.error = T1_Add_Table( char_table, charcode,
cur, len + 1 );
if ( parser->root.error )
return;
char_table->elements[charcode][len] = '\0';
n++;
}
else if ( only_immediates )
{
/* Since the current position is not updated for */
/* immediates-only mode we would get an infinite loop if */
/* we don't do anything here. */
/* */
/* This encoding array is not valid according to the type1 */
/* specification (it might be an encoding for a CID type1 */
/* font, however), so we conclude that this font is NOT a */
/* type1 font. */
parser->root.error = FT_THROW( Unknown_File_Format );
return;
}
}
else
{
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
}
T1_Skip_Spaces( parser );
}
face->type1.encoding_type = T1_ENCODING_TYPE_ARRAY;
parser->root.cursor = cur;
}
| 164,837 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: test_function (char * (*my_asnprintf) (char *, size_t *, const char *, ...))
{
char buf[8];
int size;
for (size = 0; size <= 8; size++)
{
size_t length = size;
char *result = my_asnprintf (NULL, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
free (result);
}
for (size = 0; size <= 8; size++)
{
size_t length;
char *result;
memcpy (buf, "DEADBEEF", 8);
length = size;
result = my_asnprintf (buf, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
if (size < 6)
ASSERT (result != buf);
ASSERT (memcmp (buf + size, &"DEADBEEF"[size], 8 - size) == 0);
if (result != buf)
free (result);
}
}
Commit Message: vasnprintf: Fix heap memory overrun bug.
Reported by Ben Pfaff <[email protected]> in
<https://lists.gnu.org/archive/html/bug-gnulib/2018-09/msg00107.html>.
* lib/vasnprintf.c (convert_to_decimal): Allocate one more byte of
memory.
* tests/test-vasnprintf.c (test_function): Add another test.
CWE ID: CWE-119 | test_function (char * (*my_asnprintf) (char *, size_t *, const char *, ...))
{
char buf[8];
int size;
for (size = 0; size <= 8; size++)
{
size_t length = size;
char *result = my_asnprintf (NULL, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
free (result);
}
for (size = 0; size <= 8; size++)
{
size_t length;
char *result;
memcpy (buf, "DEADBEEF", 8);
length = size;
result = my_asnprintf (buf, &length, "%d", 12345);
ASSERT (result != NULL);
ASSERT (strcmp (result, "12345") == 0);
ASSERT (length == 5);
if (size < 5 + 1)
ASSERT (result != buf);
ASSERT (memcmp (buf + size, &"DEADBEEF"[size], 8 - size) == 0);
if (result != buf)
free (result);
}
/* Note: This test assumes IEEE 754 representation of 'double' floats. */
for (size = 0; size <= 8; size++)
{
size_t length;
char *result;
memcpy (buf, "DEADBEEF", 8);
length = size;
result = my_asnprintf (buf, &length, "%2.0f", 1.6314159265358979e+125);
ASSERT (result != NULL);
ASSERT (strcmp (result, "163141592653589790215729350939528493057529598899734151772468186268423257777068536614838678161083520756952076273094236944990208") == 0);
ASSERT (length == 126);
if (size < 126 + 1)
ASSERT (result != buf);
ASSERT (memcmp (buf + size, &"DEADBEEF"[size], 8 - size) == 0);
if (result != buf)
free (result);
}
}
| 169,014 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hb_buffer_create (unsigned int pre_alloc_size)
{
hb_buffer_t *buffer;
if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer))
return &_hb_buffer_nil;
if (pre_alloc_size)
hb_buffer_ensure(buffer, pre_alloc_size);
buffer->unicode = &_hb_unicode_funcs_nil;
return buffer;
}
Commit Message:
CWE ID: | hb_buffer_create (unsigned int pre_alloc_size)
{
hb_buffer_t *buffer;
if (!HB_OBJECT_DO_CREATE (hb_buffer_t, buffer))
return &_hb_buffer_nil;
if (pre_alloc_size)
hb_buffer_ensure (buffer, pre_alloc_size);
buffer->unicode = &_hb_unicode_funcs_nil;
return buffer;
}
| 164,773 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CreateSession::ExecutePost(Response* const response) {
DictionaryValue *capabilities = NULL;
if (!GetDictionaryParameter("desiredCapabilities", &capabilities)) {
response->SetError(new Error(
kBadRequest, "Missing or invalid 'desiredCapabilities'"));
return;
}
CommandLine command_line_options(CommandLine::NO_PROGRAM);
ListValue* switches = NULL;
const char* kCustomSwitchesKey = "chrome.switches";
if (capabilities->GetListWithoutPathExpansion(kCustomSwitchesKey,
&switches)) {
for (size_t i = 0; i < switches->GetSize(); ++i) {
std::string switch_string;
if (!switches->GetString(i, &switch_string)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
size_t separator_index = switch_string.find("=");
if (separator_index != std::string::npos) {
CommandLine::StringType switch_string_native;
if (!switches->GetString(i, &switch_string_native)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
command_line_options.AppendSwitchNative(
switch_string.substr(0, separator_index),
switch_string_native.substr(separator_index + 1));
} else {
command_line_options.AppendSwitch(switch_string);
}
}
} else if (capabilities->HasKey(kCustomSwitchesKey)) {
response->SetError(new Error(
kBadRequest, "Custom switches must be a list"));
return;
}
FilePath browser_exe;
FilePath::StringType path;
if (capabilities->GetStringWithoutPathExpansion("chrome.binary", &path))
browser_exe = FilePath(path);
Session* session = new Session();
Error* error = session->Init(browser_exe, command_line_options);
if (error) {
response->SetError(error);
return;
}
bool native_events_required = false;
Value* native_events_value = NULL;
if (capabilities->GetWithoutPathExpansion(
"chrome.nativeEvents", &native_events_value)) {
if (native_events_value->GetAsBoolean(&native_events_required)) {
session->set_use_native_events(native_events_required);
}
}
bool screenshot_on_error = false;
if (capabilities->GetBoolean(
"takeScreenshotOnError", &screenshot_on_error)) {
session->set_screenshot_on_error(screenshot_on_error);
}
VLOG(1) << "Created session " << session->id();
std::ostringstream stream;
SessionManager* session_manager = SessionManager::GetInstance();
stream << "http://" << session_manager->GetAddress() << "/session/"
<< session->id();
response->SetStatus(kSeeOther);
response->SetValue(Value::CreateStringValue(stream.str()));
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void CreateSession::ExecutePost(Response* const response) {
DictionaryValue *capabilities = NULL;
if (!GetDictionaryParameter("desiredCapabilities", &capabilities)) {
response->SetError(new Error(
kBadRequest, "Missing or invalid 'desiredCapabilities'"));
return;
}
CommandLine command_line_options(CommandLine::NO_PROGRAM);
ListValue* switches = NULL;
const char* kCustomSwitchesKey = "chrome.switches";
if (capabilities->GetListWithoutPathExpansion(kCustomSwitchesKey,
&switches)) {
for (size_t i = 0; i < switches->GetSize(); ++i) {
std::string switch_string;
if (!switches->GetString(i, &switch_string)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
size_t separator_index = switch_string.find("=");
if (separator_index != std::string::npos) {
CommandLine::StringType switch_string_native;
if (!switches->GetString(i, &switch_string_native)) {
response->SetError(new Error(
kBadRequest, "Custom switch is not a string"));
return;
}
command_line_options.AppendSwitchNative(
switch_string.substr(0, separator_index),
switch_string_native.substr(separator_index + 1));
} else {
command_line_options.AppendSwitch(switch_string);
}
}
} else if (capabilities->HasKey(kCustomSwitchesKey)) {
response->SetError(new Error(
kBadRequest, "Custom switches must be a list"));
return;
}
Value* verbose_value;
if (capabilities->GetWithoutPathExpansion("chrome.verbose", &verbose_value)) {
bool verbose;
if (verbose_value->GetAsBoolean(&verbose) && verbose) {
// Since logging is shared among sessions, if any session requests verbose
// logging, verbose logging will be enabled for all sessions. It is not
// possible to turn it off.
logging::SetMinLogLevel(logging::LOG_INFO);
} else {
response->SetError(new Error(
kBadRequest, "verbose must be a boolean true or false"));
return;
}
}
FilePath browser_exe;
FilePath::StringType path;
if (capabilities->GetStringWithoutPathExpansion("chrome.binary", &path))
browser_exe = FilePath(path);
Session* session = new Session();
Error* error = session->Init(browser_exe, command_line_options);
if (error) {
response->SetError(error);
return;
}
bool native_events_required = false;
Value* native_events_value = NULL;
if (capabilities->GetWithoutPathExpansion(
"chrome.nativeEvents", &native_events_value)) {
if (native_events_value->GetAsBoolean(&native_events_required)) {
session->set_use_native_events(native_events_required);
}
}
bool screenshot_on_error = false;
if (capabilities->GetBoolean(
"takeScreenshotOnError", &screenshot_on_error)) {
session->set_screenshot_on_error(screenshot_on_error);
}
LOG(INFO) << "Created session " << session->id();
std::ostringstream stream;
SessionManager* session_manager = SessionManager::GetInstance();
stream << "http://" << session_manager->GetAddress() << "/session/"
<< session->id();
response->SetStatus(kSeeOther);
response->SetValue(Value::CreateStringValue(stream.str()));
}
| 170,453 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GpuProcessHost::OnProcessCrashed(int exit_code) {
int process_crash_exit_code = exit_code;
base::debug::Alias(&process_crash_exit_code);
if (activity_flags_.IsFlagSet(
gpu::ActivityFlagsBase::FLAG_LOADING_PROGRAM_BINARY)) {
for (auto cache_key : client_id_to_shader_cache_) {
GetShaderCacheFactorySingleton()->ClearByClientId(
cache_key.first, base::Time(), base::Time::Max(), base::Bind([] {}));
}
}
SendOutstandingReplies(EstablishChannelStatus::GPU_HOST_INVALID);
RecordProcessCrash();
ChildProcessTerminationInfo info =
process_->GetTerminationInfo(true /* known_dead */);
GpuDataManagerImpl::GetInstance()->ProcessCrashed(info.status);
}
Commit Message: Fix GPU process fallback logic.
1. In GpuProcessHost::OnProcessCrashed() record the process crash first.
This means the GPU mode fallback will happen before a new GPU process
is started.
2. Don't call FallBackToNextGpuMode() if GPU process initialization
fails for an unsandboxed GPU process. The unsandboxed GPU is only
used for collect information and it's failure doesn't indicate a need
to change GPU modes.
Bug: 869419
Change-Id: I8bd0a03268f0ea8809f3df8458d4e6a92db9391f
Reviewed-on: https://chromium-review.googlesource.com/1157164
Reviewed-by: Zhenyao Mo <[email protected]>
Commit-Queue: kylechar <[email protected]>
Cr-Commit-Position: refs/heads/master@{#579625}
CWE ID: | void GpuProcessHost::OnProcessCrashed(int exit_code) {
int process_crash_exit_code = exit_code;
base::debug::Alias(&process_crash_exit_code);
// Record crash before doing anything that could start a new GPU process.
RecordProcessCrash();
if (activity_flags_.IsFlagSet(
gpu::ActivityFlagsBase::FLAG_LOADING_PROGRAM_BINARY)) {
for (auto cache_key : client_id_to_shader_cache_) {
GetShaderCacheFactorySingleton()->ClearByClientId(
cache_key.first, base::Time(), base::Time::Max(), base::Bind([] {}));
}
}
SendOutstandingReplies(EstablishChannelStatus::GPU_HOST_INVALID);
ChildProcessTerminationInfo info =
process_->GetTerminationInfo(true /* known_dead */);
GpuDataManagerImpl::GetInstance()->ProcessCrashed(info.status);
}
| 172,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: cib_remote_perform_op(cib_t * cib, const char *op, const char *host, const char *section,
xmlNode * data, xmlNode ** output_data, int call_options, const char *name)
{
int rc = pcmk_ok;
xmlNode *op_msg = NULL;
xmlNode *op_reply = NULL;
cib_remote_opaque_t *private = cib->variant_opaque;
if (sync_timer == NULL) {
sync_timer = calloc(1, sizeof(struct timer_rec_s));
}
if (cib->state == cib_disconnected) {
return -ENOTCONN;
}
if (output_data != NULL) {
*output_data = NULL;
}
if (op == NULL) {
crm_err("No operation specified");
return -EINVAL;
}
cib->call_id++;
/* prevent call_id from being negative (or zero) and conflicting
* with the cib_errors enum
* use 2 because we use it as (cib->call_id - 1) below
*/
if (cib->call_id < 1) {
cib->call_id = 1;
}
op_msg =
cib_create_op(cib->call_id, private->callback.token, op, host, section, data, call_options,
NULL);
if (op_msg == NULL) {
return -EPROTO;
}
crm_trace("Sending %s message to CIB service", op);
crm_send_remote_msg(private->command.session, op_msg, private->command.encrypted);
free_xml(op_msg);
if ((call_options & cib_discard_reply)) {
crm_trace("Discarding reply");
return pcmk_ok;
} else if (!(call_options & cib_sync_call)) {
return cib->call_id;
}
crm_trace("Waiting for a syncronous reply");
if (cib->call_timeout > 0) {
/* We need this, even with msgfromIPC_timeout(), because we might
* get other/older replies that don't match the active request
*/
timer_expired = FALSE;
sync_timer->call_id = cib->call_id;
sync_timer->timeout = cib->call_timeout * 1000;
sync_timer->ref = g_timeout_add(sync_timer->timeout, cib_timeout_handler, sync_timer);
}
while (timer_expired == FALSE) {
int reply_id = -1;
int msg_id = cib->call_id;
op_reply = crm_recv_remote_msg(private->command.session, private->command.encrypted);
if (op_reply == NULL) {
break;
}
crm_element_value_int(op_reply, F_CIB_CALLID, &reply_id);
CRM_CHECK(reply_id > 0, free_xml(op_reply);
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref); sync_timer->ref = 0;}
return -ENOMSG) ;
if (reply_id == msg_id) {
break;
} else if (reply_id < msg_id) {
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else if ((reply_id - 10000) > msg_id) {
/* wrap-around case */
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else {
crm_err("Received a __future__ reply:" " %d (wanted %d)", reply_id, msg_id);
}
free_xml(op_reply);
op_reply = NULL;
}
if (sync_timer->ref > 0) {
g_source_remove(sync_timer->ref);
sync_timer->ref = 0;
}
if (timer_expired) {
return -ETIME;
}
/* if(IPC_ISRCONN(native->command_channel) == FALSE) { */
/* crm_err("CIB disconnected: %d", */
/* native->command_channel->ch_status); */
/* cib->state = cib_disconnected; */
/* } */
if (op_reply == NULL) {
crm_err("No reply message - empty");
return -ENOMSG;
}
crm_trace("Syncronous reply received");
/* Start processing the reply... */
if (crm_element_value_int(op_reply, F_CIB_RC, &rc) != 0) {
rc = -EPROTO;
}
if (rc == -pcmk_err_diff_resync) {
/* This is an internal value that clients do not and should not care about */
rc = pcmk_ok;
}
if (rc == pcmk_ok || rc == -EPERM) {
crm_log_xml_debug(op_reply, "passed");
} else {
/* } else if(rc == -ETIME) { */
crm_err("Call failed: %s", pcmk_strerror(rc));
crm_log_xml_warn(op_reply, "failed");
}
if (output_data == NULL) {
/* do nothing more */
} else if (!(call_options & cib_discard_reply)) {
xmlNode *tmp = get_message_xml(op_reply, F_CIB_CALLDATA);
if (tmp == NULL) {
crm_trace("No output in reply to \"%s\" command %d", op, cib->call_id - 1);
} else {
*output_data = copy_xml(tmp);
}
}
free_xml(op_reply);
return rc;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_remote_perform_op(cib_t * cib, const char *op, const char *host, const char *section,
xmlNode * data, xmlNode ** output_data, int call_options, const char *name)
{
int rc = pcmk_ok;
int disconnected = 0;
int remaining_time = 0;
time_t start_time;
xmlNode *op_msg = NULL;
xmlNode *op_reply = NULL;
cib_remote_opaque_t *private = cib->variant_opaque;
if (cib->state == cib_disconnected) {
return -ENOTCONN;
}
if (output_data != NULL) {
*output_data = NULL;
}
if (op == NULL) {
crm_err("No operation specified");
return -EINVAL;
}
cib->call_id++;
/* prevent call_id from being negative (or zero) and conflicting
* with the cib_errors enum
* use 2 because we use it as (cib->call_id - 1) below
*/
if (cib->call_id < 1) {
cib->call_id = 1;
}
op_msg =
cib_create_op(cib->call_id, private->callback.token, op, host, section, data, call_options,
NULL);
if (op_msg == NULL) {
return -EPROTO;
}
crm_trace("Sending %s message to CIB service", op);
if (!(call_options & cib_sync_call)) {
crm_send_remote_msg(private->callback.session, op_msg, private->command.encrypted);
} else {
crm_send_remote_msg(private->command.session, op_msg, private->command.encrypted);
}
free_xml(op_msg);
if ((call_options & cib_discard_reply)) {
crm_trace("Discarding reply");
return pcmk_ok;
} else if (!(call_options & cib_sync_call)) {
return cib->call_id;
}
crm_trace("Waiting for a syncronous reply");
start_time = time(NULL);
remaining_time = cib->call_timeout ? cib->call_timeout : 60;
while (remaining_time > 0 && !disconnected) {
int reply_id = -1;
int msg_id = cib->call_id;
crm_recv_remote_msg(private->command.session, &private->command.recv_buf, private->command.encrypted, remaining_time * 1000, &disconnected);
op_reply = crm_parse_remote_buffer(&private->command.recv_buf);
if (!op_reply) {
break;
}
crm_element_value_int(op_reply, F_CIB_CALLID, &reply_id);
if (reply_id == msg_id) {
break;
} else if (reply_id < msg_id) {
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else if ((reply_id - 10000) > msg_id) {
/* wrap-around case */
crm_debug("Received old reply: %d (wanted %d)", reply_id, msg_id);
crm_log_xml_trace(op_reply, "Old reply");
} else {
crm_err("Received a __future__ reply:" " %d (wanted %d)", reply_id, msg_id);
}
free_xml(op_reply);
op_reply = NULL;
/* wasn't the right reply, try and read some more */
remaining_time = time(NULL) - start_time;
}
/* if(IPC_ISRCONN(native->command_channel) == FALSE) { */
/* crm_err("CIB disconnected: %d", */
/* native->command_channel->ch_status); */
/* cib->state = cib_disconnected; */
/* } */
if (disconnected) {
crm_err("Disconnected while waiting for reply.");
return -ENOTCONN;
} else if (op_reply == NULL) {
crm_err("No reply message - empty");
return -ENOMSG;
}
crm_trace("Syncronous reply received");
/* Start processing the reply... */
if (crm_element_value_int(op_reply, F_CIB_RC, &rc) != 0) {
rc = -EPROTO;
}
if (rc == -pcmk_err_diff_resync) {
/* This is an internal value that clients do not and should not care about */
rc = pcmk_ok;
}
if (rc == pcmk_ok || rc == -EPERM) {
crm_log_xml_debug(op_reply, "passed");
} else {
/* } else if(rc == -ETIME) { */
crm_err("Call failed: %s", pcmk_strerror(rc));
crm_log_xml_warn(op_reply, "failed");
}
if (output_data == NULL) {
/* do nothing more */
} else if (!(call_options & cib_discard_reply)) {
xmlNode *tmp = get_message_xml(op_reply, F_CIB_CALLDATA);
if (tmp == NULL) {
crm_trace("No output in reply to \"%s\" command %d", op, cib->call_id - 1);
} else {
*output_data = copy_xml(tmp);
}
}
free_xml(op_reply);
return rc;
}
| 166,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: bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
const content::NavigationEntry* entry =
source->GetController().GetActiveEntry();
if (entry) {
const GURL& url = entry->GetURL();
const GURL& virtual_url = entry->GetVirtualURL();
if ((url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUINewTabHost) ||
(virtual_url.SchemeIs(content::kChromeUIScheme) &&
virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
return true;
}
}
return search::NavEntryIsInstantNTP(source, entry);
}
Commit Message: Don't focus the location bar for NTP navigations in non-selected tabs.
BUG=677716
TEST=See bug for repro steps.
Review-Url: https://codereview.chromium.org/2624373002
Cr-Commit-Position: refs/heads/master@{#443338}
CWE ID: | bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
// Navigations in background tabs shouldn't change the focus state of the
// omnibox, since it's associated with the foreground tab.
if (source != tab_strip_model_->GetActiveWebContents())
return false;
const content::NavigationEntry* entry =
source->GetController().GetActiveEntry();
if (entry) {
const GURL& url = entry->GetURL();
const GURL& virtual_url = entry->GetVirtualURL();
if ((url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUINewTabHost) ||
(virtual_url.SchemeIs(content::kChromeUIScheme) &&
virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
return true;
}
}
return search::NavEntryIsInstantNTP(source, entry);
}
| 172,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
if (inet->opt != NULL && inet->opt->srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet->opt->faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt))
return PTR_ERR(rt);
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet->opt == NULL || !inet->opt->srr)
daddr = rt->rt_dst;
if (inet->inet_saddr == 0)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet->opt != NULL)
inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
inet->inet_dport);
inet->inet_id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
goto out;
}
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 | int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
struct ip_options_rcu *inet_opt;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
inet_opt = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet_opt != NULL && inet_opt->opt.srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet_opt->opt.faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt))
return PTR_ERR(rt);
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet_opt == NULL || !inet_opt->opt.srr)
daddr = rt->rt_dst;
if (inet->inet_saddr == 0)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet_opt)
inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
inet->inet_dport);
inet->inet_id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
goto out;
}
| 165,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
Commit Message: Resolve a merge issue between lmp and lmp-mr1+
Change-Id: I336cb003fb7f50fd7d95c30ca47e45530a7ad503
(cherry picked from commit 33f6da1092834f1e4be199cfa3b6310d66b521c0)
(cherry picked from commit bb3a0338b58fafb01ac5b34efc450b80747e71e4)
CWE ID: CWE-119 | status_t NuPlayer::GenericSource::setBuffers(
bool audio, Vector<MediaBuffer *> &buffers) {
if (mIsSecure && !audio && mVideoTrack.mSource != NULL) {
return mVideoTrack.mSource->setBuffers(buffers);
}
return INVALID_OPERATION;
}
| 174,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service) {
file_info_.is_directory = true;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectory::GDataDirectory(GDataDirectoryService* directory_service)
: GDataEntry(directory_service) {
file_info_.is_directory = true;
}
| 171,489 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheDatabase::InsertCache(const CacheRecord* record) {
if (!LazyOpen(kCreateIfNeeded))
return false;
static const char kSql[] =
"INSERT INTO Caches (cache_id, group_id, online_wildcard,"
" update_time, cache_size)"
" VALUES(?, ?, ?, ?, ?)";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, record->cache_id);
statement.BindInt64(1, record->group_id);
statement.BindBool(2, record->online_wildcard);
statement.BindInt64(3, record->update_time.ToInternalValue());
statement.BindInt64(4, record->cache_size);
return statement.Run();
}
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 | bool AppCacheDatabase::InsertCache(const CacheRecord* record) {
if (!LazyOpen(kCreateIfNeeded))
return false;
static const char kSql[] =
"INSERT INTO Caches (cache_id, group_id, online_wildcard,"
" update_time, cache_size, padding_size)"
" VALUES(?, ?, ?, ?, ?, ?)";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, record->cache_id);
statement.BindInt64(1, record->group_id);
statement.BindBool(2, record->online_wildcard);
statement.BindInt64(3, record->update_time.ToInternalValue());
DCHECK_GE(record->cache_size, 0);
statement.BindInt64(4, record->cache_size);
DCHECK_GE(record->padding_size, 0);
statement.BindInt64(5, record->padding_size);
return statement.Run();
}
| 172,979 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AMediaCodecCryptoInfo *AMediaCodecCryptoInfo_new(
int numsubsamples,
uint8_t key[16],
uint8_t iv[16],
cryptoinfo_mode_t mode,
size_t *clearbytes,
size_t *encryptedbytes) {
size_t cryptosize = sizeof(AMediaCodecCryptoInfo) + sizeof(size_t) * numsubsamples * 2;
AMediaCodecCryptoInfo *ret = (AMediaCodecCryptoInfo*) malloc(cryptosize);
if (!ret) {
ALOGE("couldn't allocate %zu bytes", cryptosize);
return NULL;
}
ret->numsubsamples = numsubsamples;
memcpy(ret->key, key, 16);
memcpy(ret->iv, iv, 16);
ret->mode = mode;
ret->pattern.encryptBlocks = 0;
ret->pattern.skipBlocks = 0;
ret->clearbytes = (size_t*) (ret + 1); // point immediately after the struct
ret->encryptedbytes = ret->clearbytes + numsubsamples; // point after the clear sizes
memcpy(ret->clearbytes, clearbytes, numsubsamples * sizeof(size_t));
memcpy(ret->encryptedbytes, encryptedbytes, numsubsamples * sizeof(size_t));
return ret;
}
Commit Message: Check for overflow of crypto size
Bug: 111603051
Test: CTS
Change-Id: Ib5b1802b9b35769a25c16e2b977308cf7a810606
(cherry picked from commit d1fd02761236b35a336434367131f71bef7405c9)
CWE ID: CWE-190 | AMediaCodecCryptoInfo *AMediaCodecCryptoInfo_new(
int numsubsamples,
uint8_t key[16],
uint8_t iv[16],
cryptoinfo_mode_t mode,
size_t *clearbytes,
size_t *encryptedbytes) {
size_t cryptosize;
// = sizeof(AMediaCodecCryptoInfo) + sizeof(size_t) * numsubsamples * 2;
if (__builtin_mul_overflow(sizeof(size_t) * 2, numsubsamples, &cryptosize) ||
__builtin_add_overflow(cryptosize, sizeof(AMediaCodecCryptoInfo), &cryptosize)) {
ALOGE("crypto size overflow");
return NULL;
}
AMediaCodecCryptoInfo *ret = (AMediaCodecCryptoInfo*) malloc(cryptosize);
if (!ret) {
ALOGE("couldn't allocate %zu bytes", cryptosize);
return NULL;
}
ret->numsubsamples = numsubsamples;
memcpy(ret->key, key, 16);
memcpy(ret->iv, iv, 16);
ret->mode = mode;
ret->pattern.encryptBlocks = 0;
ret->pattern.skipBlocks = 0;
ret->clearbytes = (size_t*) (ret + 1); // point immediately after the struct
ret->encryptedbytes = ret->clearbytes + numsubsamples; // point after the clear sizes
memcpy(ret->clearbytes, clearbytes, numsubsamples * sizeof(size_t));
memcpy(ret->encryptedbytes, encryptedbytes, numsubsamples * sizeof(size_t));
return ret;
}
| 174,093 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer,
raptor_option option, int value)
{
if(value < 0 ||
!raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER))
return 1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
if(value)
turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT;
else
turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT;
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
turtle_writer->indent = value;
break;
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
break;
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
return -1;
break;
}
return 0;
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200 | raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer,
raptor_option option, int value)
{
if(value < 0 ||
!raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER))
return 1;
switch(option) {
case RAPTOR_OPTION_WRITER_AUTO_INDENT:
if(value)
turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT;
else
turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT;
break;
case RAPTOR_OPTION_WRITER_INDENT_WIDTH:
turtle_writer->indent = value;
break;
case RAPTOR_OPTION_WRITER_AUTO_EMPTY:
case RAPTOR_OPTION_WRITER_XML_VERSION:
case RAPTOR_OPTION_WRITER_XML_DECLARATION:
break;
/* parser options */
case RAPTOR_OPTION_SCANNING:
case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES:
case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES:
case RAPTOR_OPTION_ALLOW_BAGID:
case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST:
case RAPTOR_OPTION_NORMALIZE_LANGUAGE:
case RAPTOR_OPTION_NON_NFC_FATAL:
case RAPTOR_OPTION_WARN_OTHER_PARSETYPES:
case RAPTOR_OPTION_CHECK_RDF_ID:
case RAPTOR_OPTION_HTML_TAG_SOUP:
case RAPTOR_OPTION_MICROFORMATS:
case RAPTOR_OPTION_HTML_LINK:
case RAPTOR_OPTION_WWW_TIMEOUT:
case RAPTOR_OPTION_STRICT:
/* Shared */
case RAPTOR_OPTION_NO_NET:
case RAPTOR_OPTION_NO_FILE:
case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES:
/* XML writer options */
case RAPTOR_OPTION_RELATIVE_URIS:
/* DOT serializer options */
case RAPTOR_OPTION_RESOURCE_BORDER:
case RAPTOR_OPTION_LITERAL_BORDER:
case RAPTOR_OPTION_BNODE_BORDER:
case RAPTOR_OPTION_RESOURCE_FILL:
case RAPTOR_OPTION_LITERAL_FILL:
case RAPTOR_OPTION_BNODE_FILL:
/* JSON serializer options */
case RAPTOR_OPTION_JSON_CALLBACK:
case RAPTOR_OPTION_JSON_EXTRA_DATA:
case RAPTOR_OPTION_RSS_TRIPLES:
case RAPTOR_OPTION_ATOM_ENTRY_URI:
case RAPTOR_OPTION_PREFIX_ELEMENTS:
/* Turtle serializer option */
case RAPTOR_OPTION_WRITE_BASE_URI:
/* WWW option */
case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL:
case RAPTOR_OPTION_WWW_HTTP_USER_AGENT:
case RAPTOR_OPTION_WWW_CERT_FILENAME:
case RAPTOR_OPTION_WWW_CERT_TYPE:
case RAPTOR_OPTION_WWW_CERT_PASSPHRASE:
case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER:
case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST:
default:
return -1;
break;
}
return 0;
}
| 165,663 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TestBlinkPlatformSupport::cryptographicallyRandomValues(
unsigned char* buffer,
size_t length) {
}
Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used.
These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect.
BUG=552749
Review URL: https://codereview.chromium.org/1419293005
Cr-Commit-Position: refs/heads/master@{#359229}
CWE ID: CWE-310 | void TestBlinkPlatformSupport::cryptographicallyRandomValues(
unsigned char* buffer,
size_t length) {
base::RandBytes(buffer, length);
}
| 172,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)
{
i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;
gs_parsed_file_name_t pname;
const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting";
int code = gs_parse_file_name(&pname, fname, len, imemory);
if (code < 0)
return code;
if (pname.iodev && i_ctx_p->LockFilePermissions && strcmp(pname.iodev->dname, "%pipe%") == 0)
return gs_error_invalidfileaccess;
code = check_file_permissions(i_ctx_p, fname, len, permitgroup);
return code;
}
Commit Message:
CWE ID: CWE-200 | z_check_file_permissions(gs_memory_t *mem, const char *fname, const int len, const char *permission)
{
i_ctx_t *i_ctx_p = get_minst_from_memory(mem)->i_ctx_p;
gs_parsed_file_name_t pname;
const char *permitgroup = permission[0] == 'r' ? "PermitFileReading" : "PermitFileWriting";
int code = gs_parse_file_name(&pname, fname, len, imemory);
if (code < 0)
return code;
if (pname.iodev && i_ctx_p->LockFilePermissions
&& strcmp(pname.iodev->dname, "%pipe%") == 0) {
code = gs_note_error(gs_error_invalidfileaccess);
}
else {
code = check_file_permissions(i_ctx_p, fname, len, permitgroup);
}
return code;
}
| 164,828 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode)
: micro_benchmark_controller_(this),
image_worker_task_runner_(params->image_worker_task_runner),
compositor_mode_(mode),
ui_resource_manager_(base::MakeUnique<UIResourceManager>()),
client_(params->client),
rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
settings_(*params->settings),
debug_state_(settings_.initial_debug_state),
id_(s_layer_tree_host_sequence_number.GetNext() + 1),
task_graph_runner_(params->task_graph_runner),
event_listener_properties_(),
mutator_host_(params->mutator_host) {
DCHECK(task_graph_runner_);
DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_);
DCHECK(!settings_.enable_checker_imaging ||
settings_.image_decode_tasks_enabled);
mutator_host_->SetMutatorHostClient(this);
rendering_stats_instrumentation_->set_record_rendering_stats(
debug_state_.RecordRenderingStats());
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362 | LayerTreeHost::LayerTreeHost(InitParams* params, CompositorMode mode)
: micro_benchmark_controller_(this),
image_worker_task_runner_(params->image_worker_task_runner),
compositor_mode_(mode),
ui_resource_manager_(base::MakeUnique<UIResourceManager>()),
client_(params->client),
rendering_stats_instrumentation_(RenderingStatsInstrumentation::Create()),
settings_(*params->settings),
debug_state_(settings_.initial_debug_state),
id_(s_layer_tree_host_sequence_number.GetNext() + 1),
task_graph_runner_(params->task_graph_runner),
content_source_id_(0),
event_listener_properties_(),
mutator_host_(params->mutator_host) {
DCHECK(task_graph_runner_);
DCHECK(!settings_.enable_checker_imaging || image_worker_task_runner_);
DCHECK(!settings_.enable_checker_imaging ||
settings_.image_decode_tasks_enabled);
mutator_host_->SetMutatorHostClient(this);
rendering_stats_instrumentation_->set_record_rendering_stats(
debug_state_.RecordRenderingStats());
}
| 172,394 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
quantum.unsigned_value=(value & 0xffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed short ReadPropertySignedShort(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
quantum.unsigned_value=value & 0xffff;
return(quantum.signed_value);
}
| 169,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: void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Nate Chapin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362 | void DocumentLoader::DetachFromFrame() {
void DocumentLoader::StopLoading() {
fetcher_->StopFetching();
if (frame_ && !SentDidFinishLoad())
LoadFailed(ResourceError::CancelledError(Url()));
}
void DocumentLoader::DetachFromFrame() {
DCHECK(frame_);
StopLoading();
fetcher_->ClearContext();
if (!frame_)
return;
application_cache_host_->DetachFromDocumentLoader();
application_cache_host_.Clear();
service_worker_network_provider_ = nullptr;
WeakIdentifierMap<DocumentLoader>::NotifyObjectDestroyed(this);
ClearResource();
frame_ = nullptr;
}
| 171,851 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunFwdTxfm(const int16_t *in, int16_t *out, int stride) {
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride);
}
| 174,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderViewImpl::DidFocus() {
WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr;
bool is_processing_user_gesture =
WebUserGestureIndicator::IsProcessingUserGesture(
main_frame && main_frame->IsWebLocalFrame()
? main_frame->ToWebLocalFrame()
: nullptr);
if (is_processing_user_gesture &&
!RenderThreadImpl::current()->layout_test_mode()) {
Send(new ViewHostMsg_Focus(GetRoutingID()));
}
}
Commit Message: If a page calls |window.focus()|, kick it out of fullscreen.
BUG=776418, 800056
Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017
Reviewed-on: https://chromium-review.googlesource.com/852378
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Philip Jägenstedt <[email protected]>
Commit-Queue: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#533790}
CWE ID: | void RenderViewImpl::DidFocus() {
void RenderViewImpl::DidFocus(blink::WebLocalFrame* calling_frame) {
WebFrame* main_frame = webview() ? webview()->MainFrame() : nullptr;
bool is_processing_user_gesture =
WebUserGestureIndicator::IsProcessingUserGesture(
main_frame && main_frame->IsWebLocalFrame()
? main_frame->ToWebLocalFrame()
: nullptr);
if (is_processing_user_gesture &&
!RenderThreadImpl::current()->layout_test_mode()) {
Send(new ViewHostMsg_Focus(GetRoutingID()));
// Tattle on the frame that called |window.focus()|.
RenderFrameImpl* calling_render_frame =
RenderFrameImpl::FromWebFrame(calling_frame);
if (calling_render_frame)
calling_render_frame->FrameDidCallFocus();
}
}
| 172,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
Commit Message: af_netlink: force credentials passing [CVE-2012-3520]
Pablo Neira Ayuso discovered that avahi and
potentially NetworkManager accept spoofed Netlink messages because of a
kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data
to the receiver if the sender did not provide such data, instead of not
including any such data at all or including the correct data from the
peer (as it is the case with AF_UNIX).
This bug was introduced in commit 16e572626961
(af_unix: dont send SCM_CREDENTIALS by default)
This patch forces passing credentials for netlink, as
before the regression.
Another fix would be to not add SCM_CREDENTIALS in
netlink messages if not provided by the sender, but it
might break some programs.
With help from Florian Weimer & Petr Matousek
This issue is designated as CVE-2012-3520
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Florian Weimer <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-287 | static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
| 165,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | juniper_atm1_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
int llc_hdrlen;
struct juniper_l2info_t l2info;
l2info.pictype = DLT_JUNIPER_ATM1;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
if (l2info.cookie[0] == 0x80) { /* OAM cell ? */
oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC);
return l2info.header_len;
}
ND_TCHECK2(p[0], 3);
if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */
EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */
llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL);
if (llc_hdrlen > 0)
return l2info.header_len;
}
if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */
isoclns_print(ndo, p + 1, l2info.length - 1);
/* FIXME check if frame was recognized */
return l2info.header_len;
}
if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */
return l2info.header_len;
return l2info.header_len;
trunc:
ND_PRINT((ndo, "[|juniper_atm1]"));
return l2info.header_len;
}
| 167,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashOutImageData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth,
maskColorMap->getNumPixelComps(),
maskColorMap->getBits());
imgMaskData.imgStr->reset();
imgMaskData.colorMap = maskColorMap;
imgMaskData.maskColors = NULL;
imgMaskData.colorMode = splashModeMono8;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
n = 1 << maskColorMap->getBits();
imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
maskColorMap->getGray(&pix, &gray);
imgMaskData.lookup[i] = colToByte(gray);
}
maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(),
1, splashModeMono8, gFalse);
maskSplash = new Splash(maskBitmap, vectorAntialias);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse,
maskWidth, maskHeight, mat);
delete imgMaskData.imgStr;
maskStr->close();
gfree(imgMaskData.lookup);
delete maskSplash;
splash->setSoftMask(maskBitmap);
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = NULL;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(3 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmalloc(4 * n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat);
splash->setSoftMask(NULL);
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
Commit Message:
CWE ID: CWE-189 | void SplashOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref,
Stream *str, int width, int height,
GfxImageColorMap *colorMap,
Stream *maskStr,
int maskWidth, int maskHeight,
GfxImageColorMap *maskColorMap) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashOutImageData imgMaskData;
SplashColorMode srcMode;
SplashBitmap *maskBitmap;
Splash *maskSplash;
SplashColor maskColor;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgMaskData.imgStr = new ImageStream(maskStr, maskWidth,
maskColorMap->getNumPixelComps(),
maskColorMap->getBits());
imgMaskData.imgStr->reset();
imgMaskData.colorMap = maskColorMap;
imgMaskData.maskColors = NULL;
imgMaskData.colorMode = splashModeMono8;
imgMaskData.width = maskWidth;
imgMaskData.height = maskHeight;
imgMaskData.y = 0;
n = 1 << maskColorMap->getBits();
imgMaskData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
maskColorMap->getGray(&pix, &gray);
imgMaskData.lookup[i] = colToByte(gray);
}
maskBitmap = new SplashBitmap(bitmap->getWidth(), bitmap->getHeight(),
1, splashModeMono8, gFalse);
maskSplash = new Splash(maskBitmap, vectorAntialias);
maskColor[0] = 0;
maskSplash->clear(maskColor);
maskSplash->drawImage(&imageSrc, &imgMaskData, splashModeMono8, gFalse,
maskWidth, maskHeight, mat);
delete imgMaskData.imgStr;
maskStr->close();
gfree(imgMaskData.lookup);
delete maskSplash;
splash->setSoftMask(maskBitmap);
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = NULL;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
splash->drawImage(&imageSrc, &imgData, srcMode, gFalse, width, height, mat);
splash->setSoftMask(NULL);
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
| 164,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
{
int status = 0;
return status;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119 | int NsSetParameter (preproc_effect_t *effect, void *pParam, void *pValue)
int NsSetParameter (preproc_effect_t *effect __unused,
void *pParam __unused,
void *pValue __unused)
{
int status = 0;
return status;
}
| 173,352 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
s->nextfunction = qemu_get_byte(f);
s->precision = qemu_get_byte(f);
s->nextprecision = qemu_get_byte(f);
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
Commit Message:
CWE ID: CWE-119 | static int tsc210x_load(QEMUFile *f, void *opaque, int version_id)
{
TSC210xState *s = (TSC210xState *) opaque;
int64_t now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
int i;
s->x = qemu_get_be16(f);
s->y = qemu_get_be16(f);
s->pressure = qemu_get_byte(f);
s->state = qemu_get_byte(f);
s->page = qemu_get_byte(f);
s->offset = qemu_get_byte(f);
s->command = qemu_get_byte(f);
s->irq = qemu_get_byte(f);
qemu_get_be16s(f, &s->dav);
timer_get(f, s->timer);
s->enabled = qemu_get_byte(f);
s->host_mode = qemu_get_byte(f);
s->function = qemu_get_byte(f);
if (s->function < 0 || s->function >= ARRAY_SIZE(mode_regs)) {
return -EINVAL;
}
s->nextfunction = qemu_get_byte(f);
if (s->nextfunction < 0 || s->nextfunction >= ARRAY_SIZE(mode_regs)) {
return -EINVAL;
}
s->precision = qemu_get_byte(f);
if (s->precision < 0 || s->precision >= ARRAY_SIZE(resolution)) {
return -EINVAL;
}
s->nextprecision = qemu_get_byte(f);
if (s->nextprecision < 0 || s->nextprecision >= ARRAY_SIZE(resolution)) {
return -EINVAL;
}
s->filter = qemu_get_byte(f);
s->pin_func = qemu_get_byte(f);
s->ref = qemu_get_byte(f);
qemu_get_be16s(f, &s->dac_power);
for (i = 0; i < 0x14; i ++)
qemu_get_be16s(f, &s->filter_data[i]);
s->busy = timer_pending(s->timer);
qemu_set_irq(s->pint, !s->irq);
qemu_set_irq(s->davint, !s->dav);
return 0;
}
| 165,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, setMaxLineLen)
{
long max_len;
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) {
return;
}
if (max_len < 0) {
zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero");
return;
}
intern->u.file.max_line_len = max_len;
} /* }}} */
/* {{{ proto int SplFileObject::getMaxLineLen()
| 167,058 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address)
{
PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s);
return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01,
"*l*lwwb*b*b*blww",
pcic->vendor_id, pcic->device_id, pcic->revision,
pcic->subsystem_vendor_id,
pcic->subsystem_id);
}
Commit Message:
CWE ID: CWE-20 | size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address)
{
PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s);
return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01,
"*l*lwwb*b*b*blww",
pcic->vendor_id, pcic->device_id, pcic->revision,
pcic->class_id, pcic->subsystem_vendor_id,
pcic->subsystem_id);
}
| 164,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Tracks::~Tracks()
{
Track** i = m_trackEntries;
Track** const j = m_trackEntriesEnd;
while (i != j)
{
Track* const pTrack = *i++;
delete pTrack;
}
delete[] m_trackEntries;
}
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 | Tracks::~Tracks()
| 174,473 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PaymentRequest::Abort() {
bool accepting_abort = !state_->IsPaymentAppInvoked();
if (accepting_abort)
RecordFirstAbortReason(JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT);
if (client_.is_bound())
client_->OnAbort(accepting_abort);
if (observer_for_testing_)
observer_for_testing_->OnAbortCalled();
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189 | void PaymentRequest::Abort() {
if (!IsInitialized()) {
log_.Error("Attempted abort without initialization");
OnConnectionTerminated();
return;
}
if (!IsThisPaymentRequestShowing()) {
log_.Error("Attempted abort without show");
OnConnectionTerminated();
return;
}
bool accepting_abort = !state_->IsPaymentAppInvoked();
if (accepting_abort)
RecordFirstAbortReason(JourneyLogger::ABORT_REASON_ABORTED_BY_MERCHANT);
if (client_.is_bound())
client_->OnAbort(accepting_abort);
if (observer_for_testing_)
observer_for_testing_->OnAbortCalled();
}
| 173,078 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
Commit Message: Fixed crash in elf.c with 32bit r2 when shdr->sh_size > max size_t
CWE ID: CWE-119 | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
}
| 167,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 quint32 swapBgrToRgb(quint32 pixel)
{
return ((pixel << 16) & 0xff0000) | ((pixel >> 16) & 0xff) | (pixel & 0xff00ff00);
}
Commit Message: [Qt] Remove an unnecessary masking from swapBgrToRgb()
https://bugs.webkit.org/show_bug.cgi?id=103630
Reviewed by Zoltan Herczeg.
Get rid of a masking command in swapBgrToRgb() to speed up a little bit.
* platform/graphics/qt/GraphicsContext3DQt.cpp:
(WebCore::swapBgrToRgb):
git-svn-id: svn://svn.chromium.org/blink/trunk@136375 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264 | static inline quint32 swapBgrToRgb(quint32 pixel)
{
return (((pixel << 16) | (pixel >> 16)) & 0x00ff00ff) | (pixel & 0xff00ff00);
}
| 170,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
int status)
{
struct dwc3 *dwc = dep->dwc;
req->started = false;
list_del(&req->list);
req->remaining = 0;
if (req->request.status == -EINPROGRESS)
req->request.status = status;
if (req->trb)
usb_gadget_unmap_request_by_dev(dwc->sysdev,
&req->request, req->direction);
req->trb = NULL;
trace_dwc3_gadget_giveback(req);
spin_unlock(&dwc->lock);
usb_gadget_giveback_request(&dep->endpoint, &req->request);
spin_lock(&dwc->lock);
if (dep->number > 1)
pm_runtime_put(dwc->dev);
}
Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue()
This is a requirement which has always existed but, somehow, wasn't
reflected in the documentation and problems weren't found until now
when Tuba Yavuz found a possible deadlock happening between dwc3 and
f_hid. She described the situation as follows:
spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire
/* we our function has been disabled by host */
if (!hidg->req) {
free_ep_req(hidg->in_ep, hidg->req);
goto try_again;
}
[...]
status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
=>
[...]
=> usb_gadget_giveback_request
=>
f_hidg_req_complete
=>
spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire
Note that this happens because dwc3 would call ->complete() on a
failed usb_ep_queue() due to failed Start Transfer command. This is,
anyway, a theoretical situation because dwc3 currently uses "No
Response Update Transfer" command for Bulk and Interrupt endpoints.
It's still good to make this case impossible to happen even if the "No
Reponse Update Transfer" command is changed.
Reported-by: Tuba Yavuz <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189 | void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
void dwc3_gadget_del_and_unmap_request(struct dwc3_ep *dep,
struct dwc3_request *req, int status)
{
struct dwc3 *dwc = dep->dwc;
req->started = false;
list_del(&req->list);
req->remaining = 0;
if (req->request.status == -EINPROGRESS)
req->request.status = status;
if (req->trb)
usb_gadget_unmap_request_by_dev(dwc->sysdev,
&req->request, req->direction);
req->trb = NULL;
trace_dwc3_gadget_giveback(req);
if (dep->number > 1)
pm_runtime_put(dwc->dev);
}
/**
* dwc3_gadget_giveback - call struct usb_request's ->complete callback
* @dep: The endpoint to whom the request belongs to
* @req: The request we're giving back
* @status: completion code for the request
*
* Must be called with controller's lock held and interrupts disabled. This
* function will unmap @req and call its ->complete() callback to notify upper
* layers that it has completed.
*/
void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
int status)
{
struct dwc3 *dwc = dep->dwc;
dwc3_gadget_del_and_unmap_request(dep, req, status);
spin_unlock(&dwc->lock);
usb_gadget_giveback_request(&dep->endpoint, &req->request);
spin_lock(&dwc->lock);
}
| 169,579 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Block Tifinagh + Latin mix
BUG=chromium:722639
TEST=components_unittests --gtest_filter=*IDNToU*
Review-Url: https://codereview.chromium.org/2894313002
Cr-Commit-Position: refs/heads/master@{#474199}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disalow mixing of Latin and Tifinagh.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,363 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type, phnum, shnum;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
if (S_ISREG(st.st_mode) || st.st_size != 0)
fsize = st.st_size;
else
fsize = SIZE_UNKNOWN;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type, phnum, shnum, notecount;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
if (S_ISREG(st.st_mode) || st.st_size != 0)
fsize = st.st_size;
else
fsize = SIZE_UNKNOWN;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
| 166,780 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int lua_websocket_read(lua_State *L)
{
apr_socket_t *sock;
apr_status_t rv;
int n = 0;
apr_size_t len = 1;
apr_size_t plen = 0;
unsigned short payload_short = 0;
apr_uint64_t payload_long = 0;
unsigned char *mask_bytes;
char byte;
int plaintext;
request_rec *r = ap_lua_check_request_rec(L, 1);
plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1;
mask_bytes = apr_pcalloc(r->pool, 4);
sock = ap_get_conn_socket(r->connection);
/* Get opcode and FIN bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
unsigned char ubyte, fin, opcode, mask, payload;
ubyte = (unsigned char)byte;
/* fin bit is the first bit */
fin = ubyte >> (CHAR_BIT - 1);
/* opcode is the last four bits (there's 3 reserved bits we don't care about) */
opcode = ubyte & 0xf;
/* Get the payload length and mask bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
ubyte = (unsigned char)byte;
/* Mask is the first bit */
mask = ubyte >> (CHAR_BIT - 1);
/* Payload is the last 7 bits */
payload = ubyte & 0x7f;
plen = payload;
/* Extended payload? */
if (payload == 126) {
len = 2;
if (plaintext) {
/* XXX: apr_socket_recv does not receive len bits, only up to len bits! */
rv = apr_socket_recv(sock, (char*) &payload_short, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_short, 2);
}
payload_short = ntohs(payload_short);
if (rv == APR_SUCCESS) {
plen = payload_short;
}
else {
return 0;
}
}
/* Super duper extended payload? */
if (payload == 127) {
len = 8;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) &payload_long, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_long, 8);
}
if (rv == APR_SUCCESS) {
plen = ap_ntoh64(&payload_long);
}
else {
return 0;
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s",
plen,
(payload >= 126) ? "extra payload" : "no extra payload",
mask ? "on" : "off",
fin ? "This is a final frame" : "more to follow");
if (mask) {
len = 4;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) mask_bytes, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) mask_bytes, 4);
}
if (rv != APR_SUCCESS) {
return 0;
}
}
if (plen < (HUGE_STRING_LEN*1024) && plen > 0) {
apr_size_t remaining = plen;
apr_size_t received;
apr_off_t at = 0;
char *buffer = apr_palloc(r->pool, plen+1);
buffer[plen] = 0;
if (plaintext) {
while (remaining > 0) {
received = remaining;
rv = apr_socket_recv(sock, buffer+at, &received);
if (received > 0 ) {
remaining -= received;
at += received;
}
}
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack",
at);
}
else {
rv = lua_websocket_readbytes(r->connection, buffer,
remaining);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\
"pushed to Lua stack",
remaining);
}
if (mask) {
for (n = 0; n < plen; n++) {
buffer[n] ^= mask_bytes[n%4];
}
}
lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */
lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */
return 2;
}
/* Decide if we need to react to the opcode or not */
if (opcode == 0x09) { /* ping */
char frame[2];
plen = 2;
frame[0] = 0x8A;
frame[1] = 0;
apr_socket_send(sock, frame, &plen); /* Pong! */
lua_websocket_read(L); /* read the next frame instead */
}
}
}
return 0;
}
Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org)
mod_lua: A maliciously crafted websockets PING after a script
calls r:wsupgrade() can cause a child process crash.
[Edward Lu <Chaosed0 gmail.com>]
Discovered by Guido Vranken <guidovranken gmail.com>
Submitted by: Edward Lu
Committed by: covener
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20 | static int lua_websocket_read(lua_State *L)
{
apr_socket_t *sock;
apr_status_t rv;
int do_read = 1;
int n = 0;
apr_size_t len = 1;
apr_size_t plen = 0;
unsigned short payload_short = 0;
apr_uint64_t payload_long = 0;
unsigned char *mask_bytes;
char byte;
int plaintext;
request_rec *r = ap_lua_check_request_rec(L, 1);
plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1;
mask_bytes = apr_pcalloc(r->pool, 4);
sock = ap_get_conn_socket(r->connection);
while (do_read) {
do_read = 0;
/* Get opcode and FIN bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
unsigned char ubyte, fin, opcode, mask, payload;
ubyte = (unsigned char)byte;
/* fin bit is the first bit */
fin = ubyte >> (CHAR_BIT - 1);
/* opcode is the last four bits (there's 3 reserved bits we don't care about) */
opcode = ubyte & 0xf;
/* Get the payload length and mask bit */
if (plaintext) {
rv = apr_socket_recv(sock, &byte, &len);
}
else {
rv = lua_websocket_readbytes(r->connection, &byte, 1);
}
if (rv == APR_SUCCESS) {
ubyte = (unsigned char)byte;
/* Mask is the first bit */
mask = ubyte >> (CHAR_BIT - 1);
/* Payload is the last 7 bits */
payload = ubyte & 0x7f;
plen = payload;
/* Extended payload? */
if (payload == 126) {
len = 2;
if (plaintext) {
/* XXX: apr_socket_recv does not receive len bits, only up to len bits! */
rv = apr_socket_recv(sock, (char*) &payload_short, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_short, 2);
}
payload_short = ntohs(payload_short);
if (rv == APR_SUCCESS) {
plen = payload_short;
}
else {
return 0;
}
}
/* Super duper extended payload? */
if (payload == 127) {
len = 8;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) &payload_long, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) &payload_long, 8);
}
if (rv == APR_SUCCESS) {
plen = ap_ntoh64(&payload_long);
}
else {
return 0;
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s",
plen,
(payload >= 126) ? "extra payload" : "no extra payload",
mask ? "on" : "off",
fin ? "This is a final frame" : "more to follow");
if (mask) {
len = 4;
if (plaintext) {
rv = apr_socket_recv(sock, (char*) mask_bytes, &len);
}
else {
rv = lua_websocket_readbytes(r->connection,
(char*) mask_bytes, 4);
}
if (rv != APR_SUCCESS) {
return 0;
}
}
if (plen < (HUGE_STRING_LEN*1024) && plen > 0) {
apr_size_t remaining = plen;
apr_size_t received;
apr_off_t at = 0;
char *buffer = apr_palloc(r->pool, plen+1);
buffer[plen] = 0;
if (plaintext) {
while (remaining > 0) {
received = remaining;
rv = apr_socket_recv(sock, buffer+at, &received);
if (received > 0 ) {
remaining -= received;
at += received;
}
}
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack",
at);
}
else {
rv = lua_websocket_readbytes(r->connection, buffer,
remaining);
ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r,
"Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\
"pushed to Lua stack",
remaining);
}
if (mask) {
for (n = 0; n < plen; n++) {
buffer[n] ^= mask_bytes[n%4];
}
}
lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */
lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */
return 2;
}
/* Decide if we need to react to the opcode or not */
if (opcode == 0x09) { /* ping */
char frame[2];
plen = 2;
frame[0] = 0x8A;
frame[1] = 0;
apr_socket_send(sock, frame, &plen); /* Pong! */
do_read = 1;
}
}
}
}
return 0;
}
| 166,744 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 perf_pmu_register(struct pmu *pmu, const char *name, int type)
{
int cpu, ret;
mutex_lock(&pmus_lock);
ret = -ENOMEM;
pmu->pmu_disable_count = alloc_percpu(int);
if (!pmu->pmu_disable_count)
goto unlock;
pmu->type = -1;
if (!name)
goto skip_type;
pmu->name = name;
if (type < 0) {
type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
if (type < 0) {
ret = type;
goto free_pdc;
}
}
pmu->type = type;
if (pmu_bus_running) {
ret = pmu_dev_alloc(pmu);
if (ret)
goto free_idr;
}
skip_type:
pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
if (pmu->pmu_cpu_context)
goto got_cpu_context;
ret = -ENOMEM;
pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
if (!pmu->pmu_cpu_context)
goto free_dev;
for_each_possible_cpu(cpu) {
struct perf_cpu_context *cpuctx;
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
__perf_event_init_context(&cpuctx->ctx);
lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
cpuctx->ctx.type = cpu_context;
cpuctx->ctx.pmu = pmu;
__perf_cpu_hrtimer_init(cpuctx, cpu);
INIT_LIST_HEAD(&cpuctx->rotation_list);
cpuctx->unique_pmu = pmu;
}
got_cpu_context:
if (!pmu->start_txn) {
if (pmu->pmu_enable) {
/*
* If we have pmu_enable/pmu_disable calls, install
* transaction stubs that use that to try and batch
* hardware accesses.
*/
pmu->start_txn = perf_pmu_start_txn;
pmu->commit_txn = perf_pmu_commit_txn;
pmu->cancel_txn = perf_pmu_cancel_txn;
} else {
pmu->start_txn = perf_pmu_nop_void;
pmu->commit_txn = perf_pmu_nop_int;
pmu->cancel_txn = perf_pmu_nop_void;
}
}
if (!pmu->pmu_enable) {
pmu->pmu_enable = perf_pmu_nop_void;
pmu->pmu_disable = perf_pmu_nop_void;
}
if (!pmu->event_idx)
pmu->event_idx = perf_event_idx_default;
list_add_rcu(&pmu->entry, &pmus);
ret = 0;
unlock:
mutex_unlock(&pmus_lock);
return ret;
free_dev:
device_del(pmu->dev);
put_device(pmu->dev);
free_idr:
if (pmu->type >= PERF_TYPE_MAX)
idr_remove(&pmu_idr, pmu->type);
free_pdc:
free_percpu(pmu->pmu_disable_count);
goto unlock;
}
Commit Message: perf: Tighten (and fix) the grouping condition
The fix from 9fc81d87420d ("perf: Fix events installation during
moving group") was incomplete in that it failed to recognise that
creating a group with events for different CPUs is semantically
broken -- they cannot be co-scheduled.
Furthermore, it leads to real breakage where, when we create an event
for CPU Y and then migrate it to form a group on CPU X, the code gets
confused where the counter is programmed -- triggered in practice
as well by me via the perf fuzzer.
Fix this by tightening the rules for creating groups. Only allow
grouping of counters that can be co-scheduled in the same context.
This means for the same task and/or the same cpu.
Fixes: 9fc81d87420d ("perf: Fix events installation during moving group")
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | int perf_pmu_register(struct pmu *pmu, const char *name, int type)
{
int cpu, ret;
mutex_lock(&pmus_lock);
ret = -ENOMEM;
pmu->pmu_disable_count = alloc_percpu(int);
if (!pmu->pmu_disable_count)
goto unlock;
pmu->type = -1;
if (!name)
goto skip_type;
pmu->name = name;
if (type < 0) {
type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
if (type < 0) {
ret = type;
goto free_pdc;
}
}
pmu->type = type;
if (pmu_bus_running) {
ret = pmu_dev_alloc(pmu);
if (ret)
goto free_idr;
}
skip_type:
pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
if (pmu->pmu_cpu_context)
goto got_cpu_context;
ret = -ENOMEM;
pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
if (!pmu->pmu_cpu_context)
goto free_dev;
for_each_possible_cpu(cpu) {
struct perf_cpu_context *cpuctx;
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
__perf_event_init_context(&cpuctx->ctx);
lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
cpuctx->ctx.pmu = pmu;
__perf_cpu_hrtimer_init(cpuctx, cpu);
INIT_LIST_HEAD(&cpuctx->rotation_list);
cpuctx->unique_pmu = pmu;
}
got_cpu_context:
if (!pmu->start_txn) {
if (pmu->pmu_enable) {
/*
* If we have pmu_enable/pmu_disable calls, install
* transaction stubs that use that to try and batch
* hardware accesses.
*/
pmu->start_txn = perf_pmu_start_txn;
pmu->commit_txn = perf_pmu_commit_txn;
pmu->cancel_txn = perf_pmu_cancel_txn;
} else {
pmu->start_txn = perf_pmu_nop_void;
pmu->commit_txn = perf_pmu_nop_int;
pmu->cancel_txn = perf_pmu_nop_void;
}
}
if (!pmu->pmu_enable) {
pmu->pmu_enable = perf_pmu_nop_void;
pmu->pmu_disable = perf_pmu_nop_void;
}
if (!pmu->event_idx)
pmu->event_idx = perf_event_idx_default;
list_add_rcu(&pmu->entry, &pmus);
ret = 0;
unlock:
mutex_unlock(&pmus_lock);
return ret;
free_dev:
device_del(pmu->dev);
put_device(pmu->dev);
free_idr:
if (pmu->type >= PERF_TYPE_MAX)
idr_remove(&pmu_idr, pmu->type);
free_pdc:
free_percpu(pmu->pmu_disable_count);
goto unlock;
}
| 168,852 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: ...
CWE ID: CWE-20 | ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 168,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: void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%s", idx.c_str());
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89 | void CWebServer::GetFloorplanImage(WebEmSession & session, const request& req, reply & rep)
{
std::string idx = request::findValue(&req, "idx");
if (idx == "") {
return;
}
std::vector<std::vector<std::string> > result;
result = m_sql.safe_queryBlob("SELECT Image FROM Floorplans WHERE ID=%d", atol(idx.c_str()));
if (result.empty())
return;
reply::set_content(&rep, result[0][0].begin(), result[0][0].end());
std::string oname = "floorplan";
if (result[0][0].size() > 10)
{
if (result[0][0][0] == 'P')
oname += ".png";
else if (result[0][0][0] == -1)
oname += ".jpg";
else if (result[0][0][0] == 'B')
oname += ".bmp";
else if (result[0][0][0] == 'G')
oname += ".gif";
}
reply::add_header_attachment(&rep, oname);
}
| 169,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DisconnectWindowLinux::Show(remoting::ChromotingHost* host,
const std::string& username) {
NOTIMPLEMENTED();
}
Commit Message: Initial implementation of DisconnectWindow on Linux.
BUG=None
TEST=Manual
Review URL: http://codereview.chromium.org/7089016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DisconnectWindowLinux::Show(remoting::ChromotingHost* host,
const std::string& username) {
host_ = host;
CreateWindow();
gtk_label_set_text(GTK_LABEL(user_label_), username.c_str());
gtk_window_present(GTK_WINDOW(disconnect_window_));
}
| 170,474 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host,
DevToolsAgentHostClient* client)
: binding_(this),
agent_host_(agent_host),
client_(client),
process_host_id_(ChildProcessHost::kInvalidUniqueID),
host_(nullptr),
dispatcher_(new protocol::UberDispatcher(this)),
weak_factory_(this) {
dispatcher_->setFallThroughForNotFound(true);
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host,
DevToolsAgentHostClient* client,
bool restricted)
: binding_(this),
agent_host_(agent_host),
client_(client),
restricted_(restricted),
process_host_id_(ChildProcessHost::kInvalidUniqueID),
host_(nullptr),
dispatcher_(new protocol::UberDispatcher(this)),
weak_factory_(this) {
dispatcher_->setFallThroughForNotFound(true);
}
| 173,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
{
int i;
png_uint_16 freq[256];
/* libpng takes the count from the PLTE count; we don't check it here but we
* do set the array to 0 for unspecified entries.
*/
memset(freq, 0, sizeof freq);
for (i=0; i<nparams; ++i)
{
char *endptr = NULL;
unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
if (params[i][0] && *endptr == 0 && l <= 65535)
freq[i] = (png_uint_16)l;
else
{
fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
exit(1);
}
}
png_set_hIST(png_ptr, info_ptr, freq);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams, png_charpp params)
insert_hIST(png_structp png_ptr, png_infop info_ptr, int nparams,
png_charpp params)
{
int i;
png_uint_16 freq[256];
/* libpng takes the count from the PLTE count; we don't check it here but we
* do set the array to 0 for unspecified entries.
*/
memset(freq, 0, sizeof freq);
for (i=0; i<nparams; ++i)
{
char *endptr = NULL;
unsigned long int l = strtoul(params[i], &endptr, 0/*base*/);
if (params[i][0] && *endptr == 0 && l <= 65535)
freq[i] = (png_uint_16)l;
else
{
fprintf(stderr, "hIST[%d]: %s: invalid frequency\n", i, params[i]);
exit(1);
}
}
png_set_hIST(png_ptr, info_ptr, freq);
}
| 173,582 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TEE_Result syscall_asymm_operate(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *src_data, size_t src_len,
void *dst_data, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen64;
size_t dlen;
struct tee_obj *o;
void *label = NULL;
size_t label_len = 0;
size_t n;
int salt_len;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64));
if (res != TEE_SUCCESS)
return res;
dlen = dlen64;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
params = malloc(sizeof(TEE_Attribute) * num_params);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_GENERIC;
goto out;
}
switch (cs->algo) {
case TEE_ALG_RSA_NOPAD:
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else {
/*
* We will panic because "the mode is not compatible
* with the function"
*/
res = TEE_ERROR_GENERIC;
}
break;
case TEE_ALG_RSAES_PKCS1_V1_5:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
label = params[n].content.ref.buffer;
label_len = params[n].content.ref.length;
break;
}
}
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
label, label_len,
src_data, src_len,
dst_data, &dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsaes_decrypt(
cs->algo, o->attr, label, label_len,
src_data, src_len, dst_data, &dlen);
} else {
res = TEE_ERROR_BAD_PARAMETERS;
}
break;
#if defined(CFG_CRYPTO_RSASSA_NA1)
case TEE_ALG_RSASSA_PKCS1_V1_5:
#endif
case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
if (cs->mode != TEE_MODE_SIGN) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params, src_len);
res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
src_data, src_len, dst_data,
&dlen);
break;
case TEE_ALG_DSA_SHA1:
case TEE_ALG_DSA_SHA224:
case TEE_ALG_DSA_SHA256:
res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
case TEE_ALG_ECDSA_P192:
case TEE_ALG_ECDSA_P224:
case TEE_ALG_ECDSA_P256:
case TEE_ALG_ECDSA_P384:
case TEE_ALG_ECDSA_P521:
res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
default:
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
out:
free(params);
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
dlen64 = dlen;
res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
Commit Message: svc: check for allocation overflow in crypto calls part 2
Without checking for overflow there is a risk of allocating a buffer
with size smaller than anticipated and as a consequence of that it might
lead to a heap based overflow with attacker controlled data written
outside the boundaries of the buffer.
Fixes: OP-TEE-2018-0011: "Integer overflow in crypto system calls (x2)"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-119 | TEE_Result syscall_asymm_operate(unsigned long state,
const struct utee_attribute *usr_params,
size_t num_params, const void *src_data, size_t src_len,
void *dst_data, uint64_t *dst_len)
{
TEE_Result res;
struct tee_cryp_state *cs;
struct tee_ta_session *sess;
uint64_t dlen64;
size_t dlen;
struct tee_obj *o;
void *label = NULL;
size_t label_len = 0;
size_t n;
int salt_len;
TEE_Attribute *params = NULL;
struct user_ta_ctx *utc;
res = tee_ta_get_current_session(&sess);
if (res != TEE_SUCCESS)
return res;
utc = to_user_ta_ctx(sess->ctx);
res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
if (res != TEE_SUCCESS)
return res;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) src_data, src_len);
if (res != TEE_SUCCESS)
return res;
res = tee_svc_copy_from_user(&dlen64, dst_len, sizeof(dlen64));
if (res != TEE_SUCCESS)
return res;
dlen = dlen64;
res = tee_mmu_check_access_rights(
utc,
TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
TEE_MEMORY_ACCESS_ANY_OWNER,
(uaddr_t) dst_data, dlen);
if (res != TEE_SUCCESS)
return res;
size_t alloc_size = 0;
if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
return TEE_ERROR_OVERFLOW;
params = malloc(alloc_size);
if (!params)
return TEE_ERROR_OUT_OF_MEMORY;
res = copy_in_attrs(utc, usr_params, num_params, params);
if (res != TEE_SUCCESS)
goto out;
res = tee_obj_get(utc, cs->key1, &o);
if (res != TEE_SUCCESS)
goto out;
if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
res = TEE_ERROR_GENERIC;
goto out;
}
switch (cs->algo) {
case TEE_ALG_RSA_NOPAD:
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
src_len, dst_data,
&dlen);
} else {
/*
* We will panic because "the mode is not compatible
* with the function"
*/
res = TEE_ERROR_GENERIC;
}
break;
case TEE_ALG_RSAES_PKCS1_V1_5:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
for (n = 0; n < num_params; n++) {
if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
label = params[n].content.ref.buffer;
label_len = params[n].content.ref.length;
break;
}
}
if (cs->mode == TEE_MODE_ENCRYPT) {
res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
label, label_len,
src_data, src_len,
dst_data, &dlen);
} else if (cs->mode == TEE_MODE_DECRYPT) {
res = crypto_acipher_rsaes_decrypt(
cs->algo, o->attr, label, label_len,
src_data, src_len, dst_data, &dlen);
} else {
res = TEE_ERROR_BAD_PARAMETERS;
}
break;
#if defined(CFG_CRYPTO_RSASSA_NA1)
case TEE_ALG_RSASSA_PKCS1_V1_5:
#endif
case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
if (cs->mode != TEE_MODE_SIGN) {
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
salt_len = pkcs1_get_salt_len(params, num_params, src_len);
res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
src_data, src_len, dst_data,
&dlen);
break;
case TEE_ALG_DSA_SHA1:
case TEE_ALG_DSA_SHA224:
case TEE_ALG_DSA_SHA256:
res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
case TEE_ALG_ECDSA_P192:
case TEE_ALG_ECDSA_P224:
case TEE_ALG_ECDSA_P256:
case TEE_ALG_ECDSA_P384:
case TEE_ALG_ECDSA_P521:
res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
src_len, dst_data, &dlen);
break;
default:
res = TEE_ERROR_BAD_PARAMETERS;
break;
}
out:
free(params);
if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
TEE_Result res2;
dlen64 = dlen;
res2 = tee_svc_copy_to_user(dst_len, &dlen64, sizeof(*dst_len));
if (res2 != TEE_SUCCESS)
return res2;
}
return res;
}
| 169,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MagickBooleanType ClonePixelCacheRepository(
CacheInfo *restrict clone_info,CacheInfo *restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads 2
#define cache_threads(source,destination,chunk) \
num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \
GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \
GetMagickResourceLimit(ThreadResource) : MaxCacheThreads)
MagickBooleanType
status;
NexusInfo
**restrict cache_nexus,
**restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) &&
(cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->active_index_channel == clone_info->active_index_channel))
{
/*
Identical pixel cache morphology.
*/
CopyPixels(clone_info->pixels,cache_info->pixels,cache_info->columns*
cache_info->rows);
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
(void) memcpy(clone_info->indexes,cache_info->indexes,
cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes));
return(MagickTrue);
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
if ((cache_nexus == (NexusInfo **) NULL) ||
(clone_nexus == (NexusInfo **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->pixels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t)
clone_nexus[id]->length);
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length);
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
{
/*
Clone indexes.
*/
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->indexes);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length);
status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception);
}
}
cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads);
clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
Commit Message:
CWE ID: CWE-189 | static MagickBooleanType ClonePixelCacheRepository(
CacheInfo *restrict clone_info,CacheInfo *restrict cache_info,
ExceptionInfo *exception)
{
#define MaxCacheThreads 2
#define cache_threads(source,destination,chunk) \
num_threads((chunk) < (16*GetMagickResourceLimit(ThreadResource)) ? 1 : \
GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \
GetMagickResourceLimit(ThreadResource) : MaxCacheThreads)
MagickBooleanType
status;
NexusInfo
**restrict cache_nexus,
**restrict clone_nexus;
size_t
length;
ssize_t
y;
assert(cache_info != (CacheInfo *) NULL);
assert(clone_info != (CacheInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
if (cache_info->type == PingCache)
return(MagickTrue);
if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) &&
((clone_info->type == MemoryCache) || (clone_info->type == MapCache)) &&
(cache_info->columns == clone_info->columns) &&
(cache_info->rows == clone_info->rows) &&
(cache_info->active_index_channel == clone_info->active_index_channel))
{
/*
Identical pixel cache morphology.
*/
(void) memcpy(clone_info->pixels,cache_info->pixels,cache_info->columns*
cache_info->rows*sizeof(*cache_info->pixels));
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
(void) memcpy(clone_info->indexes,cache_info->indexes,
cache_info->columns*cache_info->rows*sizeof(*cache_info->indexes));
return(MagickTrue);
}
/*
Mismatched pixel cache morphology.
*/
cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads);
if ((cache_nexus == (NexusInfo **) NULL) ||
(clone_nexus == (NexusInfo **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->pixels);
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t)
clone_nexus[id]->length);
(void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length);
status=WritePixelCachePixels(clone_info,clone_nexus[id],exception);
}
if ((cache_info->active_index_channel != MagickFalse) &&
(clone_info->active_index_channel != MagickFalse))
{
/*
Clone indexes.
*/
length=(size_t) MagickMin(cache_info->columns,clone_info->columns)*
sizeof(*cache_info->indexes);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
cache_threads(cache_info,clone_info,cache_info->rows)
#endif
for (y=0; y < (ssize_t) cache_info->rows; y++)
{
const int
id = GetOpenMPThreadId();
PixelPacket
*pixels;
RectangleInfo
region;
if (status == MagickFalse)
continue;
if (y >= (ssize_t) clone_info->rows)
continue;
region.width=cache_info->columns;
region.height=1;
region.x=0;
region.y=y;
pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,®ion,MagickTrue,
cache_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception);
if (status == MagickFalse)
continue;
region.width=clone_info->columns;
pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,®ion,MagickTrue,
clone_nexus[id],exception);
if (pixels == (PixelPacket *) NULL)
continue;
(void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length);
status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception);
}
}
cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads);
clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads);
if (cache_info->debug != MagickFalse)
{
char
message[MaxTextExtent];
(void) FormatLocaleString(message,MaxTextExtent,"%s => %s",
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type),
CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type));
(void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message);
}
return(status);
}
| 168,810 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
}
Commit Message:
CWE ID: CWE-125 | xps_load_sfnt_name(xps_font_t *font, char *namep)
{
byte *namedata;
int offset, length;
/*int format;*/
int count, stringoffset;
int found;
int i, k;
found = 0;
strcpy(namep, "Unknown");
offset = xps_find_sfnt_table(font, "name", &length);
if (offset < 0 || length < 6)
{
gs_warn("cannot find name table");
return;
}
/* validate the offset, and the data for the two
* values we're about to read
*/
if (offset + 6 > font->length)
{
gs_warn("name table byte offset invalid");
return;
}
namedata = font->data + offset;
/*format = u16(namedata + 0);*/
count = u16(namedata + 2);
stringoffset = u16(namedata + 4);
if (stringoffset + offset > font->length
|| offset + 6 + count * 12 > font->length)
{
gs_warn("name table invalid");
return;
}
if (length < 6 + (count * 12))
{
gs_warn("name table too short");
{
if (pid == 1 && eid == 0 && langid == 0) /* mac roman, english */
{
if (found < 3)
{
memcpy(namep, namedata + stringoffset + offset, length);
namep[length] = 0;
found = 3;
}
}
if (pid == 3 && eid == 1 && langid == 0x409) /* windows unicode ucs-2, US */
{
if (found < 2)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 2;
for (k = 0; k < n; k ++)
{
int c = u16(s + k * 2);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 2;
}
}
if (pid == 3 && eid == 10 && langid == 0x409) /* windows unicode ucs-4, US */
{
if (found < 1)
{
unsigned char *s = namedata + stringoffset + offset;
int n = length / 4;
for (k = 0; k < n; k ++)
{
int c = u32(s + k * 4);
namep[k] = isprint(c) ? c : '?';
}
namep[k] = 0;
found = 1;
}
}
}
}
}
| 164,787 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
unsigned long flags;
int ret;
spin_lock_irqsave(&dev->lock, flags);
buf[0] = CP2112_GPIO_SET;
buf[1] = value ? 0xff : 0;
buf[2] = 1 << offset;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf,
CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0)
hid_err(hdev, "error setting GPIO values: %d\n", ret);
spin_unlock_irqrestore(&dev->lock, flags);
}
Commit Message: HID: cp2112: fix sleep-while-atomic
A recent commit fixing DMA-buffers on stack added a shared transfer
buffer protected by a spinlock. This is broken as the USB HID request
callbacks can sleep. Fix this up by replacing the spinlock with a mutex.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-404 | static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
struct cp2112_device *dev = gpiochip_get_data(chip);
struct hid_device *hdev = dev->hdev;
u8 *buf = dev->in_out_buffer;
int ret;
mutex_lock(&dev->lock);
buf[0] = CP2112_GPIO_SET;
buf[1] = value ? 0xff : 0;
buf[2] = 1 << offset;
ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf,
CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT,
HID_REQ_SET_REPORT);
if (ret < 0)
hid_err(hdev, "error setting GPIO values: %d\n", ret);
mutex_unlock(&dev->lock);
}
| 168,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %lu, expected %zu", (unsigned long)outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
Commit Message: Fix build
Change-Id: I48ba34b3df9c9a896d4b18c3f48e41744b7dab54
CWE ID: CWE-264 | void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) {
if (len > outHeader->nAllocLen) {
ALOGE("memset buffer too small: got %u, expected %zu", outHeader->nAllocLen, len);
android_errorWriteLog(0x534e4554, "29422022");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return NULL;
}
return memset(outHeader->pBuffer, c, len);
}
| 174,156 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) {
const xmlChar *name = NULL;
xmlChar *ExternalID = NULL;
xmlChar *URI = NULL;
/*
* We know that '<!DOCTYPE' has been detected.
*/
SKIP(9);
SKIP_BLANKS;
/*
* Parse the DOCTYPE name.
*/
name = xmlParseName(ctxt);
if (name == NULL) {
xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED,
"xmlParseDocTypeDecl : no DOCTYPE name !\n");
}
ctxt->intSubName = name;
SKIP_BLANKS;
/*
* Check for SystemID and ExternalID
*/
URI = xmlParseExternalID(ctxt, &ExternalID, 1);
if ((URI != NULL) || (ExternalID != NULL)) {
ctxt->hasExternalSubset = 1;
}
ctxt->extSubURI = URI;
ctxt->extSubSystem = ExternalID;
SKIP_BLANKS;
/*
* Create and update the internal subset.
*/
if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) &&
(!ctxt->disableSAX))
ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI);
if (ctxt->instate == XML_PARSER_EOF)
return;
/*
* Is there any internal subset declarations ?
* they are handled separately in xmlParseInternalSubset()
*/
if (RAW == '[')
return;
/*
* We should be at the end of the DOCTYPE declaration.
*/
if (RAW != '>') {
xmlFatalErr(ctxt, XML_ERR_DOCTYPE_NOT_FINISHED, NULL);
}
NEXT;
}
| 171,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1) - 1;
defaultoptions(&h);
lua_settop(L, 2);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
luaL_checkstack(L, 1, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res);
break;
}
case 'x': {
break;
}
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f);
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d);
break;
}
case 'c': {
if (size == 0) {
if (!lua_isnumber(L, -1))
luaL_error(L, "format `c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
}
lua_pushlstring(L, data+pos, size);
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1);
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1);
return lua_gettop(L) - 2;
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190 | static int b_unpack (lua_State *L) {
Header h;
const char *fmt = luaL_checkstring(L, 1);
size_t ld;
const char *data = luaL_checklstring(L, 2, &ld);
size_t pos = luaL_optinteger(L, 3, 1) - 1;
int n = 0; /* number of results */
defaultoptions(&h);
while (*fmt) {
int opt = *fmt++;
size_t size = optsize(L, opt, &fmt);
pos += gettoalign(pos, &h, opt, size);
luaL_argcheck(L, pos+size <= ld, 2, "data string too short");
/* stack space for item + next position */
luaL_checkstack(L, 2, "too many results");
switch (opt) {
case 'b': case 'B': case 'h': case 'H':
case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */
int issigned = islower(opt);
lua_Number res = getinteger(data+pos, h.endian, issigned, size);
lua_pushnumber(L, res); n++;
break;
}
case 'x': {
break;
}
case 'f': {
float f;
memcpy(&f, data+pos, size);
correctbytes((char *)&f, sizeof(f), h.endian);
lua_pushnumber(L, f); n++;
break;
}
case 'd': {
double d;
memcpy(&d, data+pos, size);
correctbytes((char *)&d, sizeof(d), h.endian);
lua_pushnumber(L, d); n++;
break;
}
case 'c': {
if (size == 0) {
if (n == 0 || !lua_isnumber(L, -1))
luaL_error(L, "format 'c0' needs a previous size");
size = lua_tonumber(L, -1);
lua_pop(L, 1); n--;
luaL_argcheck(L, size <= ld && pos <= ld - size,
2, "data string too short");
}
lua_pushlstring(L, data+pos, size); n++;
break;
}
case 's': {
const char *e = (const char *)memchr(data+pos, '\0', ld - pos);
if (e == NULL)
luaL_error(L, "unfinished string in data");
size = (e - (data+pos)) + 1;
lua_pushlstring(L, data+pos, size - 1); n++;
break;
}
default: controloptions(L, opt, &fmt, &h);
}
pos += size;
}
lua_pushinteger(L, pos + 1); /* next position */
return n + 1;
}
| 170,163 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 virtio_gpu_object_create(struct virtio_gpu_device *vgdev,
unsigned long size, bool kernel, bool pinned,
struct virtio_gpu_object **bo_ptr)
{
struct virtio_gpu_object *bo;
enum ttm_bo_type type;
size_t acc_size;
int ret;
if (kernel)
type = ttm_bo_type_kernel;
else
type = ttm_bo_type_device;
*bo_ptr = NULL;
acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size,
sizeof(struct virtio_gpu_object));
bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
size = roundup(size, PAGE_SIZE);
ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size);
if (ret != 0)
return ret;
bo->dumb = false;
virtio_gpu_init_ttm_placement(bo, pinned);
ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type,
&bo->placement, 0, !kernel, NULL, acc_size,
NULL, NULL, &virtio_gpu_ttm_bo_destroy);
/* ttm_bo_init failure will call the destroy */
if (ret != 0)
return ret;
*bo_ptr = bo;
return 0;
}
Commit Message: drm/virtio: don't leak bo on drm_gem_object_init failure
Reported-by: 李强 <[email protected]>
Signed-off-by: Gerd Hoffmann <[email protected]>
Link: http://patchwork.freedesktop.org/patch/msgid/[email protected]
CWE ID: CWE-772 | int virtio_gpu_object_create(struct virtio_gpu_device *vgdev,
unsigned long size, bool kernel, bool pinned,
struct virtio_gpu_object **bo_ptr)
{
struct virtio_gpu_object *bo;
enum ttm_bo_type type;
size_t acc_size;
int ret;
if (kernel)
type = ttm_bo_type_kernel;
else
type = ttm_bo_type_device;
*bo_ptr = NULL;
acc_size = ttm_bo_dma_acc_size(&vgdev->mman.bdev, size,
sizeof(struct virtio_gpu_object));
bo = kzalloc(sizeof(struct virtio_gpu_object), GFP_KERNEL);
if (bo == NULL)
return -ENOMEM;
size = roundup(size, PAGE_SIZE);
ret = drm_gem_object_init(vgdev->ddev, &bo->gem_base, size);
if (ret != 0) {
kfree(bo);
return ret;
}
bo->dumb = false;
virtio_gpu_init_ttm_placement(bo, pinned);
ret = ttm_bo_init(&vgdev->mman.bdev, &bo->tbo, size, type,
&bo->placement, 0, !kernel, NULL, acc_size,
NULL, NULL, &virtio_gpu_ttm_bo_destroy);
/* ttm_bo_init failure will call the destroy */
if (ret != 0)
return ret;
*bo_ptr = bo;
return 0;
}
| 168,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC)
{
sapi_header_struct sapi_header;
char *colon_offset;
char *header_line;
uint header_line_len;
int http_response_code;
if (SG(headers_sent) && !SG(request_info).no_headers) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)",
output_start_filename, output_start_lineno);
} else {
sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent");
}
return FAILURE;
}
switch (op) {
case SAPI_HEADER_SET_STATUS:
sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC);
return SUCCESS;
case SAPI_HEADER_ADD:
case SAPI_HEADER_REPLACE:
case SAPI_HEADER_DELETE: {
sapi_header_line *p = arg;
if (!p->line || !p->line_len) {
return FAILURE;
}
header_line = p->line;
header_line_len = p->line_len;
http_response_code = p->response_code;
break;
}
case SAPI_HEADER_DELETE_ALL:
if (sapi_module.header_handler) {
sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
}
zend_llist_clean(&SG(sapi_headers).headers);
return SUCCESS;
default:
return FAILURE;
}
header_line = estrndup(header_line, header_line_len);
/* cut off trailing spaces, linefeeds and carriage-returns */
if (header_line_len && isspace(header_line[header_line_len-1])) {
do {
header_line_len--;
} while(header_line_len && isspace(header_line[header_line_len-1]));
header_line[header_line_len]='\0';
}
if (op == SAPI_HEADER_DELETE) {
if (strchr(header_line, ':')) {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon.");
return FAILURE;
}
if (sapi_module.header_handler) {
sapi_header.header = header_line;
sapi_header.header_len = header_line_len;
sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
}
sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len);
efree(header_line);
return SUCCESS;
} else {
/* new line/NUL character safety check */
int i;
for (i = 0; i < header_line_len; i++) {
/* RFC 2616 allows new lines if followed by SP or HT */
int illegal_break =
(header_line[i+1] != ' ' && header_line[i+1] != '\t')
&& (
header_line[i] == '\n'
|| (header_line[i] == '\r' && header_line[i+1] != '\n'));
if (illegal_break) {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header may not contain "
"more than a single header, new line detected");
return FAILURE;
}
if (header_line[i] == '\0') {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes");
return FAILURE;
}
}
}
sapi_header.header = header_line;
sapi_header.header_len = header_line_len;
/* Check the header for a few cases that we have special support for in SAPI */
if (header_line_len>=5
&& !strncasecmp(header_line, "HTTP/", 5)) {
/* filter out the response code */
sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC);
/* sapi_update_response_code doesn't free the status line if the code didn't change */
if (SG(sapi_headers).http_status_line) {
efree(SG(sapi_headers).http_status_line);
}
SG(sapi_headers).http_status_line = header_line;
return SUCCESS;
} else {
colon_offset = strchr(header_line, ':');
if (colon_offset) {
*colon_offset = 0;
if (!STRCASECMP(header_line, "Content-Type")) {
char *ptr = colon_offset+1, *mimetype = NULL, *newheader;
size_t len = header_line_len - (ptr - header_line), newlen;
while (*ptr == ' ') {
ptr++;
len--;
}
/* Disable possible output compression for images */
if (!strncmp(ptr, "image/", sizeof("image/")-1)) {
zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
mimetype = estrdup(ptr);
newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC);
if (!SG(sapi_headers).mimetype){
SG(sapi_headers).mimetype = estrdup(mimetype);
}
if (newlen != 0) {
newlen += sizeof("Content-type: ");
newheader = emalloc(newlen);
PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1);
strlcat(newheader, mimetype, newlen);
sapi_header.header = newheader;
sapi_header.header_len = newlen - 1;
efree(header_line);
}
efree(mimetype);
SG(sapi_headers).send_default_content_type = 0;
} else if (!STRCASECMP(header_line, "Content-Length")) {
/* Script is setting Content-length. The script cannot reasonably
* know the size of the message body after compression, so it's best
* do disable compression altogether. This contributes to making scripts
* portable between setups that have and don't have zlib compression
* enabled globally. See req #44164 */
zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"),
"0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
} else if (!STRCASECMP(header_line, "Location")) {
if ((SG(sapi_headers).http_response_code < 300 ||
SG(sapi_headers).http_response_code > 399) &&
SG(sapi_headers).http_response_code != 201) {
/* Return a Found Redirect if one is not already specified */
if (http_response_code) { /* user specified redirect code */
sapi_update_response_code(http_response_code TSRMLS_CC);
} else if (SG(request_info).proto_num > 1000 &&
SG(request_info).request_method &&
strcmp(SG(request_info).request_method, "HEAD") &&
strcmp(SG(request_info).request_method, "GET")) {
sapi_update_response_code(303 TSRMLS_CC);
} else {
sapi_update_response_code(302 TSRMLS_CC);
}
}
} else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */
sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */
}
if (sapi_header.header==header_line) {
*colon_offset = ':';
}
}
}
if (http_response_code) {
sapi_update_response_code(http_response_code TSRMLS_CC);
}
sapi_header_add_op(op, &sapi_header TSRMLS_CC);
return SUCCESS;
}
Commit Message: Update header handling to RFC 7230
CWE ID: CWE-79 | SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC)
{
sapi_header_struct sapi_header;
char *colon_offset;
char *header_line;
uint header_line_len;
int http_response_code;
if (SG(headers_sent) && !SG(request_info).no_headers) {
const char *output_start_filename = php_output_get_start_filename(TSRMLS_C);
int output_start_lineno = php_output_get_start_lineno(TSRMLS_C);
if (output_start_filename) {
sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)",
output_start_filename, output_start_lineno);
} else {
sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent");
}
return FAILURE;
}
switch (op) {
case SAPI_HEADER_SET_STATUS:
sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC);
return SUCCESS;
case SAPI_HEADER_ADD:
case SAPI_HEADER_REPLACE:
case SAPI_HEADER_DELETE: {
sapi_header_line *p = arg;
if (!p->line || !p->line_len) {
return FAILURE;
}
header_line = p->line;
header_line_len = p->line_len;
http_response_code = p->response_code;
break;
}
case SAPI_HEADER_DELETE_ALL:
if (sapi_module.header_handler) {
sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
}
zend_llist_clean(&SG(sapi_headers).headers);
return SUCCESS;
default:
return FAILURE;
}
header_line = estrndup(header_line, header_line_len);
/* cut off trailing spaces, linefeeds and carriage-returns */
if (header_line_len && isspace(header_line[header_line_len-1])) {
do {
header_line_len--;
} while(header_line_len && isspace(header_line[header_line_len-1]));
header_line[header_line_len]='\0';
}
if (op == SAPI_HEADER_DELETE) {
if (strchr(header_line, ':')) {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon.");
return FAILURE;
}
if (sapi_module.header_handler) {
sapi_header.header = header_line;
sapi_header.header_len = header_line_len;
sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC);
}
sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len);
efree(header_line);
return SUCCESS;
} else {
/* new line/NUL character safety check */
int i;
for (i = 0; i < header_line_len; i++) {
/* RFC 7230 ch. 3.2.4 deprecates folding support */
if (header_line[i] == '\n' || header_line[i] == '\r') {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header may not contain "
"more than a single header, new line detected");
return FAILURE;
}
if (header_line[i] == '\0') {
efree(header_line);
sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes");
return FAILURE;
}
}
}
sapi_header.header = header_line;
sapi_header.header_len = header_line_len;
/* Check the header for a few cases that we have special support for in SAPI */
if (header_line_len>=5
&& !strncasecmp(header_line, "HTTP/", 5)) {
/* filter out the response code */
sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC);
/* sapi_update_response_code doesn't free the status line if the code didn't change */
if (SG(sapi_headers).http_status_line) {
efree(SG(sapi_headers).http_status_line);
}
SG(sapi_headers).http_status_line = header_line;
return SUCCESS;
} else {
colon_offset = strchr(header_line, ':');
if (colon_offset) {
*colon_offset = 0;
if (!STRCASECMP(header_line, "Content-Type")) {
char *ptr = colon_offset+1, *mimetype = NULL, *newheader;
size_t len = header_line_len - (ptr - header_line), newlen;
while (*ptr == ' ') {
ptr++;
len--;
}
/* Disable possible output compression for images */
if (!strncmp(ptr, "image/", sizeof("image/")-1)) {
zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"), "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
}
mimetype = estrdup(ptr);
newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC);
if (!SG(sapi_headers).mimetype){
SG(sapi_headers).mimetype = estrdup(mimetype);
}
if (newlen != 0) {
newlen += sizeof("Content-type: ");
newheader = emalloc(newlen);
PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1);
strlcat(newheader, mimetype, newlen);
sapi_header.header = newheader;
sapi_header.header_len = newlen - 1;
efree(header_line);
}
efree(mimetype);
SG(sapi_headers).send_default_content_type = 0;
} else if (!STRCASECMP(header_line, "Content-Length")) {
/* Script is setting Content-length. The script cannot reasonably
* know the size of the message body after compression, so it's best
* do disable compression altogether. This contributes to making scripts
* portable between setups that have and don't have zlib compression
* enabled globally. See req #44164 */
zend_alter_ini_entry("zlib.output_compression", sizeof("zlib.output_compression"),
"0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
} else if (!STRCASECMP(header_line, "Location")) {
if ((SG(sapi_headers).http_response_code < 300 ||
SG(sapi_headers).http_response_code > 399) &&
SG(sapi_headers).http_response_code != 201) {
/* Return a Found Redirect if one is not already specified */
if (http_response_code) { /* user specified redirect code */
sapi_update_response_code(http_response_code TSRMLS_CC);
} else if (SG(request_info).proto_num > 1000 &&
SG(request_info).request_method &&
strcmp(SG(request_info).request_method, "HEAD") &&
strcmp(SG(request_info).request_method, "GET")) {
sapi_update_response_code(303 TSRMLS_CC);
} else {
sapi_update_response_code(302 TSRMLS_CC);
}
}
} else if (!STRCASECMP(header_line, "WWW-Authenticate")) { /* HTTP Authentication */
sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */
}
if (sapi_header.header==header_line) {
*colon_offset = ':';
}
}
}
if (http_response_code) {
sapi_update_response_code(http_response_code TSRMLS_CC);
}
sapi_header_add_op(op, &sapi_header TSRMLS_CC);
return SUCCESS;
}
| 167,472 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[20];
sprintf(key, "a=framesize:%lu", PT);
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
Commit Message: Fix corruption via buffer overflow in mediaserver
change unbound sprintf() to snprintf() so network-provided values
can't overflow the buffers.
Applicable to all K/L/M/N branches.
Bug: 25747670
Change-Id: Id6a5120c2d08a6fbbd47deffb680ecf82015f4f6
CWE ID: CWE-284 | bool ASessionDescription::getDimensions(
size_t index, unsigned long PT,
int32_t *width, int32_t *height) const {
*width = 0;
*height = 0;
char key[33];
snprintf(key, sizeof(key), "a=framesize:%lu", PT);
if (PT > 9999999) {
android_errorWriteLog(0x534e4554, "25747670");
}
AString value;
if (!findAttribute(index, key, &value)) {
return false;
}
const char *s = value.c_str();
char *end;
*width = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '-');
s = end + 1;
*height = strtoul(s, &end, 10);
CHECK_GT(end, s);
CHECK_EQ(*end, '\0');
return true;
}
| 173,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: long Chapters::Parse()
{
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start; // payload start
const long long stop = pos + m_size; // payload stop
while (pos < stop)
{
long long id, size;
long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x05B9) // EditionEntry ID
{
status = ParseEdition(pos, size);
if (status < 0) // error
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Chapters::Parse()
if (status < 0) // error
return status;
}
pos += size;
assert(pos <= stop);
}
assert(pos == stop);
return 0;
}
| 174,400 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SendAutomationJSONRequest(AutomationMessageSender* sender,
const DictionaryValue& request_dict,
DictionaryValue* reply_dict,
std::string* error_msg) {
std::string request, reply;
base::JSONWriter::Write(&request_dict, false, &request);
bool success = false;
int timeout_ms = TestTimeouts::action_max_timeout_ms();
base::Time before_sending = base::Time::Now();
if (!SendAutomationJSONRequest(
sender, request, timeout_ms, &reply, &success)) {
int64 elapsed_ms = (base::Time::Now() - before_sending).InMilliseconds();
std::string command;
request_dict.GetString("command", &command);
if (elapsed_ms >= timeout_ms) {
*error_msg = base::StringPrintf(
"Chrome did not respond to '%s'. Request may have timed out. "
"Elapsed time was %" PRId64 " ms. Request timeout was %d ms. "
"Request details: (%s).",
command.c_str(),
elapsed_ms,
timeout_ms,
request.c_str());
} else {
*error_msg = base::StringPrintf(
"Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. "
"Request details: (%s).",
command.c_str(),
elapsed_ms,
request.c_str());
}
return false;
}
scoped_ptr<Value> value(base::JSONReader::Read(reply, true));
if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) {
std::string command;
request_dict.GetString("command", &command);
LOG(ERROR) << "JSON request did not return dict: " << command << "\n";
return false;
}
DictionaryValue* dict = static_cast<DictionaryValue*>(value.get());
if (!success) {
std::string command, error;
request_dict.GetString("command", &command);
dict->GetString("error", &error);
*error_msg = base::StringPrintf(
"Internal Chrome error during '%s': (%s). Request details: (%s).",
command.c_str(),
error.c_str(),
request.c_str());
LOG(ERROR) << "JSON request failed: " << command << "\n"
<< " with error: " << error;
return false;
}
reply_dict->MergeDictionary(dict);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool SendAutomationJSONRequest(AutomationMessageSender* sender,
const DictionaryValue& request_dict,
DictionaryValue* reply_dict,
std::string* error_msg) {
std::string request, reply;
base::JSONWriter::Write(&request_dict, false, &request);
std::string command;
request_dict.GetString("command", &command);
LOG(INFO) << "Sending '" << command << "' command.";
base::Time before_sending = base::Time::Now();
bool success = false;
if (!SendAutomationJSONRequestWithDefaultTimeout(
sender, request, &reply, &success)) {
*error_msg = base::StringPrintf(
"Chrome did not respond to '%s'. Elapsed time was %" PRId64 " ms. "
"Request details: (%s).",
command.c_str(),
(base::Time::Now() - before_sending).InMilliseconds(),
request.c_str());
return false;
}
scoped_ptr<Value> value(base::JSONReader::Read(reply, true));
if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) {
LOG(ERROR) << "JSON request did not return dict: " << command << "\n";
return false;
}
DictionaryValue* dict = static_cast<DictionaryValue*>(value.get());
if (!success) {
std::string error;
dict->GetString("error", &error);
*error_msg = base::StringPrintf(
"Internal Chrome error during '%s': (%s). Request details: (%s).",
command.c_str(),
error.c_str(),
request.c_str());
LOG(ERROR) << "JSON request failed: " << command << "\n"
<< " with error: " << error;
return false;
}
reply_dict->MergeDictionary(dict);
return true;
}
| 170,451 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string DataUseUserData::GetServiceNameAsString(ServiceName service_name) {
switch (service_name) {
case SUGGESTIONS:
return "Suggestions";
case NOT_TAGGED:
return "NotTagged";
case TRANSLATE:
return "Translate";
case SYNC:
return "Sync";
case OMNIBOX:
return "Omnibox";
case INVALIDATION:
return "Invalidation";
case RAPPOR:
return "Rappor";
case VARIATIONS:
return "Variations";
case UMA:
return "UMA";
case DOMAIN_RELIABILITY:
return "DomainReliability";
case PROFILE_DOWNLOADER:
return "ProfileDownloader";
case GOOGLE_URL_TRACKER:
return "GoogleURLTracker";
case AUTOFILL:
return "Autofill";
case POLICY:
return "Policy";
case SPELL_CHECKER:
return "SpellChecker";
case NTP_SNIPPETS:
return "NTPSnippets";
case SAFE_BROWSING:
return "SafeBrowsing";
case DATA_REDUCTION_PROXY:
return "DataReductionProxy";
case PRECACHE:
return "Precache";
case NTP_TILES:
return "NTPTiles";
case FEEDBACK_UPLOADER:
return "FeedbackUploader";
case TRACING_UPLOADER:
return "TracingUploader";
case DOM_DISTILLER:
return "DOMDistiller";
case CLOUD_PRINT:
return "CloudPrint";
case SEARCH_PROVIDER_LOGOS:
return "SearchProviderLogos";
case UPDATE_CLIENT:
return "UpdateClient";
case GCM_DRIVER:
return "GCMDriver";
case WEB_HISTORY_SERVICE:
return "WebHistoryService";
case NETWORK_TIME_TRACKER:
return "NetworkTimeTracker";
case SUPERVISED_USER:
return "SupervisedUser";
case IMAGE_FETCHER_UNTAGGED:
return "ImageFetcherUntagged";
case GAIA:
return "GAIA";
}
return "INVALID";
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190 | std::string DataUseUserData::GetServiceNameAsString(ServiceName service_name) {
switch (service_name) {
case SUGGESTIONS:
return "Suggestions";
case NOT_TAGGED:
return "NotTagged";
case TRANSLATE:
return "Translate";
case SYNC:
return "Sync";
case OMNIBOX:
return "Omnibox";
case INVALIDATION:
return "Invalidation";
case RAPPOR:
return "Rappor";
case VARIATIONS:
return "Variations";
case UMA:
return "UMA";
case DOMAIN_RELIABILITY:
return "DomainReliability";
case PROFILE_DOWNLOADER:
return "ProfileDownloader";
case GOOGLE_URL_TRACKER:
return "GoogleURLTracker";
case AUTOFILL:
return "Autofill";
case POLICY:
return "Policy";
case SPELL_CHECKER:
return "SpellChecker";
case NTP_SNIPPETS:
return "NTPSnippets";
case SAFE_BROWSING:
return "SafeBrowsing";
case DATA_REDUCTION_PROXY:
return "DataReductionProxy";
case PRECACHE:
return "Precache";
case NTP_TILES:
return "NTPTiles";
case FEEDBACK_UPLOADER:
return "FeedbackUploader";
case TRACING_UPLOADER:
return "TracingUploader";
case DOM_DISTILLER:
return "DOMDistiller";
case CLOUD_PRINT:
return "CloudPrint";
case SEARCH_PROVIDER_LOGOS:
return "SearchProviderLogos";
case UPDATE_CLIENT:
return "UpdateClient";
case GCM_DRIVER:
return "GCMDriver";
case WEB_HISTORY_SERVICE:
return "WebHistoryService";
case NETWORK_TIME_TRACKER:
return "NetworkTimeTracker";
case SUPERVISED_USER:
return "SupervisedUser";
case IMAGE_FETCHER_UNTAGGED:
return "ImageFetcherUntagged";
case GAIA:
return "GAIA";
case CAPTIVE_PORTAL:
return "CaptivePortal";
case WEB_RESOURCE_SERVICE:
return "WebResourceService";
case SIGNIN:
return "Signin";
}
return "INVALID";
}
| 172,018 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CStarter::removeDeferredJobs() {
bool ret = true;
if ( this->deferral_tid == -1 ) {
return ( ret );
}
m_deferred_job_update = true;
if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) {
dprintf( D_FULLDEBUG, "Cancelled time deferred execution for "
"Job %d.%d\n",
this->jic->jobCluster(),
this->jic->jobProc() );
this->deferral_tid = -1;
} else {
MyString error = "Failed to cancel deferred execution timer for Job ";
error += this->jic->jobCluster();
error += ".";
error += this->jic->jobProc();
EXCEPT( error.Value() );
ret = false;
}
return ( ret );
}
Commit Message:
CWE ID: CWE-134 | CStarter::removeDeferredJobs() {
bool ret = true;
if ( this->deferral_tid == -1 ) {
return ( ret );
}
m_deferred_job_update = true;
if ( daemonCore->Cancel_Timer( this->deferral_tid ) >= 0 ) {
dprintf( D_FULLDEBUG, "Cancelled time deferred execution for "
"Job %d.%d\n",
this->jic->jobCluster(),
this->jic->jobProc() );
this->deferral_tid = -1;
} else {
MyString error = "Failed to cancel deferred execution timer for Job ";
error += this->jic->jobCluster();
error += ".";
error += this->jic->jobProc();
EXCEPT( "%s", error.Value() );
ret = false;
}
return ( ret );
}
| 165,379 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int init_ssl_connection(SSL *con)
{
int i;
const char *str;
X509 *peer;
long verify_error;
MS_STATIC char buf[BUFSIZ];
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
const unsigned char *next_proto_neg;
unsigned next_proto_neg_len;
#endif
unsigned char *exportedkeymat;
i = SSL_accept(con);
#ifdef CERT_CB_TEST_RETRY
{
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
&& SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
fprintf(stderr,
"LOOKUP from certificate callback during accept\n");
i = SSL_accept(con);
}
}
#endif
#ifndef OPENSSL_NO_SRP
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
return (1);
}
BIO_printf(bio_err, "ERROR\n");
verify_error = SSL_get_verify_result(con);
if (verify_error != X509_V_OK) {
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
}
/* Always print any error messages */
ERR_print_errors(bio_err);
return (0);
}
if (s_brief)
print_ssl_summary(bio_err, con);
PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(bio_s_out, "Client certificate\n");
PEM_write_bio_X509(bio_s_out, peer);
X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "subject=%s\n", buf);
X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "issuer=%s\n", buf);
X509_free(peer);
}
if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
ssl_print_sigalgs(bio_s_out, con);
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_s_out, con);
ssl_print_curves(bio_s_out, con, 0);
#endif
BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
if (next_proto_neg) {
BIO_printf(bio_s_out, "NEXTPROTO is ");
BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
BIO_printf(bio_s_out, "\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile
= SSL_get_selected_srtp_profile(con);
if (srtp_profile)
BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
if (SSL_cache_hit(con))
BIO_printf(bio_s_out, "Reused session-id\n");
if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
TLS1_FLAGS_TLS_PADDING_BUG)
BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
#ifndef OPENSSL_NO_KRB5
client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
if (client_princ != NULL) {
BIO_printf(bio_s_out, "Kerberos peer principal is %s\n",
client_princ);
}
#endif /* OPENSSL_NO_KRB5 */
BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
if (keymatexportlabel != NULL) {
BIO_printf(bio_s_out, "Keying material exporter:\n");
BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(con, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio_s_out, " Error\n");
} else {
BIO_printf(bio_s_out, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
BIO_printf(bio_s_out, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
return (1);
}
Commit Message:
CWE ID: CWE-399 | static int init_ssl_connection(SSL *con)
{
int i;
const char *str;
X509 *peer;
long verify_error;
MS_STATIC char buf[BUFSIZ];
#ifndef OPENSSL_NO_KRB5
char *client_princ;
#endif
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
const unsigned char *next_proto_neg;
unsigned next_proto_neg_len;
#endif
unsigned char *exportedkeymat;
i = SSL_accept(con);
#ifdef CERT_CB_TEST_RETRY
{
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP
&& SSL_state(con) == SSL3_ST_SR_CLNT_HELLO_C) {
fprintf(stderr,
"LOOKUP from certificate callback during accept\n");
i = SSL_accept(con);
}
}
#endif
#ifndef OPENSSL_NO_SRP
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
srp_callback_parm.user =
SRP_VBASE_get_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) {
BIO_printf(bio_s_out, "LOOKUP during accept %s\n",
srp_callback_parm.login);
SRP_user_pwd_free(srp_callback_parm.user);
srp_callback_parm.user =
SRP_VBASE_get1_by_user(srp_callback_parm.vb,
srp_callback_parm.login);
if (srp_callback_parm.user)
BIO_printf(bio_s_out, "LOOKUP done %s\n",
srp_callback_parm.user->info);
return (1);
}
BIO_printf(bio_err, "ERROR\n");
verify_error = SSL_get_verify_result(con);
if (verify_error != X509_V_OK) {
BIO_printf(bio_err, "verify error:%s\n",
X509_verify_cert_error_string(verify_error));
}
/* Always print any error messages */
ERR_print_errors(bio_err);
return (0);
}
if (s_brief)
print_ssl_summary(bio_err, con);
PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con));
peer = SSL_get_peer_certificate(con);
if (peer != NULL) {
BIO_printf(bio_s_out, "Client certificate\n");
PEM_write_bio_X509(bio_s_out, peer);
X509_NAME_oneline(X509_get_subject_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "subject=%s\n", buf);
X509_NAME_oneline(X509_get_issuer_name(peer), buf, sizeof buf);
BIO_printf(bio_s_out, "issuer=%s\n", buf);
X509_free(peer);
}
if (SSL_get_shared_ciphers(con, buf, sizeof buf) != NULL)
BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf);
str = SSL_CIPHER_get_name(SSL_get_current_cipher(con));
ssl_print_sigalgs(bio_s_out, con);
#ifndef OPENSSL_NO_EC
ssl_print_point_formats(bio_s_out, con);
ssl_print_curves(bio_s_out, con, 0);
#endif
BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)");
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len);
if (next_proto_neg) {
BIO_printf(bio_s_out, "NEXTPROTO is ");
BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len);
BIO_printf(bio_s_out, "\n");
}
#endif
#ifndef OPENSSL_NO_SRTP
{
SRTP_PROTECTION_PROFILE *srtp_profile
= SSL_get_selected_srtp_profile(con);
if (srtp_profile)
BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n",
srtp_profile->name);
}
#endif
if (SSL_cache_hit(con))
BIO_printf(bio_s_out, "Reused session-id\n");
if (SSL_ctrl(con, SSL_CTRL_GET_FLAGS, 0, NULL) &
TLS1_FLAGS_TLS_PADDING_BUG)
BIO_printf(bio_s_out, "Peer has incorrect TLSv1 block padding\n");
#ifndef OPENSSL_NO_KRB5
client_princ = kssl_ctx_get0_client_princ(SSL_get0_kssl_ctx(con));
if (client_princ != NULL) {
BIO_printf(bio_s_out, "Kerberos peer principal is %s\n",
client_princ);
}
#endif /* OPENSSL_NO_KRB5 */
BIO_printf(bio_s_out, "Secure Renegotiation IS%s supported\n",
SSL_get_secure_renegotiation_support(con) ? "" : " NOT");
if (keymatexportlabel != NULL) {
BIO_printf(bio_s_out, "Keying material exporter:\n");
BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel);
BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen);
exportedkeymat = OPENSSL_malloc(keymatexportlen);
if (exportedkeymat != NULL) {
if (!SSL_export_keying_material(con, exportedkeymat,
keymatexportlen,
keymatexportlabel,
strlen(keymatexportlabel),
NULL, 0, 0)) {
BIO_printf(bio_s_out, " Error\n");
} else {
BIO_printf(bio_s_out, " Keying material: ");
for (i = 0; i < keymatexportlen; i++)
BIO_printf(bio_s_out, "%02X", exportedkeymat[i]);
BIO_printf(bio_s_out, "\n");
}
OPENSSL_free(exportedkeymat);
}
}
return (1);
}
| 165,247 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl)
{
struct scm_fp_list *new_fpl;
int i;
if (!fpl)
return NULL;
new_fpl = kmemdup(fpl, offsetof(struct scm_fp_list, fp[fpl->count]),
GFP_KERNEL);
if (new_fpl) {
for (i = 0; i < fpl->count; i++)
get_file(fpl->fp[i]);
new_fpl->max = new_fpl->count;
}
return new_fpl;
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl)
{
struct scm_fp_list *new_fpl;
int i;
if (!fpl)
return NULL;
new_fpl = kmemdup(fpl, offsetof(struct scm_fp_list, fp[fpl->count]),
GFP_KERNEL);
if (new_fpl) {
for (i = 0; i < fpl->count; i++)
get_file(fpl->fp[i]);
new_fpl->max = new_fpl->count;
new_fpl->user = get_uid(fpl->user);
}
return new_fpl;
}
| 167,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, size_t * out_len)
{
size_t in_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
in_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
in_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
in_len = in[2] * 0x100;
in_len += in[3];
i = 5;
}
else {
return -1;
}
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], in_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[in_len - 2] && (in_len - 2 > 0))
in_len--;
if (2 == in_len)
return -1;
memcpy(out, plaintext, in_len - 2);
*out_len = in_len - 2;
return 0;
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, size_t * out_len)
decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len)
{
size_t cipher_len;
size_t i;
unsigned char iv[16] = { 0 };
unsigned char plaintext[4096] = { 0 };
epass2003_exdata *exdata = NULL;
if (!card->drv_data)
return SC_ERROR_INVALID_ARGUMENTS;
exdata = (epass2003_exdata *)card->drv_data;
/* no cipher */
if (in[0] == 0x99)
return 0;
/* parse cipher length */
if (0x01 == in[2] && 0x82 != in[1]) {
cipher_len = in[1];
i = 3;
}
else if (0x01 == in[3] && 0x81 == in[1]) {
cipher_len = in[2];
i = 4;
}
else if (0x01 == in[4] && 0x82 == in[1]) {
cipher_len = in[2] * 0x100;
cipher_len += in[3];
i = 5;
}
else {
return -1;
}
if (cipher_len < 2 || i+cipher_len > inlen || cipher_len > sizeof plaintext)
return -1;
/* decrypt */
if (KEY_TYPE_AES == exdata->smtype)
aes128_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
else
des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext);
/* unpadding */
while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0))
cipher_len--;
if (2 == cipher_len)
return -1;
memcpy(out, plaintext, cipher_len - 2);
*out_len = cipher_len - 2;
return 0;
}
| 169,054 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadProfileLong(const EndianType endian,
unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,945 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
u32 rmr, u64 to,
u32 xdr_off, int write_len,
struct svc_rdma_req_map *vec)
{
struct ib_rdma_wr write_wr;
struct ib_sge *sge;
int xdr_sge_no;
int sge_no;
int sge_bytes;
int sge_off;
int bc;
struct svc_rdma_op_ctxt *ctxt;
if (vec->count > RPCSVC_MAXPAGES) {
pr_err("svcrdma: Too many pages (%lu)\n", vec->count);
return -EIO;
}
dprintk("svcrdma: RDMA_WRITE rmr=%x, to=%llx, xdr_off=%d, "
"write_len=%d, vec->sge=%p, vec->count=%lu\n",
rmr, (unsigned long long)to, xdr_off,
write_len, vec->sge, vec->count);
ctxt = svc_rdma_get_context(xprt);
ctxt->direction = DMA_TO_DEVICE;
sge = ctxt->sge;
/* Find the SGE associated with xdr_off */
for (bc = xdr_off, xdr_sge_no = 1; bc && xdr_sge_no < vec->count;
xdr_sge_no++) {
if (vec->sge[xdr_sge_no].iov_len > bc)
break;
bc -= vec->sge[xdr_sge_no].iov_len;
}
sge_off = bc;
bc = write_len;
sge_no = 0;
/* Copy the remaining SGE */
while (bc != 0) {
sge_bytes = min_t(size_t,
bc, vec->sge[xdr_sge_no].iov_len-sge_off);
sge[sge_no].length = sge_bytes;
sge[sge_no].addr =
dma_map_xdr(xprt, &rqstp->rq_res, xdr_off,
sge_bytes, DMA_TO_DEVICE);
xdr_off += sge_bytes;
if (ib_dma_mapping_error(xprt->sc_cm_id->device,
sge[sge_no].addr))
goto err;
svc_rdma_count_mappings(xprt, ctxt);
sge[sge_no].lkey = xprt->sc_pd->local_dma_lkey;
ctxt->count++;
sge_off = 0;
sge_no++;
xdr_sge_no++;
if (xdr_sge_no > vec->count) {
pr_err("svcrdma: Too many sges (%d)\n", xdr_sge_no);
goto err;
}
bc -= sge_bytes;
if (sge_no == xprt->sc_max_sge)
break;
}
/* Prepare WRITE WR */
memset(&write_wr, 0, sizeof write_wr);
ctxt->cqe.done = svc_rdma_wc_write;
write_wr.wr.wr_cqe = &ctxt->cqe;
write_wr.wr.sg_list = &sge[0];
write_wr.wr.num_sge = sge_no;
write_wr.wr.opcode = IB_WR_RDMA_WRITE;
write_wr.wr.send_flags = IB_SEND_SIGNALED;
write_wr.rkey = rmr;
write_wr.remote_addr = to;
/* Post It */
atomic_inc(&rdma_stat_write);
if (svc_rdma_send(xprt, &write_wr.wr))
goto err;
return write_len - bc;
err:
svc_rdma_unmap_dma(ctxt);
svc_rdma_put_context(ctxt, 0);
return -EIO;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static int send_write(struct svcxprt_rdma *xprt, struct svc_rqst *rqstp,
static int svc_rdma_dma_map_page(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
unsigned int sge_no,
struct page *page,
unsigned int offset,
unsigned int len)
{
struct ib_device *dev = rdma->sc_cm_id->device;
dma_addr_t dma_addr;
dma_addr = ib_dma_map_page(dev, page, offset, len, DMA_TO_DEVICE);
if (ib_dma_mapping_error(dev, dma_addr))
return -EIO;
ctxt->sge[sge_no].addr = dma_addr;
ctxt->sge[sge_no].length = len;
ctxt->sge[sge_no].lkey = rdma->sc_pd->local_dma_lkey;
svc_rdma_count_mappings(rdma, ctxt);
return 0;
}
/**
* svc_rdma_map_reply_hdr - DMA map the transport header buffer
* @rdma: controlling transport
* @ctxt: op_ctxt for the Send WR
* @rdma_resp: buffer containing transport header
* @len: length of transport header
*
* Returns:
* %0 if the header is DMA mapped,
* %-EIO if DMA mapping failed.
*/
int svc_rdma_map_reply_hdr(struct svcxprt_rdma *rdma,
struct svc_rdma_op_ctxt *ctxt,
__be32 *rdma_resp,
unsigned int len)
{
ctxt->direction = DMA_TO_DEVICE;
ctxt->pages[0] = virt_to_page(rdma_resp);
ctxt->count = 1;
return svc_rdma_dma_map_page(rdma, ctxt, 0, ctxt->pages[0], 0, len);
}
| 168,169 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: oxide::BrowserContext* WebContext::GetContext() {
if (context_.get()) {
return context_.get();
}
DCHECK(construct_props_);
oxide::BrowserContext::Params params(
construct_props_->data_path,
construct_props_->cache_path,
construct_props_->max_cache_size_hint,
construct_props_->session_cookie_mode);
params.host_mapping_rules = construct_props_->host_mapping_rules;
context_ = oxide::BrowserContext::Create(params);
UserAgentSettings* ua_settings = UserAgentSettings::Get(context_.get());
if (!construct_props_->product.empty()) {
ua_settings->SetProduct(construct_props_->product);
}
if (!construct_props_->user_agent.empty()) {
ua_settings->SetUserAgent(construct_props_->user_agent);
}
if (!construct_props_->accept_langs.empty()) {
ua_settings->SetAcceptLangs(construct_props_->accept_langs);
}
ua_settings->SetUserAgentOverrides(construct_props_->user_agent_overrides);
ua_settings->SetLegacyUserAgentOverrideEnabled(
construct_props_->legacy_user_agent_override_enabled);
context_->SetCookiePolicy(construct_props_->cookie_policy);
context_->SetIsPopupBlockerEnabled(construct_props_->popup_blocker_enabled);
context_->SetDoNotTrack(construct_props_->do_not_track);
MediaCaptureDevicesContext* dc =
MediaCaptureDevicesContext::Get(context_.get());
if (!construct_props_->default_audio_capture_device_id.empty()) {
if (!dc->SetDefaultAudioDeviceId(
construct_props_->default_audio_capture_device_id)) {
client_->DefaultAudioCaptureDeviceChanged();
}
}
if (!construct_props_->default_video_capture_device_id.empty()) {
if (!dc->SetDefaultVideoDeviceId(
construct_props_->default_video_capture_device_id)) {
client_->DefaultVideoCaptureDeviceChanged();
}
}
dc->set_client(this);
DevToolsManager* devtools = DevToolsManager::Get(context_.get());
if (!construct_props_->devtools_ip.empty()) {
devtools->SetAddress(construct_props_->devtools_ip);
}
if (construct_props_->devtools_port != -1) {
devtools->SetPort(construct_props_->devtools_port);
}
devtools->SetEnabled(construct_props_->devtools_enabled);
context_->SetDelegate(delegate_.get());
construct_props_.reset();
UpdateUserScripts();
return context_.get();
}
Commit Message:
CWE ID: CWE-20 | oxide::BrowserContext* WebContext::GetContext() {
BrowserContext* WebContext::GetContext() {
if (context_.get()) {
return context_.get();
}
DCHECK(construct_props_);
BrowserContext::Params params(
construct_props_->data_path,
construct_props_->cache_path,
construct_props_->max_cache_size_hint,
construct_props_->session_cookie_mode);
params.host_mapping_rules = construct_props_->host_mapping_rules;
context_ = BrowserContext::Create(params);
UserAgentSettings* ua_settings = UserAgentSettings::Get(context_.get());
if (!construct_props_->product.empty()) {
ua_settings->SetProduct(construct_props_->product);
}
if (!construct_props_->user_agent.empty()) {
ua_settings->SetUserAgent(construct_props_->user_agent);
}
if (!construct_props_->accept_langs.empty()) {
ua_settings->SetAcceptLangs(construct_props_->accept_langs);
}
ua_settings->SetUserAgentOverrides(construct_props_->user_agent_overrides);
ua_settings->SetLegacyUserAgentOverrideEnabled(
construct_props_->legacy_user_agent_override_enabled);
context_->SetCookiePolicy(construct_props_->cookie_policy);
context_->SetIsPopupBlockerEnabled(construct_props_->popup_blocker_enabled);
context_->SetDoNotTrack(construct_props_->do_not_track);
MediaCaptureDevicesContext* dc =
MediaCaptureDevicesContext::Get(context_.get());
if (!construct_props_->default_audio_capture_device_id.empty()) {
if (!dc->SetDefaultAudioDeviceId(
construct_props_->default_audio_capture_device_id)) {
client_->DefaultAudioCaptureDeviceChanged();
}
}
if (!construct_props_->default_video_capture_device_id.empty()) {
if (!dc->SetDefaultVideoDeviceId(
construct_props_->default_video_capture_device_id)) {
client_->DefaultVideoCaptureDeviceChanged();
}
}
dc->set_client(this);
DevToolsManager* devtools = DevToolsManager::Get(context_.get());
if (!construct_props_->devtools_ip.empty()) {
devtools->SetAddress(construct_props_->devtools_ip);
}
if (construct_props_->devtools_port != -1) {
devtools->SetPort(construct_props_->devtools_port);
}
devtools->SetEnabled(construct_props_->devtools_enabled);
context_->SetDelegate(delegate_.get());
construct_props_.reset();
UpdateUserScripts();
return context_.get();
}
| 165,412 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: __be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | __be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
u32 id;
id = __ipv6_select_ident(net, daddr, saddr);
return htonl(id);
}
| 169,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
uint32_t guest_irq, bool set)
{
struct kvm_kernel_irq_routing_entry *e;
struct kvm_irq_routing_table *irq_rt;
struct kvm_lapic_irq irq;
struct kvm_vcpu *vcpu;
struct vcpu_data vcpu_info;
int idx, ret = -EINVAL;
if (!kvm_arch_has_assigned_device(kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(kvm->vcpus[0]))
return 0;
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
BUG_ON(guest_irq >= irq_rt->nr_rt_entries);
hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
if (e->type != KVM_IRQ_ROUTING_MSI)
continue;
/*
* VT-d PI cannot support posting multicast/broadcast
* interrupts to a vCPU, we still use interrupt remapping
* for these kind of interrupts.
*
* For lowest-priority interrupts, we only support
* those with single CPU as the destination, e.g. user
* configures the interrupts via /proc/irq or uses
* irqbalance to make the interrupts single-CPU.
*
* We will support full lowest-priority interrupt later.
*/
kvm_set_msi_irq(kvm, e, &irq);
if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
/*
* Make sure the IRTE is in remapped mode if
* we don't handle it in posted mode.
*/
ret = irq_set_vcpu_affinity(host_irq, NULL);
if (ret < 0) {
printk(KERN_INFO
"failed to back to remapped mode, irq: %u\n",
host_irq);
goto out;
}
continue;
}
vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
vcpu_info.vector = irq.vector;
trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
vcpu_info.vector, vcpu_info.pi_desc_addr, set);
if (set)
ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
else {
/* suppress notification event before unposting */
pi_set_sn(vcpu_to_pi_desc(vcpu));
ret = irq_set_vcpu_affinity(host_irq, NULL);
pi_clear_sn(vcpu_to_pi_desc(vcpu));
}
if (ret < 0) {
printk(KERN_INFO "%s: failed to update PI IRTE\n",
__func__);
goto out;
}
}
ret = 0;
out:
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
Commit Message: KVM: VMX: Do not BUG() on out-of-bounds guest IRQ
The value of the guest_irq argument to vmx_update_pi_irte() is
ultimately coming from a KVM_IRQFD API call. Do not BUG() in
vmx_update_pi_irte() if the value is out-of bounds. (Especially,
since KVM as a whole seems to hang after that.)
Instead, print a message only once if we find that we don't have a
route for a certain IRQ (which can be out-of-bounds or within the
array).
This fixes CVE-2017-1000252.
Fixes: efc644048ecde54 ("KVM: x86: Update IRTE for posted-interrupts")
Signed-off-by: Jan H. Schönherr <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20 | static int vmx_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
uint32_t guest_irq, bool set)
{
struct kvm_kernel_irq_routing_entry *e;
struct kvm_irq_routing_table *irq_rt;
struct kvm_lapic_irq irq;
struct kvm_vcpu *vcpu;
struct vcpu_data vcpu_info;
int idx, ret = 0;
if (!kvm_arch_has_assigned_device(kvm) ||
!irq_remapping_cap(IRQ_POSTING_CAP) ||
!kvm_vcpu_apicv_active(kvm->vcpus[0]))
return 0;
idx = srcu_read_lock(&kvm->irq_srcu);
irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
if (guest_irq >= irq_rt->nr_rt_entries ||
hlist_empty(&irq_rt->map[guest_irq])) {
pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
guest_irq, irq_rt->nr_rt_entries);
goto out;
}
hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
if (e->type != KVM_IRQ_ROUTING_MSI)
continue;
/*
* VT-d PI cannot support posting multicast/broadcast
* interrupts to a vCPU, we still use interrupt remapping
* for these kind of interrupts.
*
* For lowest-priority interrupts, we only support
* those with single CPU as the destination, e.g. user
* configures the interrupts via /proc/irq or uses
* irqbalance to make the interrupts single-CPU.
*
* We will support full lowest-priority interrupt later.
*/
kvm_set_msi_irq(kvm, e, &irq);
if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu)) {
/*
* Make sure the IRTE is in remapped mode if
* we don't handle it in posted mode.
*/
ret = irq_set_vcpu_affinity(host_irq, NULL);
if (ret < 0) {
printk(KERN_INFO
"failed to back to remapped mode, irq: %u\n",
host_irq);
goto out;
}
continue;
}
vcpu_info.pi_desc_addr = __pa(vcpu_to_pi_desc(vcpu));
vcpu_info.vector = irq.vector;
trace_kvm_pi_irte_update(vcpu->vcpu_id, host_irq, e->gsi,
vcpu_info.vector, vcpu_info.pi_desc_addr, set);
if (set)
ret = irq_set_vcpu_affinity(host_irq, &vcpu_info);
else {
/* suppress notification event before unposting */
pi_set_sn(vcpu_to_pi_desc(vcpu));
ret = irq_set_vcpu_affinity(host_irq, NULL);
pi_clear_sn(vcpu_to_pi_desc(vcpu));
}
if (ret < 0) {
printk(KERN_INFO "%s: failed to update PI IRTE\n",
__func__);
goto out;
}
}
ret = 0;
out:
srcu_read_unlock(&kvm->irq_srcu, idx);
return ret;
}
| 170,009 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
VncPalette **palette)
{
int max;
max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch(vs->clientds.pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 0;
}
Commit Message:
CWE ID: CWE-125 | static int tight_fill_palette(VncState *vs, int x, int y,
size_t count, uint32_t *bg, uint32_t *fg,
VncPalette **palette)
{
int max;
max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor;
if (max < 2 &&
count >= tight_conf[vs->tight.compression].mono_min_rect_size) {
max = 2;
}
if (max >= 256) {
max = 256;
}
switch (vs->client_pf.bytes_per_pixel) {
case 4:
return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);
case 2:
return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);
default:
max = 2;
return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);
}
return 0;
}
| 165,466 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Disallow Arabic/Hebrew NSMs to come after an unrelated base char.
Arabic NSM(non-spacing mark)s and Hebrew NSMs are allowed to mix with
Latin with the current 'moderately restrictive script mixing policy'.
They're not blocked by BiDi check either because both LTR and RTL labels
can have an NSM.
Block them from coming after an unrelated script (e.g. Latin + Arabic
NSM).
Bug: chromium:729979
Test: components_unittests --gtest_filter=*IDNToUni*
Change-Id: I5b93fbcf76d17121bf1baaa480ef3624424b3317
Reviewed-on: https://chromium-review.googlesource.com/528348
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#478205}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
// - Disallow Arabic non-spacing marks after non-Arabic characters.
// - Disallow Hebrew non-spacing marks after non-Hebrew characters.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,336 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.