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: const SystemProfileProto& MetricsLog::RecordEnvironment(
DelegatingProvider* delegating_provider) {
DCHECK(!has_environment_);
has_environment_ = true;
SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
system_profile);
std::string brand_code;
if (client_->GetBrand(&brand_code))
system_profile->set_brand_code(brand_code);
SystemProfileProto::Hardware::CPU* cpu =
system_profile->mutable_hardware()->mutable_cpu();
base::CPU cpu_info;
cpu->set_vendor_name(cpu_info.vendor_name());
cpu->set_signature(cpu_info.signature());
cpu->set_num_cores(base::SysInfo::NumberOfProcessors());
delegating_provider->ProvideSystemProfileMetrics(system_profile);
return *system_profile;
}
Commit Message: Add CPU metrics provider and Add CPU/GPU provider for UKM.
Bug: 907674
Change-Id: I61b88aeac8d2a7ff81d812fa5a267f48203ec7e2
Reviewed-on: https://chromium-review.googlesource.com/c/1381376
Commit-Queue: Nik Bhagat <[email protected]>
Reviewed-by: Robert Kaplow <[email protected]>
Cr-Commit-Position: refs/heads/master@{#618037}
CWE ID: CWE-79 | const SystemProfileProto& MetricsLog::RecordEnvironment(
DelegatingProvider* delegating_provider) {
DCHECK(!has_environment_);
has_environment_ = true;
SystemProfileProto* system_profile = uma_proto()->mutable_system_profile();
WriteMetricsEnableDefault(client_->GetMetricsReportingDefaultState(),
system_profile);
std::string brand_code;
if (client_->GetBrand(&brand_code))
system_profile->set_brand_code(brand_code);
delegating_provider->ProvideSystemProfileMetrics(system_profile);
return *system_profile;
}
| 172,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_writers.frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
if (flags & MS_RDONLY)
acct_auto_close(sb);
shrink_dcache_sb(sb);
sync_filesystem(sb);
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force) {
mark_files_ro(sb);
} else {
retval = sb_prepare_remount_readonly(sb);
if (retval)
return retval;
}
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval) {
if (!force)
goto cancel_readonly;
/* If forced remount, go ahead despite any errors */
WARN(1, "forced remount of a %s fs returned %i\n",
sb->s_type->name, retval);
}
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/* Needs to be ordered wrt mnt_is_readonly() */
smp_wmb();
sb->s_readonly_remount = 0;
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
cancel_readonly:
sb->s_readonly_remount = 0;
return retval;
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | int do_remount_sb(struct super_block *sb, int flags, void *data, int force)
{
int retval;
int remount_ro;
if (sb->s_writers.frozen != SB_UNFROZEN)
return -EBUSY;
#ifdef CONFIG_BLOCK
if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev))
return -EACCES;
#endif
if (flags & MS_RDONLY)
acct_auto_close(sb);
shrink_dcache_sb(sb);
sync_filesystem(sb);
remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY);
/* If we are remounting RDONLY and current sb is read/write,
make sure there are no rw files opened */
if (remount_ro) {
if (force) {
sb->s_readonly_remount = 1;
smp_wmb();
} else {
retval = sb_prepare_remount_readonly(sb);
if (retval)
return retval;
}
}
if (sb->s_op->remount_fs) {
retval = sb->s_op->remount_fs(sb, &flags, data);
if (retval) {
if (!force)
goto cancel_readonly;
/* If forced remount, go ahead despite any errors */
WARN(1, "forced remount of a %s fs returned %i\n",
sb->s_type->name, retval);
}
}
sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK);
/* Needs to be ordered wrt mnt_is_readonly() */
smp_wmb();
sb->s_readonly_remount = 0;
/*
* Some filesystems modify their metadata via some other path than the
* bdev buffer cache (eg. use a private mapping, or directories in
* pagecache, etc). Also file data modifications go via their own
* mappings. So If we try to mount readonly then copy the filesystem
* from bdev, we could get stale data, so invalidate it to give a best
* effort at coherency.
*/
if (remount_ro && sb->s_bdev)
invalidate_bdev(sb->s_bdev);
return 0;
cancel_readonly:
sb->s_readonly_remount = 0;
return retval;
}
| 166,808 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PermissionsData::CanCaptureVisiblePage(const GURL& document_url,
int tab_id,
std::string* error) const {
bool has_active_tab = false;
bool has_all_urls = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
const URLPattern all_urls(URLPattern::SCHEME_ALL,
URLPattern::kAllUrlsPattern);
has_all_urls =
active_permissions_unsafe_->explicit_hosts().ContainsPattern(all_urls);
}
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
std::string access_error;
if (GetPageAccess(origin_url, tab_id, &access_error) == PageAccess::kAllowed)
return true;
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20 | bool PermissionsData::CanCaptureVisiblePage(const GURL& document_url,
bool PermissionsData::CanCaptureVisiblePage(
const GURL& document_url,
int tab_id,
std::string* error,
CaptureRequirement capture_requirement) const {
bool has_active_tab = false;
bool has_all_urls = false;
bool has_page_capture = false;
url::Origin origin = url::Origin::Create(document_url);
const GURL origin_url = origin.GetURL();
{
base::AutoLock auto_lock(runtime_lock_);
if (location_ != Manifest::COMPONENT &&
IsPolicyBlockedHostUnsafe(origin_url)) {
if (error)
*error = extension_misc::kPolicyBlockedScripting;
return false;
}
const PermissionSet* tab_permissions = GetTabSpecificPermissions(tab_id);
has_active_tab = tab_permissions &&
tab_permissions->HasAPIPermission(APIPermission::kTab);
const URLPattern all_urls(URLPattern::SCHEME_ALL,
URLPattern::kAllUrlsPattern);
has_all_urls =
active_permissions_unsafe_->explicit_hosts().ContainsPattern(all_urls);
has_page_capture = active_permissions_unsafe_->HasAPIPermission(
APIPermission::kPageCapture);
}
std::string access_error;
if (capture_requirement == CaptureRequirement::kActiveTabOrAllUrls) {
if (!has_active_tab && !has_all_urls) {
if (error)
*error = manifest_errors::kAllURLOrActiveTabNeeded;
return false;
}
// We check GetPageAccess() (in addition to the <all_urls> and activeTab
// checks below) for the case of URLs that can be conditionally granted
// (such as file:// URLs or chrome:// URLs for component extensions). If an
// extension has <all_urls>, GetPageAccess() will still (correctly) return
// false if, for instance, the URL is a file:// URL and the extension does
// not have file access. See https://crbug.com/810220. If the extension has
// page access (and has activeTab or <all_urls>), allow the capture.
if (GetPageAccess(origin_url, tab_id, &access_error) ==
PageAccess::kAllowed)
return true;
} else {
DCHECK_EQ(CaptureRequirement::kPageCapture, capture_requirement);
if (!has_page_capture) {
if (error)
*error = manifest_errors::kPageCaptureNeeded;
}
// If the URL is a typical web URL, the pageCapture permission is
// sufficient.
if ((origin_url.SchemeIs(url::kHttpScheme) ||
origin_url.SchemeIs(url::kHttpsScheme)) &&
!origin.IsSameOriginWith(url::Origin::Create(
ExtensionsClient::Get()->GetWebstoreBaseURL()))) {
return true;
}
}
// activeTab (since the extension scheme is not included in the list of
// valid schemes for extension permissions). To capture an extension's own
// page, either activeTab or <all_urls> is needed (it's no higher privilege
// than a normal web page). At least one of these is still needed because
// the extension page may have embedded web content.
if (origin_url.host() == extension_id_)
return true;
bool allowed_with_active_tab =
origin_url.SchemeIs(content::kChromeUIScheme) ||
origin_url.SchemeIs(kExtensionScheme) ||
document_url.SchemeIs(url::kDataScheme) ||
origin.IsSameOriginWith(
url::Origin::Create(ExtensionsClient::Get()->GetWebstoreBaseURL()));
if (!allowed_with_active_tab) {
if (error)
*error = access_error;
return false;
}
if (has_active_tab)
return true;
if (error)
*error = manifest_errors::kActiveTabPermissionNotGranted;
return false;
}
| 173,010 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const char* SegmentInfo::GetWritingAppAsUTF8() const
{
return m_pWritingAppAsUTF8;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const char* SegmentInfo::GetWritingAppAsUTF8() const
| 174,383 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno)
{
void *uidl = NULL;
char buf[LONG_STRING];
char path[PATH_MAX];
struct Progress progressbar;
struct PopData *pop_data = (struct PopData *) ctx->data;
struct PopCache *cache = NULL;
struct Header *h = ctx->hdrs[msgno];
unsigned short bcache = 1;
/* see if we already have the message in body cache */
msg->fp = mutt_bcache_get(pop_data->bcache, h->data);
if (msg->fp)
return 0;
/*
* see if we already have the message in our cache in
* case $message_cachedir is unset
*/
cache = &pop_data->cache[h->index % POP_CACHE_LEN];
if (cache->path)
{
if (cache->index == h->index)
{
/* yes, so just return a pointer to the message */
msg->fp = fopen(cache->path, "r");
if (msg->fp)
return 0;
mutt_perror(cache->path);
return -1;
}
else
{
/* clear the previous entry */
unlink(cache->path);
FREE(&cache->path);
}
}
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
/* verify that massage index is correct */
if (h->refno < 0)
{
mutt_error(
_("The message index is incorrect. Try reopening the mailbox."));
return -1;
}
mutt_progress_init(&progressbar, _("Fetching message..."), MUTT_PROGRESS_SIZE,
NetInc, h->content->length + h->content->offset - 1);
/* see if we can put in body cache; use our cache as fallback */
msg->fp = mutt_bcache_put(pop_data->bcache, h->data);
if (!msg->fp)
{
/* no */
bcache = 0;
mutt_mktemp(path, sizeof(path));
msg->fp = mutt_file_fopen(path, "w+");
if (!msg->fp)
{
mutt_perror(path);
return -1;
}
}
snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno);
const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp);
if (ret == 0)
break;
mutt_file_fclose(&msg->fp);
/* if RETR failed (e.g. connection closed), be sure to remove either
* the file in bcache or from POP's own cache since the next iteration
* of the loop will re-attempt to put() the message */
if (!bcache)
unlink(path);
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
if (ret == -3)
{
mutt_error(_("Can't write message to temporary file!"));
return -1;
}
}
/* Update the header information. Previously, we only downloaded a
* portion of the headers, those required for the main display.
*/
if (bcache)
mutt_bcache_commit(pop_data->bcache, h->data);
else
{
cache->index = h->index;
cache->path = mutt_str_strdup(path);
}
rewind(msg->fp);
uidl = h->data;
/* we replace envelop, key in subj_hash has to be updated as well */
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_remove(ctx, h);
mutt_env_free(&h->env);
h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0);
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_add(ctx, h);
h->data = uidl;
h->lines = 0;
fgets(buf, sizeof(buf), msg->fp);
while (!feof(msg->fp))
{
ctx->hdrs[msgno]->lines++;
fgets(buf, sizeof(buf), msg->fp);
}
h->content->length = ftello(msg->fp) - h->content->offset;
/* This needs to be done in case this is a multipart message */
if (!WithCrypto)
h->security = crypt_query(h->content);
mutt_clear_error();
rewind(msg->fp);
return 0;
}
Commit Message: sanitise cache paths
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-22 | static int pop_fetch_message(struct Context *ctx, struct Message *msg, int msgno)
{
void *uidl = NULL;
char buf[LONG_STRING];
char path[PATH_MAX];
struct Progress progressbar;
struct PopData *pop_data = (struct PopData *) ctx->data;
struct PopCache *cache = NULL;
struct Header *h = ctx->hdrs[msgno];
unsigned short bcache = 1;
/* see if we already have the message in body cache */
msg->fp = mutt_bcache_get(pop_data->bcache, cache_id(h->data));
if (msg->fp)
return 0;
/*
* see if we already have the message in our cache in
* case $message_cachedir is unset
*/
cache = &pop_data->cache[h->index % POP_CACHE_LEN];
if (cache->path)
{
if (cache->index == h->index)
{
/* yes, so just return a pointer to the message */
msg->fp = fopen(cache->path, "r");
if (msg->fp)
return 0;
mutt_perror(cache->path);
return -1;
}
else
{
/* clear the previous entry */
unlink(cache->path);
FREE(&cache->path);
}
}
while (true)
{
if (pop_reconnect(ctx) < 0)
return -1;
/* verify that massage index is correct */
if (h->refno < 0)
{
mutt_error(
_("The message index is incorrect. Try reopening the mailbox."));
return -1;
}
mutt_progress_init(&progressbar, _("Fetching message..."), MUTT_PROGRESS_SIZE,
NetInc, h->content->length + h->content->offset - 1);
/* see if we can put in body cache; use our cache as fallback */
msg->fp = mutt_bcache_put(pop_data->bcache, cache_id(h->data));
if (!msg->fp)
{
/* no */
bcache = 0;
mutt_mktemp(path, sizeof(path));
msg->fp = mutt_file_fopen(path, "w+");
if (!msg->fp)
{
mutt_perror(path);
return -1;
}
}
snprintf(buf, sizeof(buf), "RETR %d\r\n", h->refno);
const int ret = pop_fetch_data(pop_data, buf, &progressbar, fetch_message, msg->fp);
if (ret == 0)
break;
mutt_file_fclose(&msg->fp);
/* if RETR failed (e.g. connection closed), be sure to remove either
* the file in bcache or from POP's own cache since the next iteration
* of the loop will re-attempt to put() the message */
if (!bcache)
unlink(path);
if (ret == -2)
{
mutt_error("%s", pop_data->err_msg);
return -1;
}
if (ret == -3)
{
mutt_error(_("Can't write message to temporary file!"));
return -1;
}
}
/* Update the header information. Previously, we only downloaded a
* portion of the headers, those required for the main display.
*/
if (bcache)
mutt_bcache_commit(pop_data->bcache, cache_id(h->data));
else
{
cache->index = h->index;
cache->path = mutt_str_strdup(path);
}
rewind(msg->fp);
uidl = h->data;
/* we replace envelop, key in subj_hash has to be updated as well */
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_delete(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_remove(ctx, h);
mutt_env_free(&h->env);
h->env = mutt_rfc822_read_header(msg->fp, h, 0, 0);
if (ctx->subj_hash && h->env->real_subj)
mutt_hash_insert(ctx->subj_hash, h->env->real_subj, h);
mutt_label_hash_add(ctx, h);
h->data = uidl;
h->lines = 0;
fgets(buf, sizeof(buf), msg->fp);
while (!feof(msg->fp))
{
ctx->hdrs[msgno]->lines++;
fgets(buf, sizeof(buf), msg->fp);
}
h->content->length = ftello(msg->fp) - h->content->offset;
/* This needs to be done in case this is a multipart message */
if (!WithCrypto)
h->security = crypt_query(h->content);
mutt_clear_error();
rewind(msg->fp);
return 0;
}
| 169,122 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget());
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
Commit Message:
CWE ID: CWE-78 | void Part::slotOpenExtractedEntry(KJob *job)
{
if (!job->error()) {
OpenJob *openJob = qobject_cast<OpenJob*>(job);
Q_ASSERT(openJob);
m_tmpExtractDirList << openJob->tempDir();
const QString fullName = openJob->validatedFilePath();
bool isWritable = m_model->archive() && !m_model->archive()->isReadOnly();
if (!isWritable) {
QFile::setPermissions(fullName, QFileDevice::ReadOwner | QFileDevice::ReadGroup | QFileDevice::ReadOther);
}
if (isWritable) {
m_fileWatcher = new QFileSystemWatcher;
connect(m_fileWatcher, &QFileSystemWatcher::fileChanged, this, &Part::slotWatchedFileModified);
m_fileWatcher->addPath(fullName);
}
if (qobject_cast<OpenWithJob*>(job)) {
const QList<QUrl> urls = {QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile)};
KRun::displayOpenWithDialog(urls, widget());
} else {
KRun::runUrl(QUrl::fromUserInput(fullName, QString(), QUrl::AssumeLocalFile),
QMimeDatabase().mimeTypeForFile(fullName).name(),
widget(), false, false);
}
} else if (job->error() != KJob::KilledJobError) {
KMessageBox::error(widget(), job->errorString());
}
setReadyGui();
}
| 164,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
Commit Message:
CWE ID: CWE-320 | static int generate_key(DH *dh)
{
int ok = 0;
int generate_new_key = 0;
unsigned l;
BN_CTX *ctx = NULL;
BN_MONT_CTX *mont = NULL;
BIGNUM *pub_key = NULL, *priv_key = NULL;
if (BN_num_bits(dh->p) > OPENSSL_DH_MAX_MODULUS_BITS) {
DHerr(DH_F_GENERATE_KEY, DH_R_MODULUS_TOO_LARGE);
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
generate_new_key = 1;
} else
| 165,332 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FileAPIMessageFilter::OnCreateSnapshotFile(
int request_id, const GURL& blob_url, const GURL& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
FileSystemURL url(path);
base::Callback<void(const FilePath&)> register_file_callback =
base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob,
this, blob_url, url.path());
FileSystemOperation* operation = GetNewOperation(url, request_id);
if (!operation)
return;
operation->CreateSnapshotFile(
url,
base::Bind(&FileAPIMessageFilter::DidCreateSnapshot,
this, request_id, register_file_callback));
}
Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files
We also need to check the read permission and call GrantReadFile() for
sandboxed files for CreateSnapshotFile().
BUG=162114
TEST=manual
Review URL: https://codereview.chromium.org/11280231
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | void FileAPIMessageFilter::OnCreateSnapshotFile(
int request_id, const GURL& blob_url, const GURL& path) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
FileSystemURL url(path);
base::Callback<void(const FilePath&)> register_file_callback =
base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob,
this, blob_url, url);
// Make sure if this file can be read by the renderer as this is
// called when the renderer is about to create a new File object
// (for reading the file).
base::PlatformFileError error;
if (!HasPermissionsForFile(url, kReadFilePermissions, &error)) {
Send(new FileSystemMsg_DidFail(request_id, error));
return;
}
FileSystemOperation* operation = GetNewOperation(url, request_id);
if (!operation)
return;
operation->CreateSnapshotFile(
url,
base::Bind(&FileAPIMessageFilter::DidCreateSnapshot,
this, request_id, register_file_callback));
}
| 171,586 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION(locale_get_primary_language )
PHP_FUNCTION(locale_get_primary_language )
{
get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,184 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PicContext *s = avctx->priv_data;
AVFrame *frame = data;
uint32_t *palette;
int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
int i, x, y, plane, tmp, ret, val;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&s->g) < 11)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le16u(&s->g) != 0x1234)
return AVERROR_INVALIDDATA;
s->width = bytestream2_get_le16u(&s->g);
s->height = bytestream2_get_le16u(&s->g);
bytestream2_skip(&s->g, 4);
tmp = bytestream2_get_byteu(&s->g);
bits_per_plane = tmp & 0xF;
s->nb_planes = (tmp >> 4) + 1;
bpp = bits_per_plane * s->nb_planes;
if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
avpriv_request_sample(avctx, "Unsupported bit depth");
return AVERROR_PATCHWELCOME;
}
if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
bytestream2_skip(&s->g, 2);
etype = bytestream2_get_le16(&s->g);
esize = bytestream2_get_le16(&s->g);
if (bytestream2_get_bytes_left(&s->g) < esize)
return AVERROR_INVALIDDATA;
} else {
etype = -1;
esize = 0;
}
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
return -1;
if (s->width != avctx->width && s->height != avctx->height) {
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
}
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
memset(frame->data[0], 0, s->height * frame->linesize[0]);
frame->pict_type = AV_PICTURE_TYPE_I;
frame->palette_has_changed = 1;
pos_after_pal = bytestream2_tell(&s->g) + esize;
palette = (uint32_t*)frame->data[1];
if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {
int idx = bytestream2_get_byte(&s->g);
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
} else if (etype == 2) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];
}
} else if (etype == 3) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];
}
} else if (etype == 4 || etype == 5) {
npal = FFMIN(esize / 3, 256);
for (i = 0; i < npal; i++) {
palette[i] = bytestream2_get_be24(&s->g) << 2;
palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;
}
} else {
if (bpp == 1) {
npal = 2;
palette[0] = 0xFF000000;
palette[1] = 0xFFFFFFFF;
} else if (bpp == 2) {
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
} else {
npal = 16;
memcpy(palette, ff_cga_palette, npal * 4);
}
}
memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
val = 0;
y = s->height - 1;
if (bytestream2_get_le16(&s->g)) {
x = 0;
plane = 0;
while (bytestream2_get_bytes_left(&s->g) >= 6) {
int stop_size, marker, t1, t2;
t1 = bytestream2_get_bytes_left(&s->g);
t2 = bytestream2_get_le16(&s->g);
stop_size = t1 - FFMIN(t1, t2);
bytestream2_skip(&s->g, 2);
marker = bytestream2_get_byte(&s->g);
while (plane < s->nb_planes &&
bytestream2_get_bytes_left(&s->g) > stop_size) {
int run = 1;
val = bytestream2_get_byte(&s->g);
if (val == marker) {
run = bytestream2_get_byte(&s->g);
if (run == 0)
run = bytestream2_get_le16(&s->g);
val = bytestream2_get_byte(&s->g);
}
if (!bytestream2_get_bytes_left(&s->g))
break;
if (bits_per_plane == 8) {
picmemset_8bpp(s, frame, val, run, &x, &y);
if (y < 0)
goto finish;
} else {
picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);
}
}
}
if (x < avctx->width) {
int run = (y + 1) * avctx->width - x;
if (bits_per_plane == 8)
picmemset_8bpp(s, frame, val, run, &x, &y);
else
picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
}
} else {
while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
bytestream2_skip(&s->g, avctx->width);
y--;
}
}
finish:
*got_frame = 1;
return avpkt->size;
}
Commit Message: avcodec/pictordec: Fix logic error
Fixes: 559/clusterfuzz-testcase-6424225917173760
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-787 | static int decode_frame(AVCodecContext *avctx,
void *data, int *got_frame,
AVPacket *avpkt)
{
PicContext *s = avctx->priv_data;
AVFrame *frame = data;
uint32_t *palette;
int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;
int i, x, y, plane, tmp, ret, val;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
if (bytestream2_get_bytes_left(&s->g) < 11)
return AVERROR_INVALIDDATA;
if (bytestream2_get_le16u(&s->g) != 0x1234)
return AVERROR_INVALIDDATA;
s->width = bytestream2_get_le16u(&s->g);
s->height = bytestream2_get_le16u(&s->g);
bytestream2_skip(&s->g, 4);
tmp = bytestream2_get_byteu(&s->g);
bits_per_plane = tmp & 0xF;
s->nb_planes = (tmp >> 4) + 1;
bpp = bits_per_plane * s->nb_planes;
if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {
avpriv_request_sample(avctx, "Unsupported bit depth");
return AVERROR_PATCHWELCOME;
}
if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {
bytestream2_skip(&s->g, 2);
etype = bytestream2_get_le16(&s->g);
esize = bytestream2_get_le16(&s->g);
if (bytestream2_get_bytes_left(&s->g) < esize)
return AVERROR_INVALIDDATA;
} else {
etype = -1;
esize = 0;
}
avctx->pix_fmt = AV_PIX_FMT_PAL8;
if (av_image_check_size(s->width, s->height, 0, avctx) < 0)
return -1;
if (s->width != avctx->width || s->height != avctx->height) {
ret = ff_set_dimensions(avctx, s->width, s->height);
if (ret < 0)
return ret;
}
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
memset(frame->data[0], 0, s->height * frame->linesize[0]);
frame->pict_type = AV_PICTURE_TYPE_I;
frame->palette_has_changed = 1;
pos_after_pal = bytestream2_tell(&s->g) + esize;
palette = (uint32_t*)frame->data[1];
if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {
int idx = bytestream2_get_byte(&s->g);
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];
} else if (etype == 2) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_cga_palette[FFMIN(pal_idx, 15)];
}
} else if (etype == 3) {
npal = FFMIN(esize, 16);
for (i = 0; i < npal; i++) {
int pal_idx = bytestream2_get_byte(&s->g);
palette[i] = ff_ega_palette[FFMIN(pal_idx, 63)];
}
} else if (etype == 4 || etype == 5) {
npal = FFMIN(esize / 3, 256);
for (i = 0; i < npal; i++) {
palette[i] = bytestream2_get_be24(&s->g) << 2;
palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;
}
} else {
if (bpp == 1) {
npal = 2;
palette[0] = 0xFF000000;
palette[1] = 0xFFFFFFFF;
} else if (bpp == 2) {
npal = 4;
for (i = 0; i < npal; i++)
palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];
} else {
npal = 16;
memcpy(palette, ff_cga_palette, npal * 4);
}
}
memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);
bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);
val = 0;
y = s->height - 1;
if (bytestream2_get_le16(&s->g)) {
x = 0;
plane = 0;
while (bytestream2_get_bytes_left(&s->g) >= 6) {
int stop_size, marker, t1, t2;
t1 = bytestream2_get_bytes_left(&s->g);
t2 = bytestream2_get_le16(&s->g);
stop_size = t1 - FFMIN(t1, t2);
bytestream2_skip(&s->g, 2);
marker = bytestream2_get_byte(&s->g);
while (plane < s->nb_planes &&
bytestream2_get_bytes_left(&s->g) > stop_size) {
int run = 1;
val = bytestream2_get_byte(&s->g);
if (val == marker) {
run = bytestream2_get_byte(&s->g);
if (run == 0)
run = bytestream2_get_le16(&s->g);
val = bytestream2_get_byte(&s->g);
}
if (!bytestream2_get_bytes_left(&s->g))
break;
if (bits_per_plane == 8) {
picmemset_8bpp(s, frame, val, run, &x, &y);
if (y < 0)
goto finish;
} else {
picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);
}
}
}
if (x < avctx->width) {
int run = (y + 1) * avctx->width - x;
if (bits_per_plane == 8)
picmemset_8bpp(s, frame, val, run, &x, &y);
else
picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);
}
} else {
while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {
memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));
bytestream2_skip(&s->g, avctx->width);
y--;
}
}
finish:
*got_frame = 1;
return avpkt->size;
}
| 168,249 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */
{
fpm_globals.max_requests = wp->config->pm_max_requests;
if (0 > fpm_stdio_init_child(wp) ||
0 > fpm_log_init_child(wp) ||
0 > fpm_status_init_child(wp) ||
0 > fpm_unix_init_child(wp) ||
0 > fpm_signals_init_child() ||
0 > fpm_env_init_child(wp) ||
0 > fpm_php_init_child(wp)) {
zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name);
exit(FPM_EXIT_SOFTWARE);
}
}
/* }}} */
Commit Message: Fixed bug #73342
Directly listen on socket, instead of duping it to STDIN and
listening on that.
CWE ID: CWE-400 | static void fpm_child_init(struct fpm_worker_pool_s *wp) /* {{{ */
{
fpm_globals.max_requests = wp->config->pm_max_requests;
fpm_globals.listening_socket = dup(wp->listening_socket);
if (0 > fpm_stdio_init_child(wp) ||
0 > fpm_log_init_child(wp) ||
0 > fpm_status_init_child(wp) ||
0 > fpm_unix_init_child(wp) ||
0 > fpm_signals_init_child() ||
0 > fpm_env_init_child(wp) ||
0 > fpm_php_init_child(wp)) {
zlog(ZLOG_ERROR, "[pool %s] child failed to initialize", wp->config->name);
exit(FPM_EXIT_SOFTWARE);
}
}
/* }}} */
| 169,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: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
if (n <= 0) return(n); /* error or non-blocking io */
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
Commit Message: Fix crash in dtls1_get_record whilst in the listen state where you get two
separate reads performed - one for the header and one for the body of the
handshake record.
CVE-2014-3571
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: | int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
*p == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
| 169,935 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
mem_free(gr.gr_ctx.value,
sizeof(gss_union_ctx_id_desc));
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
mem_free(gr.gr_ctx.value, sizeof(gss_union_ctx_id_desc));
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
Commit Message: Fix gssrpc data leakage [CVE-2014-9423]
[MITKRB5-SA-2015-001] In svcauth_gss_accept_sec_context(), do not copy
bytes from the union context into the handle field we send to the
client. We do not use this handle field, so just supply a fixed
string of "xxxx".
In gss_union_ctx_id_struct, remove the unused "interposer" field which
was causing part of the union context to remain uninitialized.
ticket: 8058 (new)
target_version: 1.13.1
tags: pullup
CWE ID: CWE-200 | gssrpc__svcauth_gss(struct svc_req *rqst, struct rpc_msg *msg,
bool_t *no_dispatch)
{
enum auth_stat retstat;
XDR xdrs;
SVCAUTH *auth;
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
struct rpc_gss_init_res gr;
int call_stat, offset;
OM_uint32 min_stat;
log_debug("in svcauth_gss()");
/* Initialize reply. */
rqst->rq_xprt->xp_verf = gssrpc__null_auth;
/* Allocate and set up server auth handle. */
if (rqst->rq_xprt->xp_auth == NULL ||
rqst->rq_xprt->xp_auth == &svc_auth_none) {
if ((auth = calloc(sizeof(*auth), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
if ((gd = calloc(sizeof(*gd), 1)) == NULL) {
fprintf(stderr, "svcauth_gss: out_of_memory\n");
return (AUTH_FAILED);
}
auth->svc_ah_ops = &svc_auth_gss_ops;
SVCAUTH_PRIVATE(auth) = gd;
rqst->rq_xprt->xp_auth = auth;
}
else gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
log_debug("xp_auth=%p, gd=%p", rqst->rq_xprt->xp_auth, gd);
/* Deserialize client credentials. */
if (rqst->rq_cred.oa_length <= 0)
return (AUTH_BADCRED);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gc, 0, sizeof(*gc));
log_debug("calling xdrmem_create()");
log_debug("oa_base=%p, oa_length=%u", rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length);
xdrmem_create(&xdrs, rqst->rq_cred.oa_base,
rqst->rq_cred.oa_length, XDR_DECODE);
log_debug("xdrmem_create() returned");
if (!xdr_rpc_gss_cred(&xdrs, gc)) {
log_debug("xdr_rpc_gss_cred() failed");
XDR_DESTROY(&xdrs);
return (AUTH_BADCRED);
}
XDR_DESTROY(&xdrs);
retstat = AUTH_FAILED;
#define ret_freegc(code) do { retstat = code; goto freegc; } while (0)
/* Check version. */
if (gc->gc_v != RPCSEC_GSS_VERSION)
ret_freegc (AUTH_BADCRED);
/* Check RPCSEC_GSS service. */
if (gc->gc_svc != RPCSEC_GSS_SVC_NONE &&
gc->gc_svc != RPCSEC_GSS_SVC_INTEGRITY &&
gc->gc_svc != RPCSEC_GSS_SVC_PRIVACY)
ret_freegc (AUTH_BADCRED);
/* Check sequence number. */
if (gd->established) {
if (gc->gc_seq > MAXSEQ)
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
if ((offset = gd->seqlast - gc->gc_seq) < 0) {
gd->seqlast = gc->gc_seq;
offset = 0 - offset;
gd->seqmask <<= offset;
offset = 0;
} else if ((u_int)offset >= gd->win ||
(gd->seqmask & (1 << offset))) {
*no_dispatch = 1;
ret_freegc (RPCSEC_GSS_CTXPROBLEM);
}
gd->seq = gc->gc_seq;
gd->seqmask |= (1 << offset);
}
if (gd->established) {
rqst->rq_clntname = (char *)gd->client_name;
rqst->rq_svccred = (char *)gd->ctx;
}
/* Handle RPCSEC_GSS control procedure. */
switch (gc->gc_proc) {
case RPCSEC_GSS_INIT:
case RPCSEC_GSS_CONTINUE_INIT:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_acquire_cred())
ret_freegc (AUTH_FAILED);
if (!svcauth_gss_accept_sec_context(rqst, &gr))
ret_freegc (AUTH_REJECTEDCRED);
if (!svcauth_gss_nextverf(rqst, htonl(gr.gr_win))) {
gss_release_buffer(&min_stat, &gr.gr_token);
ret_freegc (AUTH_FAILED);
}
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt, xdr_rpc_gss_init_res,
(caddr_t)&gr);
gss_release_buffer(&min_stat, &gr.gr_token);
gss_release_buffer(&min_stat, &gd->checksum);
if (!call_stat)
ret_freegc (AUTH_FAILED);
if (gr.gr_major == GSS_S_COMPLETE)
gd->established = TRUE;
break;
case RPCSEC_GSS_DATA:
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
break;
case RPCSEC_GSS_DESTROY:
if (rqst->rq_proc != NULLPROC)
ret_freegc (AUTH_FAILED); /* XXX ? */
if (!svcauth_gss_validate(rqst, gd, msg))
ret_freegc (RPCSEC_GSS_CREDPROBLEM);
if (!svcauth_gss_nextverf(rqst, htonl(gc->gc_seq)))
ret_freegc (AUTH_FAILED);
*no_dispatch = TRUE;
call_stat = svc_sendreply(rqst->rq_xprt,
xdr_void, (caddr_t)NULL);
log_debug("sendreply in destroy: %d", call_stat);
if (!svcauth_gss_release_cred())
ret_freegc (AUTH_FAILED);
SVCAUTH_DESTROY(rqst->rq_xprt->xp_auth);
rqst->rq_xprt->xp_auth = &svc_auth_none;
break;
default:
ret_freegc (AUTH_REJECTEDCRED);
break;
}
retstat = AUTH_OK;
freegc:
xdr_free(xdr_rpc_gss_cred, gc);
log_debug("returning %d from svcauth_gss()", retstat);
return (retstat);
}
| 166,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: explicit SyncInternal(const std::string& name)
: name_(name),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
enable_sync_tabs_for_other_clients_(false),
registrar_(NULL),
change_delegate_(NULL),
initialized_(false),
testing_mode_(NON_TEST),
observing_ip_address_changes_(false),
traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
encryptor_(NULL),
unrecoverable_error_handler_(NULL),
report_unrecoverable_error_function_(NULL),
created_on_loop_(MessageLoop::current()),
nigori_overwrite_count_(0) {
for (int i = syncable::FIRST_REAL_MODEL_TYPE;
i < syncable::MODEL_TYPE_COUNT; ++i) {
notification_info_map_.insert(
std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
}
BindJsMessageHandler(
"getNotificationState",
&SyncManager::SyncInternal::GetNotificationState);
BindJsMessageHandler(
"getNotificationInfo",
&SyncManager::SyncInternal::GetNotificationInfo);
BindJsMessageHandler(
"getRootNodeDetails",
&SyncManager::SyncInternal::GetRootNodeDetails);
BindJsMessageHandler(
"getNodeSummariesById",
&SyncManager::SyncInternal::GetNodeSummariesById);
BindJsMessageHandler(
"getNodeDetailsById",
&SyncManager::SyncInternal::GetNodeDetailsById);
BindJsMessageHandler(
"getAllNodes",
&SyncManager::SyncInternal::GetAllNodes);
BindJsMessageHandler(
"getChildNodeIds",
&SyncManager::SyncInternal::GetChildNodeIds);
BindJsMessageHandler(
"getClientServerTraffic",
&SyncManager::SyncInternal::GetClientServerTraffic);
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | explicit SyncInternal(const std::string& name)
: name_(name),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
registrar_(NULL),
change_delegate_(NULL),
initialized_(false),
testing_mode_(NON_TEST),
observing_ip_address_changes_(false),
traffic_recorder_(kMaxMessagesToRecord, kMaxMessageSizeToRecord),
encryptor_(NULL),
unrecoverable_error_handler_(NULL),
report_unrecoverable_error_function_(NULL),
created_on_loop_(MessageLoop::current()),
nigori_overwrite_count_(0) {
for (int i = syncable::FIRST_REAL_MODEL_TYPE;
i < syncable::MODEL_TYPE_COUNT; ++i) {
notification_info_map_.insert(
std::make_pair(syncable::ModelTypeFromInt(i), NotificationInfo()));
}
BindJsMessageHandler(
"getNotificationState",
&SyncManager::SyncInternal::GetNotificationState);
BindJsMessageHandler(
"getNotificationInfo",
&SyncManager::SyncInternal::GetNotificationInfo);
BindJsMessageHandler(
"getRootNodeDetails",
&SyncManager::SyncInternal::GetRootNodeDetails);
BindJsMessageHandler(
"getNodeSummariesById",
&SyncManager::SyncInternal::GetNodeSummariesById);
BindJsMessageHandler(
"getNodeDetailsById",
&SyncManager::SyncInternal::GetNodeDetailsById);
BindJsMessageHandler(
"getAllNodes",
&SyncManager::SyncInternal::GetAllNodes);
BindJsMessageHandler(
"getChildNodeIds",
&SyncManager::SyncInternal::GetChildNodeIds);
BindJsMessageHandler(
"getClientServerTraffic",
&SyncManager::SyncInternal::GetClientServerTraffic);
}
| 170,797 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
url_loader_factory, create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_));
if (ShouldAddDefaultProxyBypassRules())
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
url_loader_factory, create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_));
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
| 172,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret)
{
int ok = 0;
BIGNUM *q = NULL;
*ret = 0;
q = BN_new();
if (q == NULL)
goto err;
BN_set_word(q, 1);
if (BN_cmp(pub_key, q) <= 0)
*ret |= DH_CHECK_PUBKEY_TOO_SMALL;
BN_copy(q, dh->p);
BN_sub_word(q, 1);
if (BN_cmp(pub_key, q) >= 0)
*ret |= DH_CHECK_PUBKEY_TOO_LARGE;
ok = 1;
err:
if (q != NULL)
BN_free(q);
return (ok);
}
Commit Message:
CWE ID: CWE-200 | int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key, int *ret)
{
int ok = 0;
BIGNUM *tmp = NULL;
BN_CTX *ctx = NULL;
*ret = 0;
ctx = BN_CTX_new();
if (ctx == NULL)
goto err;
BN_CTX_start(ctx);
tmp = BN_CTX_get(ctx);
if (tmp == NULL)
goto err;
BN_set_word(tmp, 1);
if (BN_cmp(pub_key, tmp) <= 0)
*ret |= DH_CHECK_PUBKEY_TOO_SMALL;
BN_copy(tmp, dh->p);
BN_sub_word(tmp, 1);
if (BN_cmp(pub_key, tmp) >= 0)
*ret |= DH_CHECK_PUBKEY_TOO_LARGE;
if (dh->q != NULL) {
/* Check pub_key^q == 1 mod p */
if (!BN_mod_exp(tmp, pub_key, dh->q, dh->p, ctx))
goto err;
if (!BN_is_one(tmp))
*ret |= DH_CHECK_PUBKEY_INVALID;
}
ok = 1;
err:
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
return (ok);
}
| 165,258 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code)
{
iparam_list *const iplist = (iparam_list *) plist;
iparam_loc loc;
ref_param_read(iplist, pkey, &loc, -1); /* can't fail */
*loc.presult = code;
switch (ref_param_read_get_policy(plist, pkey)) {
case gs_param_policy_ignore:
return 0;
return_error(gs_error_configurationerror);
default:
return code;
}
}
Commit Message:
CWE ID: CWE-704 | ref_param_read_signal_error(gs_param_list * plist, gs_param_name pkey, int code)
{
iparam_list *const iplist = (iparam_list *) plist;
iparam_loc loc = {0};
ref_param_read(iplist, pkey, &loc, -1);
if (loc.presult)
*loc.presult = code;
switch (ref_param_read_get_policy(plist, pkey)) {
case gs_param_policy_ignore:
return 0;
return_error(gs_error_configurationerror);
default:
return code;
}
}
| 164,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlStopParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
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 | xmlStopParser(xmlParserCtxtPtr ctxt) {
if (ctxt == NULL)
return;
ctxt->instate = XML_PARSER_EOF;
ctxt->errNo = XML_ERR_USER_STOP;
ctxt->disableSAX = 1;
if (ctxt->input != NULL) {
ctxt->input->cur = BAD_CAST"";
ctxt->input->base = ctxt->input->cur;
}
}
| 171,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: wiki_handle_http_request(HttpRequest *req)
{
HttpResponse *res = http_response_new(req);
char *page = http_request_get_path_info(req);
char *command = http_request_get_query_string(req);
char *wikitext = "";
util_dehttpize(page); /* remove any encoding on the requested
page name. */
if (!strcmp(page, "/"))
{
if (access("WikiHome", R_OK) != 0)
wiki_redirect(res, "/WikiHome?create");
page = "/WikiHome";
}
if (!strcmp(page, "/styles.css"))
{
/* Return CSS page */
http_response_set_content_type(res, "text/css");
http_response_printf(res, "%s", CssData);
http_response_send(res);
exit(0);
}
if (!strcmp(page, "/favicon.ico"))
{
/* Return favicon */
http_response_set_content_type(res, "image/ico");
http_response_set_data(res, FaviconData, FaviconDataLen);
http_response_send(res);
exit(0);
}
page = page + 1; /* skip slash */
if (!strncmp(page, "api/", 4))
{
char *p;
page += 4;
for (p=page; *p != '\0'; p++)
if (*p=='?') { *p ='\0'; break; }
wiki_handle_rest_call(req, res, page);
exit(0);
}
/* A little safety. issue a malformed request for any paths,
* There shouldn't need to be any..
*/
if (strchr(page, '/'))
{
http_response_set_status(res, 404, "Not Found");
http_response_printf(res, "<html><body>404 Not Found</body></html>\n");
http_response_send(res);
exit(0);
}
if (!strcmp(page, "Changes"))
{
wiki_show_changes_page(res);
}
else if (!strcmp(page, "ChangesRss"))
{
wiki_show_changes_page_rss(res);
}
else if (!strcmp(page, "Search"))
{
wiki_show_search_results_page(res, http_request_param_get(req, "expr"));
}
else if (!strcmp(page, "Create"))
{
if ( (wikitext = http_request_param_get(req, "title")) != NULL)
{
/* create page and redirect */
wiki_redirect(res, http_request_param_get(req, "title"));
}
else
{
/* show create page form */
wiki_show_create_page(res);
}
}
else
{
/* TODO: dont blindly write wikitext data to disk */
if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL)
{
file_write(page, wikitext);
}
if (access(page, R_OK) == 0) /* page exists */
{
wikitext = file_read(page);
if (!strcmp(command, "edit"))
{
/* print edit page */
wiki_show_edit_page(res, wikitext, page);
}
else
{
wiki_show_page(res, wikitext, page);
}
}
else
{
if (!strcmp(command, "create"))
{
wiki_show_edit_page(res, NULL, page);
}
else
{
char buf[1024];
snprintf(buf, 1024, "%s?create", page);
wiki_redirect(res, buf);
}
}
}
}
Commit Message: page_name_is_good function
CWE ID: CWE-22 | wiki_handle_http_request(HttpRequest *req)
{
HttpResponse *res = http_response_new(req);
char *page = http_request_get_path_info(req);
char *command = http_request_get_query_string(req);
char *wikitext = "";
util_dehttpize(page); /* remove any encoding on the requested
page name. */
if (!strcmp(page, "/"))
{
if (access("WikiHome", R_OK) != 0)
wiki_redirect(res, "/WikiHome?create");
page = "/WikiHome";
}
if (!strcmp(page, "/styles.css"))
{
/* Return CSS page */
http_response_set_content_type(res, "text/css");
http_response_printf(res, "%s", CssData);
http_response_send(res);
exit(0);
}
if (!strcmp(page, "/favicon.ico"))
{
/* Return favicon */
http_response_set_content_type(res, "image/ico");
http_response_set_data(res, FaviconData, FaviconDataLen);
http_response_send(res);
exit(0);
}
page = page + 1; /* skip slash */
if (!strncmp(page, "api/", 4))
{
char *p;
page += 4;
for (p=page; *p != '\0'; p++)
if (*p=='?') { *p ='\0'; break; }
wiki_handle_rest_call(req, res, page);
exit(0);
}
/* A little safety. issue a malformed request for any paths,
* There shouldn't need to be any..
*/
if (!page_name_is_good(page))
{
http_response_set_status(res, 404, "Not Found");
http_response_printf(res, "<html><body>404 Not Found</body></html>\n");
http_response_send(res);
exit(0);
}
if (!strcmp(page, "Changes"))
{
wiki_show_changes_page(res);
}
else if (!strcmp(page, "ChangesRss"))
{
wiki_show_changes_page_rss(res);
}
else if (!strcmp(page, "Search"))
{
wiki_show_search_results_page(res, http_request_param_get(req, "expr"));
}
else if (!strcmp(page, "Create"))
{
if ( (wikitext = http_request_param_get(req, "title")) != NULL)
{
/* create page and redirect */
wiki_redirect(res, http_request_param_get(req, "title"));
}
else
{
/* show create page form */
wiki_show_create_page(res);
}
}
else
{
/* TODO: dont blindly write wikitext data to disk */
if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL)
{
file_write(page, wikitext);
}
if (access(page, R_OK) == 0) /* page exists */
{
wikitext = file_read(page);
if (!strcmp(command, "edit"))
{
/* print edit page */
wiki_show_edit_page(res, wikitext, page);
}
else
{
wiki_show_page(res, wikitext, page);
}
}
else
{
if (!strcmp(command, "create"))
{
wiki_show_edit_page(res, NULL, page);
}
else
{
char buf[1024];
snprintf(buf, 1024, "%s?create", page);
wiki_redirect(res, buf);
}
}
}
}
| 167,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 copyStereo8(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
*dst++ = src[1][i] << 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyStereo8(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
*dst++ = src[1][i] << 8;
}
}
| 174,023 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::ParseCues(
long long off,
long long& pos,
long& len)
{
if (m_pCues)
return 0; //success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; //don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id != 0x0C53BB6B) //Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; //consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
if (size == 0) //weird, although technically not illegal
return 1; //done
pos += len; //consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; //don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues = new (std::nothrow) Cues(
this,
pos,
size,
element_start,
element_size);
assert(m_pCues); //TODO
return 0; //success
}
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 Segment::ParseCues(
long Segment::ParseCues(long long off, long long& pos, long& len) {
if (m_pCues)
return 0; // success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; // don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id != 0x0C53BB6B) // Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
// Read Size
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
if (size == 0) // weird, although technically not illegal
return 1; // done
pos += len; // consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
// Pos now points to start of payload
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; // don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues =
new (std::nothrow) Cues(this, pos, size, element_start, element_size);
assert(m_pCues); // TODO
return 0; // success
}
| 174,421 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
return ret;
}
Commit Message:
CWE ID: CWE-190 | int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
if (sn->l1_size > QCOW_MAX_L1_SIZE) {
error_setg(errp, "Snapshot L1 table too large");
return -EFBIG;
}
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
return ret;
}
| 165,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: update_display(struct display *dp)
/* called once after the first read to update all the info, original_pp and
* original_ip must have been filled in.
*/
{
png_structp pp;
png_infop ip;
/* Now perform the initial read with a 0 tranform. */
read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
/* Move the result to the 'original' fields */
dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
dp->original_rowbytes = png_get_rowbytes(pp, ip);
if (dp->original_rowbytes == 0)
display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
dp->chunks = png_get_valid(pp, ip, 0xffffffff);
if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
dp->original_rows = png_get_rows(pp, ip);
if (dp->original_rows == NULL)
display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
if (!png_get_IHDR(pp, ip,
&dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
&dp->interlace_method, &dp->compression_method, &dp->filter_method))
display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
/* 'active' transforms are discovered based on the original image format;
* running one active transform can activate others. At present the code
* does not attempt to determine the closure.
*/
{
png_uint_32 chunks = dp->chunks;
int active = 0, inactive = 0;
int ct = dp->color_type;
int bd = dp->bit_depth;
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i)
{
int transform = transform_info[i].transform;
if ((transform_info[i].valid_chunks == 0 ||
(transform_info[i].valid_chunks & chunks) != 0) &&
(transform_info[i].color_mask_required & ct) ==
transform_info[i].color_mask_required &&
(transform_info[i].color_mask_absent & ct) == 0 &&
(transform_info[i].bit_depths & bd) != 0 &&
(transform_info[i].when & TRANSFORM_R) != 0)
active |= transform;
else if ((transform_info[i].when & TRANSFORM_R) != 0)
inactive |= transform;
}
/* Some transforms appear multiple times in the table; the 'active' status
* is the logical OR of these and the inactive status must be adjusted to
* take this into account.
*/
inactive &= ~active;
dp->active_transforms = active;
dp->ignored_transforms = inactive; /* excluding write-only transforms */
if (active == 0)
display_log(dp, INTERNAL_ERROR, "bad transform table");
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | update_display(struct display *dp)
/* called once after the first read to update all the info, original_pp and
* original_ip must have been filled in.
*/
{
png_structp pp;
png_infop ip;
/* Now perform the initial read with a 0 tranform. */
read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
/* Move the result to the 'original' fields */
dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
dp->original_rowbytes = png_get_rowbytes(pp, ip);
if (dp->original_rowbytes == 0)
display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
dp->chunks = png_get_valid(pp, ip, 0xffffffff);
if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
dp->original_rows = png_get_rows(pp, ip);
if (dp->original_rows == NULL)
display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
if (!png_get_IHDR(pp, ip,
&dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
&dp->interlace_method, &dp->compression_method, &dp->filter_method))
display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
/* 'active' transforms are discovered based on the original image format;
* running one active transform can activate others. At present the code
* does not attempt to determine the closure.
*/
{
png_uint_32 chunks = dp->chunks;
int active = 0, inactive = 0;
int ct = dp->color_type;
int bd = dp->bit_depth;
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i) if (transform_info[i].name != NULL)
{
int transform = transform_info[i].transform;
if ((transform_info[i].valid_chunks == 0 ||
(transform_info[i].valid_chunks & chunks) != 0) &&
(transform_info[i].color_mask_required & ct) ==
transform_info[i].color_mask_required &&
(transform_info[i].color_mask_absent & ct) == 0 &&
(transform_info[i].bit_depths & bd) != 0 &&
(transform_info[i].when & TRANSFORM_R) != 0)
active |= transform;
else if ((transform_info[i].when & TRANSFORM_R) != 0)
inactive |= transform;
}
/* Some transforms appear multiple times in the table; the 'active' status
* is the logical OR of these and the inactive status must be adjusted to
* take this into account.
*/
inactive &= ~active;
dp->active_transforms = active;
dp->ignored_transforms = inactive; /* excluding write-only transforms */
}
}
| 173,591 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
Commit Message: nss-mymachines: do not allow overlong machine names
https://github.com/systemd/systemd/issues/2002
CWE ID: CWE-119 | enum nss_status _nss_mymachines_getpwnam_r(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_bus_message_unref_ sd_bus_message* reply = NULL;
_cleanup_bus_flush_close_unref_ sd_bus *bus = NULL;
const char *p, *e, *machine;
uint32_t mapped;
uid_t uid;
size_t l;
int r;
assert(name);
assert(pwd);
p = startswith(name, "vu-");
if (!p)
goto not_found;
e = strrchr(p, '-');
if (!e || e == p)
goto not_found;
if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */
goto not_found;
r = parse_uid(e + 1, &uid);
if (r < 0)
goto not_found;
machine = strndupa(p, e - p);
if (!machine_name_is_valid(machine))
goto not_found;
r = sd_bus_open_system(&bus);
if (r < 0)
goto fail;
r = sd_bus_call_method(bus,
"org.freedesktop.machine1",
"/org/freedesktop/machine1",
"org.freedesktop.machine1.Manager",
"MapFromMachineUser",
&error,
&reply,
"su",
machine, (uint32_t) uid);
if (r < 0) {
if (sd_bus_error_has_name(&error, BUS_ERROR_NO_SUCH_USER_MAPPING))
goto not_found;
goto fail;
}
r = sd_bus_message_read(reply, "u", &mapped);
if (r < 0)
goto fail;
l = strlen(name);
if (buflen < l+1) {
*errnop = ENOMEM;
return NSS_STATUS_TRYAGAIN;
}
memcpy(buffer, name, l+1);
pwd->pw_name = buffer;
pwd->pw_uid = mapped;
pwd->pw_gid = 65534; /* nobody */
pwd->pw_gecos = buffer;
pwd->pw_passwd = (char*) "*"; /* locked */
pwd->pw_dir = (char*) "/";
pwd->pw_shell = (char*) "/sbin/nologin";
*errnop = 0;
return NSS_STATUS_SUCCESS;
not_found:
*errnop = 0;
return NSS_STATUS_NOTFOUND;
fail:
*errnop = -r;
return NSS_STATUS_UNAVAIL;
}
| 168,870 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
line += 3; /* skip "ng " */
if (!(ptr = strchr(line, ' ')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
line = ptr + 1;
if (!(ptr = strchr(line, '\n')))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
Commit Message: smart_pkt: fix potential OOB-read when processing ng packet
OSS-fuzz has reported a potential out-of-bounds read when processing a
"ng" smart packet:
==1==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6310000249c0 at pc 0x000000493a92 bp 0x7ffddc882cd0 sp 0x7ffddc882480
READ of size 65529 at 0x6310000249c0 thread T0
SCARINESS: 26 (multi-byte-read-heap-buffer-overflow)
#0 0x493a91 in __interceptor_strchr.part.35 /src/llvm/projects/compiler-rt/lib/sanitizer_common/sanitizer_common_interceptors.inc:673
#1 0x813960 in ng_pkt libgit2/src/transports/smart_pkt.c:320:14
#2 0x810f79 in git_pkt_parse_line libgit2/src/transports/smart_pkt.c:478:9
#3 0x82c3c9 in git_smart__store_refs libgit2/src/transports/smart_protocol.c:47:12
#4 0x6373a2 in git_smart__connect libgit2/src/transports/smart.c:251:15
#5 0x57688f in git_remote_connect libgit2/src/remote.c:708:15
#6 0x52e59b in LLVMFuzzerTestOneInput /src/download_refs_fuzzer.cc:145:9
#7 0x52ef3f in ExecuteFilesOnyByOne(int, char**) /src/libfuzzer/afl/afl_driver.cpp:301:5
#8 0x52f4ee in main /src/libfuzzer/afl/afl_driver.cpp:339:12
#9 0x7f6c910db82f in __libc_start_main /build/glibc-Cl5G7W/glibc-2.23/csu/libc-start.c:291
#10 0x41d518 in _start
When parsing an "ng" packet, we keep track of both the current position
as well as the remaining length of the packet itself. But instead of
taking care not to exceed the length, we pass the current pointer's
position to `strchr`, which will search for a certain character until
hitting NUL. It is thus possible to create a crafted packet which
doesn't contain a NUL byte to trigger an out-of-bounds read.
Fix the issue by instead using `memchr`, passing the remaining length as
restriction. Furthermore, verify that we actually have enough bytes left
to produce a match at all.
OSS-Fuzz-Issue: 9406
CWE ID: CWE-125 | static int ng_pkt(git_pkt **out, const char *line, size_t len)
{
git_pkt_ng *pkt;
const char *ptr;
size_t alloclen;
pkt = git__malloc(sizeof(*pkt));
GITERR_CHECK_ALLOC(pkt);
pkt->ref = NULL;
pkt->type = GIT_PKT_NG;
if (len < 3)
goto out_err;
line += 3; /* skip "ng " */
len -= 3;
if (!(ptr = memchr(line, ' ', len)))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->ref = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->ref);
memcpy(pkt->ref, line, len);
pkt->ref[len] = '\0';
if (len < 1)
goto out_err;
line = ptr + 1;
len -= 1;
if (!(ptr = memchr(line, '\n', len)))
goto out_err;
len = ptr - line;
GITERR_CHECK_ALLOC_ADD(&alloclen, len, 1);
pkt->msg = git__malloc(alloclen);
GITERR_CHECK_ALLOC(pkt->msg);
memcpy(pkt->msg, line, len);
pkt->msg[len] = '\0';
*out = (git_pkt *)pkt;
return 0;
out_err:
giterr_set(GITERR_NET, "invalid packet line");
git__free(pkt->ref);
git__free(pkt);
return -1;
}
| 169,103 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
unsigned int b, unsigned int a, unsigned int in_digitized, double in,
unsigned int out, png_byte sample_depth, double err, double limit,
PNG_CONST char *name, double digitization_error)
{
/* Compare the scaled, digitzed, values of our local calculation (in+-err)
* with the digitized values libpng produced; 'sample_depth' is the actual
* digitization depth of the libpng output colors (the bit depth except for
* palette images where it is always 8.) The check on 'err' is to detect
* internal errors in pngvalid itself.
*/
unsigned int max = (1U<<sample_depth)-1;
double in_min = ceil((in-err)*max - digitization_error);
double in_max = floor((in+err)*max + digitization_error);
if (err > limit || !(out >= in_min && out <= in_max))
{
char message[256];
size_t pos;
pos = safecat(message, sizeof message, 0, name);
pos = safecat(message, sizeof message, pos, " output value error: rgba(");
pos = safecatn(message, sizeof message, pos, r);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, g);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, b);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, a);
pos = safecat(message, sizeof message, pos, "): ");
pos = safecatn(message, sizeof message, pos, out);
pos = safecat(message, sizeof message, pos, " expected: ");
pos = safecatn(message, sizeof message, pos, in_digitized);
pos = safecat(message, sizeof message, pos, " (");
pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
pos = safecat(message, sizeof message, pos, "..");
pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
pos = safecat(message, sizeof message, pos, ")");
png_error(pp, message);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | transform_range_check(png_const_structp pp, unsigned int r, unsigned int g,
unsigned int b, unsigned int a, unsigned int in_digitized, double in,
unsigned int out, png_byte sample_depth, double err, double limit,
const char *name, double digitization_error)
{
/* Compare the scaled, digitzed, values of our local calculation (in+-err)
* with the digitized values libpng produced; 'sample_depth' is the actual
* digitization depth of the libpng output colors (the bit depth except for
* palette images where it is always 8.) The check on 'err' is to detect
* internal errors in pngvalid itself.
*/
unsigned int max = (1U<<sample_depth)-1;
double in_min = ceil((in-err)*max - digitization_error);
double in_max = floor((in+err)*max + digitization_error);
if (err > limit || !(out >= in_min && out <= in_max))
{
char message[256];
size_t pos;
pos = safecat(message, sizeof message, 0, name);
pos = safecat(message, sizeof message, pos, " output value error: rgba(");
pos = safecatn(message, sizeof message, pos, r);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, g);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, b);
pos = safecat(message, sizeof message, pos, ",");
pos = safecatn(message, sizeof message, pos, a);
pos = safecat(message, sizeof message, pos, "): ");
pos = safecatn(message, sizeof message, pos, out);
pos = safecat(message, sizeof message, pos, " expected: ");
pos = safecatn(message, sizeof message, pos, in_digitized);
pos = safecat(message, sizeof message, pos, " (");
pos = safecatd(message, sizeof message, pos, (in-err)*max, 3);
pos = safecat(message, sizeof message, pos, "..");
pos = safecatd(message, sizeof message, pos, (in+err)*max, 3);
pos = safecat(message, sizeof message, pos, ")");
png_error(pp, message);
}
}
| 173,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) {
if (!m_debug.infile) {
int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.infile_name, size);
}
m_debug.infile = fopen (m_debug.infile_name, "ab");
if (!m_debug.infile) {
DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name);
m_debug.infile_name[0] = '\0';
return -1;
}
}
if (m_debug.infile && pbuffer && pbuffer->nFilledLen) {
unsigned long i, msize;
int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width);
int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height);
unsigned char *pvirt,*ptemp;
char *temp = (char *)pbuffer->pBuffer;
msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height);
if (metadatamode == 1) {
pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset);
if (pvirt) {
ptemp = pvirt;
for (i = 0; i < m_sVenc_cfg.input_height; i++) {
fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile);
ptemp += stride;
}
ptemp = pvirt + (stride * scanlines);
for(i = 0; i < m_sVenc_cfg.input_height/2; i++) {
fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile);
ptemp += stride;
}
munmap(pvirt, msize);
} else if (pvirt == MAP_FAILED) {
DEBUG_PRINT_ERROR("%s mmap failed", __func__);
return -1;
}
} else {
for (i = 0; i < m_sVenc_cfg.input_height; i++) {
fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile);
temp += stride;
}
temp = (char *)pbuffer->pBuffer + (stride * scanlines);
for(i = 0; i < m_sVenc_cfg.input_height/2; i++) {
fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile);
temp += stride;
}
}
}
return 0;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) {
if (venc_handle->is_secure_session()) {
DEBUG_PRINT_ERROR("logging secure input buffers is not allowed!");
return -1;
}
if (!m_debug.infile) {
int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, "%s/input_enc_%lu_%lu_%p.yuv",
m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this);
if ((size > PROPERTY_VALUE_MAX) && (size < 0)) {
DEBUG_PRINT_ERROR("Failed to open output file: %s for logging size:%d",
m_debug.infile_name, size);
}
m_debug.infile = fopen (m_debug.infile_name, "ab");
if (!m_debug.infile) {
DEBUG_PRINT_HIGH("Failed to open input file: %s for logging", m_debug.infile_name);
m_debug.infile_name[0] = '\0';
return -1;
}
}
if (m_debug.infile && pbuffer && pbuffer->nFilledLen) {
unsigned long i, msize;
int stride = VENUS_Y_STRIDE(COLOR_FMT_NV12, m_sVenc_cfg.input_width);
int scanlines = VENUS_Y_SCANLINES(COLOR_FMT_NV12, m_sVenc_cfg.input_height);
unsigned char *pvirt,*ptemp;
char *temp = (char *)pbuffer->pBuffer;
msize = VENUS_BUFFER_SIZE(COLOR_FMT_NV12, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height);
if (metadatamode == 1) {
pvirt= (unsigned char *)mmap(NULL, msize, PROT_READ|PROT_WRITE,MAP_SHARED, fd, plane_offset);
if (pvirt) {
ptemp = pvirt;
for (i = 0; i < m_sVenc_cfg.input_height; i++) {
fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile);
ptemp += stride;
}
ptemp = pvirt + (stride * scanlines);
for(i = 0; i < m_sVenc_cfg.input_height/2; i++) {
fwrite(ptemp, m_sVenc_cfg.input_width, 1, m_debug.infile);
ptemp += stride;
}
munmap(pvirt, msize);
} else if (pvirt == MAP_FAILED) {
DEBUG_PRINT_ERROR("%s mmap failed", __func__);
return -1;
}
} else {
for (i = 0; i < m_sVenc_cfg.input_height; i++) {
fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile);
temp += stride;
}
temp = (char *)pbuffer->pBuffer + (stride * scanlines);
for(i = 0; i < m_sVenc_cfg.input_height/2; i++) {
fwrite(temp, m_sVenc_cfg.input_width, 1, m_debug.infile);
temp += stride;
}
}
}
return 0;
}
| 173,506 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int page_index = 0;
if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
url_substr[0], page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void PrintPreviewDataSource::StartDataRequest(const std::string& path,
bool is_incognito,
int request_id) {
if (!EndsWith(path, "/print.pdf", true)) {
ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id);
return;
}
scoped_refptr<base::RefCountedBytes> data;
std::vector<std::string> url_substr;
base::SplitString(path, '/', &url_substr);
int preview_ui_id = -1;
int page_index = 0;
if (url_substr.size() == 3 &&
base::StringToInt(url_substr[0], &preview_ui_id),
base::StringToInt(url_substr[1], &page_index) &&
preview_ui_id >= 0) {
PrintPreviewDataService::GetInstance()->GetDataEntry(
preview_ui_id, page_index, &data);
}
if (data.get()) {
SendResponse(request_id, data);
return;
}
scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes);
SendResponse(request_id, empty_bytes);
}
| 170,827 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 trigger_fpga_config(void)
{
int ret = 0, init_l;
/* approx 10ms */
u32 timeout = 10000;
/* make sure the FPGA_can access the EEPROM */
toggle_fpga_eeprom_bus(false);
/* assert CONF_SEL_L to be able to drive FPGA_PROG_L */
qrio_gpio_direction_output(GPIO_A, CONF_SEL_L, 0);
/* trigger the config start */
qrio_gpio_direction_output(GPIO_A, FPGA_PROG_L, 0);
/* small delay for INIT_L line */
udelay(10);
/* wait for FPGA_INIT to be asserted */
do {
init_l = qrio_get_gpio(GPIO_A, FPGA_INIT_L);
if (timeout-- == 0) {
printf("FPGA_INIT timeout\n");
ret = -EFAULT;
break;
}
udelay(10);
} while (init_l);
/* deassert FPGA_PROG, config should start */
qrio_set_gpio(GPIO_A, FPGA_PROG_L, 1);
return ret;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787 | int trigger_fpga_config(void)
{
int ret = 0, init_l;
/* approx 10ms */
u32 timeout = 10000;
/* make sure the FPGA_can access the EEPROM */
toggle_fpga_eeprom_bus(false);
/* assert CONF_SEL_L to be able to drive FPGA_PROG_L */
qrio_gpio_direction_output(QRIO_GPIO_A, CONF_SEL_L, 0);
/* trigger the config start */
qrio_gpio_direction_output(QRIO_GPIO_A, FPGA_PROG_L, 0);
/* small delay for INIT_L line */
udelay(10);
/* wait for FPGA_INIT to be asserted */
do {
init_l = qrio_get_gpio(QRIO_GPIO_A, FPGA_INIT_L);
if (timeout-- == 0) {
printf("FPGA_INIT timeout\n");
ret = -EFAULT;
break;
}
udelay(10);
} while (init_l);
/* deassert FPGA_PROG, config should start */
qrio_set_gpio(QRIO_GPIO_A, FPGA_PROG_L, 1);
return ret;
}
| 169,635 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(imageloadfont)
{
char *file;
int file_name, hdr_size = sizeof(gdFont) - sizeof(char *);
int ind, body_size, n = 0, b, i, body_size_check;
gdFontPtr font;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &file, &file_name) == FAILURE) {
return;
}
stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
/* Only supports a architecture-dependent binary dump format
* at the moment.
* The file format is like this on machines with 32-byte integers:
*
* byte 0-3: (int) number of characters in the font
* byte 4-7: (int) value of first character in the font (often 32, space)
* byte 8-11: (int) pixel width of each character
* byte 12-15: (int) pixel height of each character
* bytes 16-: (char) array with character data, one byte per pixel
* in each character, for a total of
* (nchars*width*height) bytes.
*/
font = (gdFontPtr) emalloc(sizeof(gdFont));
b = 0;
while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {
b += n;
}
if (!n) {
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header");
}
php_stream_close(stream);
RETURN_FALSE;
}
i = php_stream_tell(stream);
php_stream_seek(stream, 0, SEEK_END);
body_size_check = php_stream_tell(stream) - hdr_size;
php_stream_seek(stream, i, SEEK_SET);
body_size = font->w * font->h * font->nchars;
if (body_size != body_size_check) {
font->w = FLIPWORD(font->w);
font->h = FLIPWORD(font->h);
font->nchars = FLIPWORD(font->nchars);
body_size = font->w * font->h * font->nchars;
}
if (overflow2(font->nchars, font->h)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (overflow2(font->nchars * font->h, font->w )) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (body_size != body_size_check) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
font->data = emalloc(body_size);
b = 0;
while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {
b += n;
}
if (!n) {
efree(font->data);
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body");
}
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_close(stream);
/* Adding 5 to the font index so we will never have font indices
* that overlap with the old fonts (with indices 1-5). The first
* list index given out is always 1.
*/
ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);
RETURN_LONG(ind);
}
Commit Message:
CWE ID: CWE-254 | PHP_FUNCTION(imageloadfont)
{
char *file;
int file_name, hdr_size = sizeof(gdFont) - sizeof(char *);
int ind, body_size, n = 0, b, i, body_size_check;
gdFontPtr font;
php_stream *stream;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &file, &file_name) == FAILURE) {
return;
}
stream = php_stream_open_wrapper(file, "rb", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);
if (stream == NULL) {
RETURN_FALSE;
}
/* Only supports a architecture-dependent binary dump format
* at the moment.
* The file format is like this on machines with 32-byte integers:
*
* byte 0-3: (int) number of characters in the font
* byte 4-7: (int) value of first character in the font (often 32, space)
* byte 8-11: (int) pixel width of each character
* byte 12-15: (int) pixel height of each character
* bytes 16-: (char) array with character data, one byte per pixel
* in each character, for a total of
* (nchars*width*height) bytes.
*/
font = (gdFontPtr) emalloc(sizeof(gdFont));
b = 0;
while (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {
b += n;
}
if (!n) {
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading header");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading header");
}
php_stream_close(stream);
RETURN_FALSE;
}
i = php_stream_tell(stream);
php_stream_seek(stream, 0, SEEK_END);
body_size_check = php_stream_tell(stream) - hdr_size;
php_stream_seek(stream, i, SEEK_SET);
body_size = font->w * font->h * font->nchars;
if (body_size != body_size_check) {
font->w = FLIPWORD(font->w);
font->h = FLIPWORD(font->h);
font->nchars = FLIPWORD(font->nchars);
body_size = font->w * font->h * font->nchars;
}
if (overflow2(font->nchars, font->h)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (overflow2(font->nchars * font->h, font->w )) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font, invalid font header");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
if (body_size != body_size_check) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error reading font");
efree(font);
php_stream_close(stream);
RETURN_FALSE;
}
font->data = emalloc(body_size);
b = 0;
while (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {
b += n;
}
if (!n) {
efree(font->data);
efree(font);
if (php_stream_eof(stream)) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "End of file while reading body");
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error while reading body");
}
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_close(stream);
/* Adding 5 to the font index so we will never have font indices
* that overlap with the old fonts (with indices 1-5). The first
* list index given out is always 1.
*/
ind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);
RETURN_LONG(ind);
}
| 165,311 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: poly_path(PG_FUNCTION_ARGS)
{
POLYGON *poly = PG_GETARG_POLYGON_P(0);
PATH *path;
int size;
int i;
size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts;
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = poly->npts;
path->closed = TRUE;
/* prevent instability in unused pad bytes */
path->dummy = 0;
for (i = 0; i < poly->npts; i++)
{
path->p[i].x = poly->p[i].x;
path->p[i].y = poly->p[i].y;
}
PG_RETURN_PATH_P(path);
}
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 | poly_path(PG_FUNCTION_ARGS)
{
POLYGON *poly = PG_GETARG_POLYGON_P(0);
PATH *path;
int size;
int i;
/*
* Never overflows: the old size fit in MaxAllocSize, and the new size is
* smaller by a small constant.
*/
size = offsetof(PATH, p[0]) +sizeof(path->p[0]) * poly->npts;
path = (PATH *) palloc(size);
SET_VARSIZE(path, size);
path->npts = poly->npts;
path->closed = TRUE;
/* prevent instability in unused pad bytes */
path->dummy = 0;
for (i = 0; i < poly->npts; i++)
{
path->p[i].x = poly->p[i].x;
path->p[i].y = poly->p[i].y;
}
PG_RETURN_PATH_P(path);
}
| 166,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: static inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = send(signal_fds[1], &sig_on, sizeof(sig_on), 0);
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
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 inline int btif_hl_close_select_thread(void)
{
int result = 0;
char sig_on = btif_hl_signal_select_exit;
BTIF_TRACE_DEBUG("btif_hl_signal_select_exit");
result = TEMP_FAILURE_RETRY(send(signal_fds[1], &sig_on, sizeof(sig_on), 0));
if (btif_is_enabled())
{
/* Wait for the select_thread_id to exit if BT is still enabled
and only this profile getting cleaned up*/
if (select_thread_id != -1) {
pthread_join(select_thread_id, NULL);
select_thread_id = -1;
}
}
list_free(soc_queue);
return result;
}
| 173,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = malloc(w * sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
ptr = im->data;
per_inc = 100.0 / (((float)w) * h);
for (i = 0; i < h; i++)
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
}
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
last_per = (int)per;
if (!(progress(im, (int)per, 0, last_y, w, i)))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
Commit Message:
CWE ID: CWE-20 | load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity,
char immediate_load)
{
static const int intoffset[] = { 0, 4, 2, 1 };
static const int intjump[] = { 8, 8, 4, 2 };
int rc;
DATA32 *ptr;
GifFileType *gif;
GifRowType *rows;
GifRecordType rec;
ColorMapObject *cmap;
int i, j, done, bg, r, g, b, w = 0, h = 0;
float per = 0.0, per_inc;
int last_per = 0, last_y = 0;
int transp;
int fd;
done = 0;
rows = NULL;
transp = -1;
/* if immediate_load is 1, then dont delay image laoding as below, or */
/* already data in this image - dont load it again */
if (im->data)
return 0;
fd = open(im->real_file, O_RDONLY);
if (fd < 0)
return 0;
#if GIFLIB_MAJOR >= 5
gif = DGifOpenFileHandle(fd, NULL);
#else
gif = DGifOpenFileHandle(fd);
#endif
if (!gif)
{
close(fd);
return 0;
}
rc = 0; /* Failure */
do
{
if (DGifGetRecordType(gif, &rec) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done))
{
if (DGifGetImageDesc(gif) == GIF_ERROR)
{
/* PrintGifError(); */
rec = TERMINATE_RECORD_TYPE;
}
w = gif->Image.Width;
h = gif->Image.Height;
if (!IMAGE_DIMENSIONS_OK(w, h))
goto quit2;
rows = calloc(h, sizeof(GifRowType *));
if (!rows)
goto quit2;
for (i = 0; i < h; i++)
{
rows[i] = malloc(w * sizeof(GifPixelType));
if (!rows[i])
goto quit;
}
if (gif->Image.Interlace)
{
for (i = 0; i < 4; i++)
{
for (j = intoffset[i]; j < h; j += intjump[i])
{
DGifGetLine(gif, rows[j], w);
}
}
}
else
{
for (i = 0; i < h; i++)
{
DGifGetLine(gif, rows[i], w);
}
}
done = 1;
}
else if (rec == EXTENSION_RECORD_TYPE)
{
int ext_code;
GifByteType *ext;
ext = NULL;
DGifGetExtension(gif, &ext_code, &ext);
while (ext)
{
if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0))
{
transp = (int)ext[4];
}
ext = NULL;
DGifGetExtensionNext(gif, &ext);
}
}
}
while (rec != TERMINATE_RECORD_TYPE);
if (transp >= 0)
{
SET_FLAG(im->flags, F_HAS_ALPHA);
}
else
{
UNSET_FLAG(im->flags, F_HAS_ALPHA);
}
/* set the format string member to the lower-case full extension */
/* name for the format - so example names would be: */
/* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */
im->w = w;
im->h = h;
if (!im->format)
im->format = strdup("gif");
if (im->loader || immediate_load || progress)
{
bg = gif->SBackGroundColor;
cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap);
im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h);
if (!im->data)
goto quit;
if (!cmap)
{
/* No colormap? Now what?? Let's clear the image (and not segv) */
memset(im->data, 0, sizeof(DATA32) * w * h);
rc = 1;
goto finish;
}
ptr = im->data;
per_inc = 100.0 / (((float)w) * h);
for (i = 0; i < h; i++)
*ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b);
}
else
{
r = cmap->Colors[rows[i][j]].Red;
g = cmap->Colors[rows[i][j]].Green;
b = cmap->Colors[rows[i][j]].Blue;
*ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b;
}
per += per_inc;
if (progress && (((int)per) != last_per)
&& (((int)per) % progress_granularity == 0))
{
last_per = (int)per;
if (!(progress(im, (int)per, 0, last_y, w, i)))
{
rc = 2;
goto quit;
}
last_y = i;
}
}
| 165,340 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mntput_no_expire(struct mount *mnt)
{
rcu_read_lock();
mnt_add_count(mnt, -1);
if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */
rcu_read_unlock();
return;
}
lock_mount_hash();
if (mnt_get_count(mnt)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
mnt->mnt.mnt_flags |= MNT_DOOMED;
rcu_read_unlock();
list_del(&mnt->mnt_instance);
unlock_mount_hash();
if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) {
struct task_struct *task = current;
if (likely(!(task->flags & PF_KTHREAD))) {
init_task_work(&mnt->mnt_rcu, __cleanup_mnt);
if (!task_work_add(task, &mnt->mnt_rcu, true))
return;
}
if (llist_add(&mnt->mnt_llist, &delayed_mntput_list))
schedule_delayed_work(&delayed_mntput_work, 1);
return;
}
cleanup_mnt(mnt);
}
Commit Message: mnt: Honor MNT_LOCKED when detaching mounts
Modify umount(MNT_DETACH) to keep mounts in the hash table that are
locked to their parent mounts, when the parent is lazily unmounted.
In mntput_no_expire detach the children from the hash table, depending
on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.
In __detach_mounts if there are any mounts that have been unmounted
but still are on the list of mounts of a mountpoint, remove their
children from the mount hash table and those children to the unmounted
list so they won't linger potentially indefinitely waiting for their
final mntput, now that the mounts serve no purpose.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-284 | static void mntput_no_expire(struct mount *mnt)
{
rcu_read_lock();
mnt_add_count(mnt, -1);
if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */
rcu_read_unlock();
return;
}
lock_mount_hash();
if (mnt_get_count(mnt)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) {
rcu_read_unlock();
unlock_mount_hash();
return;
}
mnt->mnt.mnt_flags |= MNT_DOOMED;
rcu_read_unlock();
list_del(&mnt->mnt_instance);
if (unlikely(!list_empty(&mnt->mnt_mounts))) {
struct mount *p, *tmp;
list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) {
umount_mnt(p);
}
}
unlock_mount_hash();
if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) {
struct task_struct *task = current;
if (likely(!(task->flags & PF_KTHREAD))) {
init_task_work(&mnt->mnt_rcu, __cleanup_mnt);
if (!task_work_add(task, &mnt->mnt_rcu, true))
return;
}
if (llist_add(&mnt->mnt_llist, &delayed_mntput_list))
schedule_delayed_work(&delayed_mntput_work, 1);
return;
}
cleanup_mnt(mnt);
}
| 167,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags)
{
struct mm_struct *mm = vma->vm_mm;
struct dev_pagemap *pgmap = NULL;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !pte_write(pte)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
pgmap = get_dev_pagemap(pte_pfn(pte), NULL);
if (pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET) {
get_page(page);
/* drop the pgmap reference now that we hold the page */
if (pgmap) {
put_dev_pagemap(pgmap);
pgmap = NULL;
}
}
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
Commit Message: mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
This is an ancient bug that was actually attempted to be fixed once
(badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
get_user_pages() race for write access") but that was then undone due to
problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").
In the meantime, the s390 situation has long been fixed, and we can now
fix it by checking the pte_dirty() bit properly (and do it better). The
s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
software dirty bits") which made it into v3.9. Earlier kernels will
have to look at the page state itself.
Also, the VM has become more scalable, and what used a purely
theoretical race back then has become easier to trigger.
To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
we already did a COW" rather than play racy games with FOLL_WRITE that
is very fundamental, and then use the pte dirty flag to validate that
the FOLL_COW flag is still valid.
Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
Acked-by: Hugh Dickins <[email protected]>
Reviewed-by: Michal Hocko <[email protected]>
Cc: Andy Lutomirski <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Nick Piggin <[email protected]>
Cc: Greg Thelen <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags)
{
struct mm_struct *mm = vma->vm_mm;
struct dev_pagemap *pgmap = NULL;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
pgmap = get_dev_pagemap(pte_pfn(pte), NULL);
if (pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET) {
get_page(page);
/* drop the pgmap reference now that we hold the page */
if (pgmap) {
put_dev_pagemap(pgmap);
pgmap = NULL;
}
}
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
| 167,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nested_vmx_check_permission(struct kvm_vcpu *vcpu)
{
if (!to_vmx(vcpu)->nested.vmxon) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
return 1;
}
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: [email protected]
Signed-off-by: Felix Wilhelm <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int nested_vmx_check_permission(struct kvm_vcpu *vcpu)
{
if (vmx_get_cpl(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
if (!to_vmx(vcpu)->nested.vmxon) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
return 1;
}
| 169,176 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock)
{
struct tcp_conn_t *conn = calloc(1, sizeof *conn);
if (conn == NULL) {
ERR("Calloc for connection struct failed");
goto error;
}
conn->sd = accept(sock->sd, NULL, NULL);
if (conn->sd < 0) {
ERR("accept failed");
goto error;
}
return conn;
error:
if (conn != NULL)
free(conn);
return NULL;
}
Commit Message: SECURITY FIX: Actually restrict the access to the printer to localhost
Before, any machine in any network connected by any of the interfaces (as
listed by "ifconfig") could access to an IPP-over-USB printer on the assigned
port, allowing users on remote machines to print and to access the web
configuration interface of a IPP-over-USB printer in contrary to conventional
USB printers which are only accessible locally.
CWE ID: CWE-264 | struct tcp_conn_t *tcp_conn_accept(struct tcp_sock_t *sock)
struct tcp_conn_t *tcp_conn_select(struct tcp_sock_t *sock,
struct tcp_sock_t *sock6)
{
struct tcp_conn_t *conn = calloc(1, sizeof *conn);
if (conn == NULL) {
ERR("Calloc for connection struct failed");
goto error;
}
fd_set rfds;
struct timeval tv;
int retval = 0;
int nfds = 0;
while (retval == 0) {
FD_ZERO(&rfds);
if (sock) {
FD_SET(sock->sd, &rfds);
nfds = sock->sd;
}
if (sock6) {
FD_SET(sock6->sd, &rfds);
if (sock6->sd > nfds)
nfds = sock6->sd;
}
if (nfds == 0) {
ERR("No valid TCP socket supplied.");
goto error;
}
nfds += 1;
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(nfds, &rfds, NULL, NULL, &tv);
if (retval == -1) {
ERR("Failed to open tcp connection");
goto error;
}
}
if (sock && FD_ISSET(sock->sd, &rfds)) {
conn->sd = accept(sock->sd, NULL, NULL);
NOTE ("Using IPv4");
} else if (sock6 && FD_ISSET(sock6->sd, &rfds)) {
conn->sd = accept(sock6->sd, NULL, NULL);
NOTE ("Using IPv6");
} else {
ERR("select failed");
goto error;
}
if (conn->sd < 0) {
ERR("accept failed");
goto error;
}
return conn;
error:
if (conn != NULL)
free(conn);
return NULL;
}
| 166,589 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uinput_create(char *name)
{
struct uinput_dev dev;
int fd, x = 0;
for(x=0; x < MAX_UINPUT_PATHS; x++)
{
fd = open(uinput_dev_path[x], O_RDWR);
if (fd < 0)
continue;
break;
}
if (x == MAX_UINPUT_PATHS) {
BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__);
return -1;
}
memset(&dev, 0, sizeof(dev));
if (name)
strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1);
dev.id.bustype = BUS_BLUETOOTH;
dev.id.vendor = 0x0000;
dev.id.product = 0x0000;
dev.id.version = 0x0000;
if (write(fd, &dev, sizeof(dev)) < 0) {
BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__);
close(fd);
return -1;
}
ioctl(fd, UI_SET_EVBIT, EV_KEY);
ioctl(fd, UI_SET_EVBIT, EV_REL);
ioctl(fd, UI_SET_EVBIT, EV_SYN);
for (x = 0; key_map[x].name != NULL; x++)
ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id);
if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__);
close(fd);
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 | int uinput_create(char *name)
{
struct uinput_dev dev;
int fd, x = 0;
for(x=0; x < MAX_UINPUT_PATHS; x++)
{
fd = TEMP_FAILURE_RETRY(open(uinput_dev_path[x], O_RDWR));
if (fd < 0)
continue;
break;
}
if (x == MAX_UINPUT_PATHS) {
BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__);
return -1;
}
memset(&dev, 0, sizeof(dev));
if (name)
strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1);
dev.id.bustype = BUS_BLUETOOTH;
dev.id.vendor = 0x0000;
dev.id.product = 0x0000;
dev.id.version = 0x0000;
if (TEMP_FAILURE_RETRY(write(fd, &dev, sizeof(dev))) < 0) {
BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__);
close(fd);
return -1;
}
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_KEY));
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_REL));
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_SYN));
for (x = 0; key_map[x].name != NULL; x++)
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id));
if (TEMP_FAILURE_RETRY(ioctl(fd, UI_DEV_CREATE, NULL)) < 0) {
BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__);
close(fd);
return -1;
}
return fd;
}
| 173,452 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: zstatus(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
switch (r_type(op)) {
case t_file:
{
stream *s;
make_bool(op, (file_is_valid(s, op) ? 1 : 0));
}
return 0;
case t_string:
{
gs_parsed_file_name_t pname;
struct stat fstat;
int code = parse_file_name(op, &pname,
i_ctx_p->LockFilePermissions, imemory);
if (code < 0) {
if (code == gs_error_undefinedfilename) {
make_bool(op, 0);
code = 0;
}
return code;
}
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = (*pname.iodev->procs.file_status)(pname.iodev,
pname.fname, &fstat);
switch (code) {
case 0:
check_ostack(4);
make_int(op - 4, stat_blocks(&fstat));
make_int(op - 3, fstat.st_size);
/*
* We can't check the value simply by using ==,
* because signed/unsigned == does the wrong thing.
* Instead, since integer assignment only keeps the
* bottom bits, we convert the values to double
* and then test for equality. This handles all
* cases of signed/unsigned or width mismatch.
*/
if ((double)op[-4].value.intval !=
(double)stat_blocks(&fstat) ||
(double)op[-3].value.intval !=
(double)fstat.st_size
)
return_error(gs_error_limitcheck);
make_int(op - 2, fstat.st_mtime);
make_int(op - 1, fstat.st_ctime);
make_bool(op, 1);
break;
case gs_error_undefinedfilename:
make_bool(op, 0);
code = 0;
}
gs_free_file_name(&pname, "status");
return code;
}
default:
return_op_typecheck(op);
}
}
Commit Message:
CWE ID: CWE-200 | zstatus(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
switch (r_type(op)) {
case t_file:
{
stream *s;
make_bool(op, (file_is_valid(s, op) ? 1 : 0));
}
return 0;
case t_string:
{
gs_parsed_file_name_t pname;
struct stat fstat;
int code = parse_file_name(op, &pname,
i_ctx_p->LockFilePermissions, imemory);
if (code < 0) {
if (code == gs_error_undefinedfilename) {
make_bool(op, 0);
code = 0;
}
return code;
}
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
code = gs_terminate_file_name(&pname, imemory, "status");
if (code < 0)
return code;
if ((code = check_file_permissions(i_ctx_p, pname.fname, pname.len,
"PermitFileReading")) >= 0) {
code = (*pname.iodev->procs.file_status)(pname.iodev,
pname.fname, &fstat);
}
switch (code) {
case 0:
check_ostack(4);
make_int(op - 4, stat_blocks(&fstat));
make_int(op - 3, fstat.st_size);
/*
* We can't check the value simply by using ==,
* because signed/unsigned == does the wrong thing.
* Instead, since integer assignment only keeps the
* bottom bits, we convert the values to double
* and then test for equality. This handles all
* cases of signed/unsigned or width mismatch.
*/
if ((double)op[-4].value.intval !=
(double)stat_blocks(&fstat) ||
(double)op[-3].value.intval !=
(double)fstat.st_size
)
return_error(gs_error_limitcheck);
make_int(op - 2, fstat.st_mtime);
make_int(op - 1, fstat.st_ctime);
make_bool(op, 1);
break;
case gs_error_undefinedfilename:
make_bool(op, 0);
code = 0;
}
gs_free_file_name(&pname, "status");
return code;
}
default:
return_op_typecheck(op);
}
}
| 164,829 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
Commit Message: Fix MediaObserver notifications in MediaStreamManager.
This CL fixes the stream type used to notify MediaObserver about
cancelled MediaStream requests.
Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate
that all stream types should be cancelled.
However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this
way and the request to update the UI is ignored.
This CL sends a separate notification for each stream type so that the
UI actually gets updated for all stream types in use.
Bug: 816033
Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405
Reviewed-on: https://chromium-review.googlesource.com/939630
Commit-Queue: Guido Urdaneta <[email protected]>
Reviewed-by: Raymes Khoury <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540122}
CWE ID: CWE-20 | MediaStreamManagerTest()
: thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP) {
audio_manager_ = std::make_unique<MockAudioManager>();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
auto video_capture_provider = std::make_unique<MockVideoCaptureProvider>();
video_capture_provider_ = video_capture_provider.get();
media_stream_manager_ = std::make_unique<MediaStreamManager>(
audio_system_.get(), audio_manager_->GetTaskRunner(),
std::move(video_capture_provider));
media_observer_ = std::make_unique<MockMediaObserver>();
browser_content_client_ =
std::make_unique<TestBrowserClient>(media_observer_.get());
SetBrowserClientForTesting(browser_content_client_.get());
base::RunLoop().RunUntilIdle();
ON_CALL(*video_capture_provider_, DoGetDeviceInfosAsync(_))
.WillByDefault(Invoke(
[](VideoCaptureProvider::GetDeviceInfosCallback& result_callback) {
std::vector<media::VideoCaptureDeviceInfo> stub_results;
base::ResetAndReturn(&result_callback).Run(stub_results);
}));
}
| 172,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, extractTo)
{
char *error = NULL;
php_stream *fp;
php_stream_statbuf ssb;
phar_entry_info *entry;
char *pathto, *filename;
size_t pathto_len, filename_len;
int ret, i;
int nelems;
zval *zval_files = NULL;
zend_bool overwrite = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) {
return;
}
fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL);
if (!fp) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, %s cannot be found", phar_obj->archive->fname);
return;
}
php_stream_close(fp);
if (pathto_len < 1) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, extraction path must be non-zero length");
return;
}
if (pathto_len >= MAXPATHLEN) {
char *tmp = estrndup(pathto, 50);
/* truncate for error message */
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp);
efree(tmp);
return;
}
if (php_stream_stat_path(pathto, &ssb) < 0) {
ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL);
if (!ret) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Unable to create path \"%s\" for extraction", pathto);
return;
}
} else if (!(ssb.sb.st_mode & S_IFDIR)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto);
return;
}
if (zval_files) {
switch (Z_TYPE_P(zval_files)) {
case IS_NULL:
goto all_files;
case IS_STRING:
filename = Z_STRVAL_P(zval_files);
filename_len = Z_STRLEN_P(zval_files);
break;
case IS_ARRAY:
nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files));
if (nelems == 0 ) {
RETURN_FALSE;
}
for (i = 0; i < nelems; i++) {
zval *zval_file;
if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) {
switch (Z_TYPE_P(zval_file)) {
case IS_STRING:
break;
default:
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, array of filenames to extract contains non-string value");
return;
}
if (NULL == (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, Z_STR_P(zval_file)))) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_P(zval_file), phar_obj->archive->fname);
}
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error);
efree(error);
return;
}
}
}
RETURN_TRUE;
default:
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, expected a filename (string) or array of filenames");
return;
}
if (NULL == (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, filename, filename_len))) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->archive->fname);
return;
}
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error);
efree(error);
return;
}
} else {
phar_archive_data *phar;
all_files:
phar = phar_obj->archive;
/* Extract all files */
if (!zend_hash_num_elements(&(phar->manifest))) {
RETURN_TRUE;
}
ZEND_HASH_FOREACH_PTR(&phar->manifest, entry) {
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar->fname, error);
efree(error);
return;
}
} ZEND_HASH_FOREACH_END();
}
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, extractTo)
{
char *error = NULL;
php_stream *fp;
php_stream_statbuf ssb;
phar_entry_info *entry;
char *pathto, *filename;
size_t pathto_len, filename_len;
int ret, i;
int nelems;
zval *zval_files = NULL;
zend_bool overwrite = 0;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|z!b", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) {
return;
}
fp = php_stream_open_wrapper(phar_obj->archive->fname, "rb", IGNORE_URL|STREAM_MUST_SEEK, NULL);
if (!fp) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, %s cannot be found", phar_obj->archive->fname);
return;
}
php_stream_close(fp);
if (pathto_len < 1) {
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, extraction path must be non-zero length");
return;
}
if (pathto_len >= MAXPATHLEN) {
char *tmp = estrndup(pathto, 50);
/* truncate for error message */
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0, "Cannot extract to \"%s...\", destination directory is too long for filesystem", tmp);
efree(tmp);
return;
}
if (php_stream_stat_path(pathto, &ssb) < 0) {
ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL);
if (!ret) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Unable to create path \"%s\" for extraction", pathto);
return;
}
} else if (!(ssb.sb.st_mode & S_IFDIR)) {
zend_throw_exception_ex(spl_ce_RuntimeException, 0,
"Unable to use path \"%s\" for extraction, it is a file, must be a directory", pathto);
return;
}
if (zval_files) {
switch (Z_TYPE_P(zval_files)) {
case IS_NULL:
goto all_files;
case IS_STRING:
filename = Z_STRVAL_P(zval_files);
filename_len = Z_STRLEN_P(zval_files);
break;
case IS_ARRAY:
nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files));
if (nelems == 0 ) {
RETURN_FALSE;
}
for (i = 0; i < nelems; i++) {
zval *zval_file;
if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) {
switch (Z_TYPE_P(zval_file)) {
case IS_STRING:
break;
default:
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, array of filenames to extract contains non-string value");
return;
}
if (NULL == (entry = zend_hash_find_ptr(&phar_obj->archive->manifest, Z_STR_P(zval_file)))) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", Z_STRVAL_P(zval_file), phar_obj->archive->fname);
}
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error);
efree(error);
return;
}
}
}
RETURN_TRUE;
default:
zend_throw_exception_ex(spl_ce_InvalidArgumentException, 0,
"Invalid argument, expected a filename (string) or array of filenames");
return;
}
if (NULL == (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, filename, filename_len))) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Phar Error: attempted to extract non-existent file \"%s\" from phar \"%s\"", filename, phar_obj->archive->fname);
return;
}
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar_obj->archive->fname, error);
efree(error);
return;
}
} else {
phar_archive_data *phar;
all_files:
phar = phar_obj->archive;
/* Extract all files */
if (!zend_hash_num_elements(&(phar->manifest))) {
RETURN_TRUE;
}
ZEND_HASH_FOREACH_PTR(&phar->manifest, entry) {
if (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error)) {
zend_throw_exception_ex(phar_ce_PharException, 0,
"Extraction from phar \"%s\" failed: %s", phar->fname, error);
efree(error);
return;
}
} ZEND_HASH_FOREACH_END();
}
RETURN_TRUE;
}
| 165,072 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | sf_open (const char *path, int mode, SF_INFO *sfinfo)
{ SF_PRIVATE *psf ;
/* Ultimate sanity check. */
assert (sizeof (sf_count_t) == 8) ;
if ((psf = psf_allocate ()) == NULL)
{ sf_errno = SFE_MALLOC_FAILED ;
return NULL ;
} ;
psf_init_files (psf) ;
psf_log_printf (psf, "File : %s\n", path) ;
if (copy_filename (psf, path) != 0)
{ sf_errno = psf->error ;
return NULL ;
} ;
psf->file.mode = mode ;
if (strcmp (path, "-") == 0)
psf->error = psf_set_stdio (psf) ;
else
psf->error = psf_fopen (psf) ;
return psf_open_file (psf, sfinfo) ;
} /* sf_open */
| 170,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cipso_v4_req_delattr(struct request_sock *req)
{
struct ip_options *opt;
struct inet_request_sock *req_inet;
req_inet = inet_rsk(req);
opt = req_inet->opt;
if (opt == NULL || opt->cipso == 0)
return;
cipso_v4_delopt(&req_inet->opt);
}
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 | void cipso_v4_req_delattr(struct request_sock *req)
{
struct ip_options_rcu *opt;
struct inet_request_sock *req_inet;
req_inet = inet_rsk(req);
opt = req_inet->opt;
if (opt == NULL || opt->opt.cipso == 0)
return;
cipso_v4_delopt(&req_inet->opt);
}
| 165,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, as hardware has verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
Commit Message: kvm: nVMX: Enforce cpl=0 for VMX instructions
VMX instructions executed inside a L1 VM will always trigger a VM exit
even when executed with cpl 3. This means we must perform the
privilege check in software.
Fixes: 70f3aac964ae("kvm: nVMX: Remove superfluous VMX instruction fault checks")
Cc: [email protected]
Signed-off-by: Felix Wilhelm <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: | static int handle_vmread(struct kvm_vcpu *vcpu)
{
unsigned long field;
u64 field_value;
unsigned long exit_qualification = vmcs_readl(EXIT_QUALIFICATION);
u32 vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO);
gva_t gva = 0;
if (!nested_vmx_check_permission(vcpu))
return 1;
if (!nested_vmx_check_vmcs12(vcpu))
return kvm_skip_emulated_instruction(vcpu);
/* Decode instruction info and find the field to read */
field = kvm_register_readl(vcpu, (((vmx_instruction_info) >> 28) & 0xf));
/* Read the field, zero-extended to a u64 field_value */
if (vmcs12_read_any(vcpu, field, &field_value) < 0) {
nested_vmx_failValid(vcpu, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
return kvm_skip_emulated_instruction(vcpu);
}
/*
* Now copy part of this value to register or memory, as requested.
* Note that the number of bits actually copied is 32 or 64 depending
* on the guest's mode (32 or 64 bit), not on the given field's length.
*/
if (vmx_instruction_info & (1u << 10)) {
kvm_register_writel(vcpu, (((vmx_instruction_info) >> 3) & 0xf),
field_value);
} else {
if (get_vmx_mem_address(vcpu, exit_qualification,
vmx_instruction_info, true, &gva))
return 1;
/* _system ok, nested_vmx_check_permission has verified cpl=0 */
kvm_write_guest_virt_system(&vcpu->arch.emulate_ctxt, gva,
&field_value, (is_long_mode(vcpu) ? 8 : 4), NULL);
}
nested_vmx_succeed(vcpu);
return kvm_skip_emulated_instruction(vcpu);
}
| 169,175 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SaveCardBubbleControllerImpl::ReshowBubble() {
is_reshow_ = true;
AutofillMetrics::LogSaveCardPromptMetric(
AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_,
is_reshow_,
pref_service_->GetInteger(
prefs::kAutofillAcceptSaveCreditCardPromptState));
ShowBubble();
}
Commit Message: [autofill] Avoid duplicate instances of the SaveCardBubble.
autofill::SaveCardBubbleControllerImpl::ShowBubble() expects
(via DCHECK) to only be called when the save card bubble is
not already visible. This constraint is violated if the user
clicks multiple times on a submit button.
If the underlying page goes away, the last SaveCardBubbleView
created by the controller will be automatically cleaned up,
but any others are left visible on the screen... holding a
refence to a possibly-deleted controller.
This CL early exits the ShowBubbleFor*** and ReshowBubble logic
if the bubble is already visible.
BUG=708819
Review-Url: https://codereview.chromium.org/2862933002
Cr-Commit-Position: refs/heads/master@{#469768}
CWE ID: CWE-416 | void SaveCardBubbleControllerImpl::ReshowBubble() {
// Don't show the bubble if it's already visible.
if (save_card_bubble_view_)
return;
is_reshow_ = true;
AutofillMetrics::LogSaveCardPromptMetric(
AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_,
is_reshow_,
pref_service_->GetInteger(
prefs::kAutofillAcceptSaveCreditCardPromptState));
ShowBubble();
}
| 172,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: white_point(PNG_CONST color_encoding *encoding)
{
CIE_color white;
white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
return white;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | white_point(PNG_CONST color_encoding *encoding)
white_point(const color_encoding *encoding)
{
CIE_color white;
white.X = encoding->red.X + encoding->green.X + encoding->blue.X;
white.Y = encoding->red.Y + encoding->green.Y + encoding->blue.Y;
white.Z = encoding->red.Z + encoding->green.Z + encoding->blue.Z;
return white;
}
| 173,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad,
OnDidStartProvisionalLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
OnDocumentOnLoadCompleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
OnJavaScriptExecuteResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse,
OnSerializeAsMHTMLResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture,
OnSetHasReceivedUserGesture)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed,
OnStreamHandleConsumed)
IPC_END_MESSAGE_MAP()
return handled;
}
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: | bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
if (!render_frame_created_)
return false;
ScopedActiveURL scoped_active_url(this);
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
if (handled)
return true;
if (delegate_->OnMessageReceived(this, msg))
return true;
RenderFrameProxyHost* proxy =
frame_tree_node_->render_manager()->GetProxyToParent();
if (proxy && proxy->cross_process_frame_connector() &&
proxy->cross_process_frame_connector()->OnMessageReceived(msg))
return true;
handled = true;
IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddMessageToConsole,
OnDidAddMessageToConsole)
IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoad,
OnDidStartProvisionalLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
OnDidFailProvisionalLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
OnDidFailLoadWithError)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateState, OnUpdateState)
IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
OnDocumentOnLoadCompleted)
IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
OnJavaScriptExecuteResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_VisualStateResponse,
OnVisualStateResponse)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptDialog,
OnRunJavaScriptDialog)
IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
OnRunBeforeUnloadConfirm)
IPC_MESSAGE_HANDLER(FrameHostMsg_RunFileChooser, OnRunFileChooser)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
OnDidAccessInitialDocument)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeOpener, OnDidChangeOpener)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidAddContentSecurityPolicies,
OnDidAddContentSecurityPolicies)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFramePolicy,
OnDidChangeFramePolicy)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeFrameOwnerProperties,
OnDidChangeFrameOwnerProperties)
IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidBlockFramebust, OnDidBlockFramebust)
IPC_MESSAGE_HANDLER(FrameHostMsg_AbortNavigation, OnAbortNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_DispatchLoad, OnDispatchLoad)
IPC_MESSAGE_HANDLER(FrameHostMsg_ForwardResourceTimingToParent,
OnForwardResourceTimingToParent)
IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
OnTextSurroundingSelectionResponse)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
OnAccessibilityLocationChanges)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_FindInPageResult,
OnAccessibilityFindInPageResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_ChildFrameHitTestResult,
OnAccessibilityChildFrameHitTestResult)
IPC_MESSAGE_HANDLER(AccessibilityHostMsg_SnapshotResponse,
OnAccessibilitySnapshotResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_ToggleFullscreen, OnToggleFullscreen)
IPC_MESSAGE_HANDLER(FrameHostMsg_SuddenTerminationDisablerChanged,
OnSuddenTerminationDisablerChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartLoading, OnDidStartLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidStopLoading, OnDidStopLoading)
IPC_MESSAGE_HANDLER(FrameHostMsg_DidChangeLoadProgress,
OnDidChangeLoadProgress)
IPC_MESSAGE_HANDLER(FrameHostMsg_SerializeAsMHTMLResponse,
OnSerializeAsMHTMLResponse)
IPC_MESSAGE_HANDLER(FrameHostMsg_SelectionChanged, OnSelectionChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGesture,
OnSetHasReceivedUserGesture)
IPC_MESSAGE_HANDLER(FrameHostMsg_SetHasReceivedUserGestureBeforeNavigation,
OnSetHasReceivedUserGestureBeforeNavigation)
IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame,
OnScrollRectToVisibleInParentFrame)
IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus)
#if BUILDFLAG(USE_EXTERNAL_POPUP_MENU)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
#endif
IPC_MESSAGE_HANDLER(FrameHostMsg_RequestOverlayRoutingToken,
OnRequestOverlayRoutingToken)
IPC_MESSAGE_HANDLER(FrameHostMsg_ShowCreatedWindow, OnShowCreatedWindow)
IPC_MESSAGE_HANDLER(FrameHostMsg_StreamHandleConsumed,
OnStreamHandleConsumed)
IPC_END_MESSAGE_MAP()
return handled;
}
| 172,717 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Cluster* Segment::GetNext(const Cluster* pCurr)
{
assert(pCurr);
assert(pCurr != &m_eos);
assert(m_clusters);
long idx = pCurr->m_index;
if (idx >= 0)
{
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; //caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
}
assert(m_clusterPreloadCount > 0);
long long pos = pCurr->m_element_start;
assert(m_size >= 0); //TODO
const long long stop = m_start + m_size; //end of segment
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long id = ReadUInt(m_pReader, pos, len);
assert(id == 0x0F43B675); //Cluster ID
if (id != 0x0F43B675)
return NULL;
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size > 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
pos += size; //consume payload
}
long long off_next = 0;
while (pos < stop)
{
long len;
long long result = GetUIntLength(m_pReader, pos, len);
assert(result == 0);
assert((pos + len) <= stop); //TODO
if (result != 0)
return NULL;
const long long idpos = pos; //pos of next (potential) cluster
const long long id = ReadUInt(m_pReader, idpos, len);
assert(id > 0); //TODO
pos += len; //consume ID
result = GetUIntLength(m_pReader, pos, len);
assert(result == 0); //TODO
assert((pos + len) <= stop); //TODO
const long long size = ReadUInt(m_pReader, pos, len);
assert(size >= 0); //TODO
pos += len; //consume length of size of element
assert((pos + size) <= stop); //TODO
if (size == 0) //weird
continue;
if (id == 0x0F43B675) //Cluster ID
{
const long long off_next_ = idpos - m_start;
long long pos_;
long len_;
const long status = Cluster::HasBlockEntries(
this,
off_next_,
pos_,
len_);
assert(status >= 0);
if (status > 0)
{
off_next = off_next_;
break;
}
}
pos += size; //consume payload
}
if (off_next <= 0)
return 0;
Cluster** const ii = m_clusters + m_clusterCount;
Cluster** i = ii;
Cluster** const jj = ii + m_clusterPreloadCount;
Cluster** j = jj;
while (i < j)
{
Cluster** const k = i + (j - i) / 2;
assert(k < jj);
Cluster* const pNext = *k;
assert(pNext);
assert(pNext->m_index < 0);
pos = pNext->GetPosition();
if (pos < off_next)
i = k + 1;
else if (pos > off_next)
j = k;
else
return pNext;
}
assert(i == j);
Cluster* const pNext = Cluster::Create(this,
-1,
off_next);
assert(pNext);
const ptrdiff_t idx_next = i - m_clusters; //insertion position
PreloadCluster(pNext, idx_next);
assert(m_clusters);
assert(idx_next < m_clusterSize);
assert(m_clusters[idx_next] == pNext);
return pNext;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cluster* Segment::GetNext(const Cluster* pCurr)
if (idx >= 0) {
assert(m_clusterCount > 0);
assert(idx < m_clusterCount);
assert(pCurr == m_clusters[idx]);
++idx;
if (idx >= m_clusterCount)
return &m_eos; // caller will LoadCluster as desired
Cluster* const pNext = m_clusters[idx];
assert(pNext);
assert(pNext->m_index >= 0);
assert(pNext->m_index == idx);
return pNext;
| 174,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: PowerLibrary* CrosLibrary::GetPowerLibrary() {
return power_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | PowerLibrary* CrosLibrary::GetPowerLibrary() {
| 170,628 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "[email protected]";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
false /* enable_sync_tabs_for_other_clients */,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "[email protected]";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
| 170,799 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri)
{
int i;
uint32_t txr_len_log2, rxr_len_log2;
uint32_t req_ring_size, cmp_ring_size;
m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT;
if ((ri->reqRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)
|| (ri->cmpRingNumPages > PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)) {
return -1;
}
req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
txr_len_log2 = pvscsi_log2(req_ring_size - 1);
}
Commit Message:
CWE ID: CWE-125 | pvscsi_ring_init_data(PVSCSIRingInfo *m, PVSCSICmdDescSetupRings *ri)
{
int i;
uint32_t txr_len_log2, rxr_len_log2;
uint32_t req_ring_size, cmp_ring_size;
m->rs_pa = ri->ringsStatePPN << VMW_PAGE_SHIFT;
req_ring_size = ri->reqRingNumPages * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
cmp_ring_size = ri->cmpRingNumPages * PVSCSI_MAX_NUM_CMP_ENTRIES_PER_PAGE;
txr_len_log2 = pvscsi_log2(req_ring_size - 1);
}
| 164,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 size_t safecat(char *buffer, size_t bufsize, size_t pos,
PNG_CONST char *cat)
{
while (pos < bufsize && cat != NULL && *cat != 0)
buffer[pos++] = *cat++;
if (pos >= bufsize)
pos = bufsize-1;
buffer[pos] = 0;
return pos;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static size_t safecat(char *buffer, size_t bufsize, size_t pos,
const char *cat)
{
while (pos < bufsize && cat != NULL && *cat != 0)
buffer[pos++] = *cat++;
if (pos >= bufsize)
pos = bufsize-1;
buffer[pos] = 0;
return pos;
}
| 173,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type,
int bdlo, int PNG_CONST bdhi)
{
/* Run the tests on each combination.
*
* NOTE: on my 32 bit x86 each of the following blocks takes
* a total of 3.5 seconds if done across every combo of bit depth
* width and height. This is a waste of time in practice, hence the
* hinc and winc stuff:
*/
static PNG_CONST png_byte hinc[] = {1, 3, 11, 1, 5};
static PNG_CONST png_byte winc[] = {1, 9, 5, 7, 1};
for (; bdlo <= bdhi; ++bdlo)
{
png_uint_32 h, w;
for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
{
/* First test all the 'size' images against the sequential
* reader using libpng to deinterlace (where required.) This
* validates the write side of libpng. There are four possibilities
* to validate.
*/
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
/* Now validate the interlaced read side - do_interlace true,
* in the progressive case this does actually make a difference
* to the code used in the non-interlaced case too.
*/
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
}
}
return 1; /* keep going */
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type,
test_size(png_modifier* const pm, png_byte const colour_type,
int bdlo, int const bdhi)
{
/* Run the tests on each combination.
*
* NOTE: on my 32 bit x86 each of the following blocks takes
* a total of 3.5 seconds if done across every combo of bit depth
* width and height. This is a waste of time in practice, hence the
* hinc and winc stuff:
*/
static const png_byte hinc[] = {1, 3, 11, 1, 5};
static const png_byte winc[] = {1, 9, 5, 7, 1};
const int save_bdlo = bdlo;
for (; bdlo <= bdhi; ++bdlo)
{
png_uint_32 h, w;
for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
{
/* First test all the 'size' images against the sequential
* reader using libpng to deinterlace (where required.) This
* validates the write side of libpng. There are four possibilities
* to validate.
*/
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 0), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 1), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
/* Now validate the interlaced read side - do_interlace true,
* in the progressive case this does actually make a difference
* to the code used in the non-interlaced case too.
*/
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_NONE, w, h, 0), 1/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# if CAN_WRITE_INTERLACE
/* Validate the pngvalid code itself: */
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
}
}
/* Now do the tests of libpng interlace handling, after we have made sure
* that the pngvalid version works:
*/
for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo)
{
png_uint_32 h, w;
for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo])
{
# ifdef PNG_READ_INTERLACING_SUPPORTED
/* Test with pngvalid generated interlaced images first; we have
* already verify these are ok (unless pngvalid has self-consistent
* read/write errors, which is unlikely), so this detects errors in the
* read side first:
*/
# if CAN_WRITE_INTERLACE
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
# endif /* READ_INTERLACING */
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Test the libpng write side against the pngvalid read side: */
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
# ifdef PNG_READ_INTERLACING_SUPPORTED
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Test both together: */
standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/,
PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/,
pm->use_update_info);
if (fail(pm))
return 0;
# endif
# endif /* READ_INTERLACING */
}
}
return 1; /* keep going */
}
| 173,709 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LayoutSVGResourceMarker::calculateLocalTransform()
{
return selfNeedsLayout();
}
Commit Message: Avoid using forced layout to trigger paint invalidation for SVG containers
Currently, SVG containers in the LayoutObject hierarchy force layout of
their children if the transform changes. The main reason for this is to
trigger paint invalidation of the subtree. In some cases - changes to the
scale factor - there are other reasons to trigger layout, like computing
a new scale factor for <text> or re-layout nodes with non-scaling stroke.
Compute a "scale-factor change" in addition to the "transform change"
already computed, then use this new signal to determine if layout should
be forced for the subtree. Trigger paint invalidation using the
LayoutObject flags instead.
The downside to this is that paint invalidation will walk into "hidden"
containers which rarely require repaint (since they are not technically
visible). This will hopefully be rectified in a follow-up CL.
For the testcase from 603850, this essentially eliminates the cost of
layout (from ~350ms to ~0ms on authors machine; layout cost is related
to text metrics recalculation), bumping frame rate significantly.
BUG=603956,603850
Review-Url: https://codereview.chromium.org/1996543002
Cr-Commit-Position: refs/heads/master@{#400950}
CWE ID: | bool LayoutSVGResourceMarker::calculateLocalTransform()
LayoutSVGContainer::TransformChange LayoutSVGResourceMarker::calculateLocalTransform()
{
return selfNeedsLayout() ? TransformChange::Full : TransformChange::None;
}
| 171,665 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: s_aes_process(stream_state * ss, stream_cursor_read * pr,
stream_cursor_write * pw, bool last)
{
stream_aes_state *const state = (stream_aes_state *) ss;
const unsigned char *limit;
const long in_size = pr->limit - pr->ptr;
const long out_size = pw->limit - pw->ptr;
unsigned char temp[16];
int status = 0;
/* figure out if we're going to run out of space */
if (in_size > out_size) {
limit = pr->ptr + out_size;
status = 1; /* need more output space */
} else {
limit = pr->limit;
status = last ? EOFC : 0; /* need more input */
}
/* set up state and context */
if (state->ctx == NULL) {
/* allocate the aes context. this is a public struct but it
contains internal pointers, so we need to store it separately
in immovable memory like any opaque structure. */
state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory,
sizeof(aes_context), "aes context structure");
if (state->ctx == NULL) {
gs_throw(gs_error_VMerror, "could not allocate aes context");
return ERRC;
}
if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) {
gs_throw1(gs_error_rangecheck, "invalid aes key length (%d bytes)",
state->keylength);
}
aes_setkey_dec(state->ctx, state->key, state->keylength * 8);
}
if (!state->initialized) {
/* read the initialization vector from the first 16 bytes */
if (in_size < 16) return 0; /* get more data */
memcpy(state->iv, pr->ptr + 1, 16);
state->initialized = 1;
pr->ptr += 16;
}
/* decrypt available blocks */
while (pr->ptr + 16 <= limit) {
aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv,
pr->ptr + 1, temp);
pr->ptr += 16;
if (last && pr->ptr == pr->limit) {
/* we're on the last block; unpad if necessary */
int pad;
if (state->use_padding) {
/* we are using RFC 1423-style padding, so the last byte of the
plaintext gives the number of bytes to discard */
pad = temp[15];
if (pad < 1 || pad > 16) {
/* Bug 692343 - don't error here, just warn. Take padding to be
* zero. This may give us a stream that's too long - preferable
* to the alternatives. */
gs_warn1("invalid aes padding byte (0x%02x)",
(unsigned char)pad);
pad = 0;
}
} else {
/* not using padding */
pad = 0;
}
memcpy(pw->ptr + 1, temp, 16 - pad);
pw->ptr += 16 - pad;
return EOFC;
}
memcpy(pw->ptr + 1, temp, 16);
pw->ptr += 16;
}
/* if we got to the end of the file without triggering the padding
check, the input must not have been a multiple of 16 bytes long.
complain. */
if (status == EOFC) {
gs_throw(gs_error_rangecheck, "aes stream isn't a multiple of 16 bytes");
return 0;
}
return status;
}
Commit Message:
CWE ID: CWE-119 | s_aes_process(stream_state * ss, stream_cursor_read * pr,
stream_cursor_write * pw, bool last)
{
stream_aes_state *const state = (stream_aes_state *) ss;
const unsigned char *limit;
const long in_size = pr->limit - pr->ptr;
const long out_size = pw->limit - pw->ptr;
unsigned char temp[16];
int status = 0;
/* figure out if we're going to run out of space */
if (in_size > out_size) {
limit = pr->ptr + out_size;
status = 1; /* need more output space */
} else {
limit = pr->limit;
status = last ? EOFC : 0; /* need more input */
}
/* set up state and context */
if (state->ctx == NULL) {
/* allocate the aes context. this is a public struct but it
contains internal pointers, so we need to store it separately
in immovable memory like any opaque structure. */
state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory,
sizeof(aes_context), "aes context structure");
if (state->ctx == NULL) {
gs_throw(gs_error_VMerror, "could not allocate aes context");
return ERRC;
}
memset(state->ctx, 0x00, sizeof(aes_context));
if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) {
gs_throw1(gs_error_rangecheck, "invalid aes key length (%d bytes)",
state->keylength);
}
aes_setkey_dec(state->ctx, state->key, state->keylength * 8);
}
if (!state->initialized) {
/* read the initialization vector from the first 16 bytes */
if (in_size < 16) return 0; /* get more data */
memcpy(state->iv, pr->ptr + 1, 16);
state->initialized = 1;
pr->ptr += 16;
}
/* decrypt available blocks */
while (pr->ptr + 16 <= limit) {
aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv,
pr->ptr + 1, temp);
pr->ptr += 16;
if (last && pr->ptr == pr->limit) {
/* we're on the last block; unpad if necessary */
int pad;
if (state->use_padding) {
/* we are using RFC 1423-style padding, so the last byte of the
plaintext gives the number of bytes to discard */
pad = temp[15];
if (pad < 1 || pad > 16) {
/* Bug 692343 - don't error here, just warn. Take padding to be
* zero. This may give us a stream that's too long - preferable
* to the alternatives. */
gs_warn1("invalid aes padding byte (0x%02x)",
(unsigned char)pad);
pad = 0;
}
} else {
/* not using padding */
pad = 0;
}
memcpy(pw->ptr + 1, temp, 16 - pad);
pw->ptr += 16 - pad;
return EOFC;
}
memcpy(pw->ptr + 1, temp, 16);
pw->ptr += 16;
}
/* if we got to the end of the file without triggering the padding
check, the input must not have been a multiple of 16 bytes long.
complain. */
if (status == EOFC) {
gs_throw(gs_error_rangecheck, "aes stream isn't a multiple of 16 bytes");
return 0;
}
return status;
}
| 164,703 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(mcrypt_ofb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190 | PHP_FUNCTION(mcrypt_ofb)
{
zval **mode;
char *cipher, *key, *data, *iv = NULL;
int cipher_len, key_len, data_len, iv_len = 0;
MCRYPT_GET_CRYPT_ARGS
convert_to_long_ex(mode);
php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC);
}
| 167,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = (uint64_t)mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > UINT32_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new (std::nothrow) uint32_t[mTimeToSampleCount * 2];
if (!mTimeToSample)
return ERROR_OUT_OF_RANGE;
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release
Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d
CWE ID: CWE-20 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (!mTimeToSample.empty() || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
if ((uint64_t)mTimeToSampleCount >
(uint64_t)UINT32_MAX / (2 * sizeof(uint32_t))) {
// Choose this bound because
// 1) 2 * sizeof(uint32_t) is the amount of memory needed for one
// time-to-sample entry in the time-to-sample table.
// 2) mTimeToSampleCount is the number of entries of the time-to-sample
// table.
// 3) We hope that the table size does not exceed UINT32_MAX.
ALOGE(" Error: Time-to-sample table size too large.");
return ERROR_OUT_OF_RANGE;
}
// Note: At this point, we know that mTimeToSampleCount * 2 will not
// overflow because of the above condition.
if (!mDataSource->getVector(data_offset + 8, &mTimeToSample,
mTimeToSampleCount * 2)) {
ALOGE(" Error: Incomplete data read for time-to-sample table.");
return ERROR_IO;
}
for (size_t i = 0; i < mTimeToSample.size(); ++i) {
mTimeToSample.editItemAt(i) = ntohl(mTimeToSample[i]);
}
return OK;
}
| 174,173 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
unsigned int flags, struct timespec *timeout)
{
int fput_needed, err, datagrams;
struct socket *sock;
struct mmsghdr __user *entry;
struct compat_mmsghdr __user *compat_entry;
struct msghdr msg_sys;
struct timespec end_time;
if (timeout &&
poll_select_set_timeout(&end_time, timeout->tv_sec,
timeout->tv_nsec))
return -EINVAL;
datagrams = 0;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
return err;
err = sock_error(sock->sk);
if (err)
goto out_put;
entry = mmsg;
compat_entry = (struct compat_mmsghdr __user *)mmsg;
while (datagrams < vlen) {
/*
* No need to ask LSM for more than the first datagram.
*/
if (MSG_CMSG_COMPAT & flags) {
err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = __put_user(err, &compat_entry->msg_len);
++compat_entry;
} else {
err = ___sys_recvmsg(sock,
(struct user_msghdr __user *)entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = put_user(err, &entry->msg_len);
++entry;
}
if (err)
break;
++datagrams;
/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
if (flags & MSG_WAITFORONE)
flags |= MSG_DONTWAIT;
if (timeout) {
ktime_get_ts(timeout);
*timeout = timespec_sub(end_time, *timeout);
if (timeout->tv_sec < 0) {
timeout->tv_sec = timeout->tv_nsec = 0;
break;
}
/* Timeout, return less than vlen datagrams */
if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
break;
}
/* Out of band data, return right away */
if (msg_sys.msg_flags & MSG_OOB)
break;
cond_resched();
}
out_put:
fput_light(sock->file, fput_needed);
if (err == 0)
return datagrams;
if (datagrams != 0) {
/*
* We may return less entries than requested (vlen) if the
* sock is non block and there aren't enough datagrams...
*/
if (err != -EAGAIN) {
/*
* ... or if recvmsg returns an error after we
* received some datagrams, where we record the
* error to return on the next call or if the
* app asks about it using getsockopt(SO_ERROR).
*/
sock->sk->sk_err = -err;
}
return datagrams;
}
return err;
}
Commit Message: net: Fix use after free in the recvmmsg exit path
The syzkaller fuzzer hit the following use-after-free:
Call Trace:
[<ffffffff8175ea0e>] __asan_report_load8_noabort+0x3e/0x40 mm/kasan/report.c:295
[<ffffffff851cc31a>] __sys_recvmmsg+0x6fa/0x7f0 net/socket.c:2261
[< inline >] SYSC_recvmmsg net/socket.c:2281
[<ffffffff851cc57f>] SyS_recvmmsg+0x16f/0x180 net/socket.c:2270
[<ffffffff86332bb6>] entry_SYSCALL_64_fastpath+0x16/0x7a
arch/x86/entry/entry_64.S:185
And, as Dmitry rightly assessed, that is because we can drop the
reference and then touch it when the underlying recvmsg calls return
some packets and then hit an error, which will make recvmmsg to set
sock->sk->sk_err, oops, fix it.
Reported-and-Tested-by: Dmitry Vyukov <[email protected]>
Cc: Alexander Potapenko <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: Kostya Serebryany <[email protected]>
Cc: Sasha Levin <[email protected]>
Fixes: a2e2725541fa ("net: Introduce recvmmsg socket syscall")
http://lkml.kernel.org/r/[email protected]
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-19 | int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
unsigned int flags, struct timespec *timeout)
{
int fput_needed, err, datagrams;
struct socket *sock;
struct mmsghdr __user *entry;
struct compat_mmsghdr __user *compat_entry;
struct msghdr msg_sys;
struct timespec end_time;
if (timeout &&
poll_select_set_timeout(&end_time, timeout->tv_sec,
timeout->tv_nsec))
return -EINVAL;
datagrams = 0;
sock = sockfd_lookup_light(fd, &err, &fput_needed);
if (!sock)
return err;
err = sock_error(sock->sk);
if (err)
goto out_put;
entry = mmsg;
compat_entry = (struct compat_mmsghdr __user *)mmsg;
while (datagrams < vlen) {
/*
* No need to ask LSM for more than the first datagram.
*/
if (MSG_CMSG_COMPAT & flags) {
err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = __put_user(err, &compat_entry->msg_len);
++compat_entry;
} else {
err = ___sys_recvmsg(sock,
(struct user_msghdr __user *)entry,
&msg_sys, flags & ~MSG_WAITFORONE,
datagrams);
if (err < 0)
break;
err = put_user(err, &entry->msg_len);
++entry;
}
if (err)
break;
++datagrams;
/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
if (flags & MSG_WAITFORONE)
flags |= MSG_DONTWAIT;
if (timeout) {
ktime_get_ts(timeout);
*timeout = timespec_sub(end_time, *timeout);
if (timeout->tv_sec < 0) {
timeout->tv_sec = timeout->tv_nsec = 0;
break;
}
/* Timeout, return less than vlen datagrams */
if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
break;
}
/* Out of band data, return right away */
if (msg_sys.msg_flags & MSG_OOB)
break;
cond_resched();
}
if (err == 0)
goto out_put;
if (datagrams == 0) {
datagrams = err;
goto out_put;
}
/*
* We may return less entries than requested (vlen) if the
* sock is non block and there aren't enough datagrams...
*/
if (err != -EAGAIN) {
/*
* ... or if recvmsg returns an error after we
* received some datagrams, where we record the
* error to return on the next call or if the
* app asks about it using getsockopt(SO_ERROR).
*/
sock->sk->sk_err = -err;
}
out_put:
fput_light(sock->file, fput_needed);
return datagrams;
}
| 166,961 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: Fix several ineffective integer overflow checks
Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added
several integer overflow checks. Unfortunately, those checks fail to take into
account integer promotion rules and are thus themselves subject to an integer
overflow. Cast the sizeof() operator to a uint64_t to force promotion while
multiplying.
Bug: 20139950
(cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32)
Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b
CWE ID: CWE-189 | status_t SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * (uint64_t)sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
| 173,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* There is a serious error in the 2 and 4 bit grayscale transform because
* the gamma table value (8 bits) is simply shifted, not rounded, so the
* error in 4 bit grayscale gamma is up to the value below. This is a hack
* to allow pngvalid to succeed:
*
* TODO: fix this in libpng
*/
if (out_depth == 2)
return .73182-.5;
if (out_depth == 4)
return .90644-.5;
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxout16;
/* This is the case where the value was calculated at 8-bit precision then
* scaled to 16 bits.
*/
else if (out_depth == 16)
return pm->maxout8 * 257;
else
return pm->maxout8;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
static double outerr(const png_modifier *pm, int in_depth, int out_depth)
{
/* There is a serious error in the 2 and 4 bit grayscale transform because
* the gamma table value (8 bits) is simply shifted, not rounded, so the
* error in 4 bit grayscale gamma is up to the value below. This is a hack
* to allow pngvalid to succeed:
*
* TODO: fix this in libpng
*/
if (out_depth == 2)
return .73182-.5;
if (out_depth == 4)
return .90644-.5;
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxout16;
/* This is the case where the value was calculated at 8-bit precision then
* scaled to 16 bits.
*/
else if (out_depth == 16)
return pm->maxout8 * 257;
else
return pm->maxout8;
}
| 173,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int,
gboolean *cap_dir, char *cap_dst, int *err, gchar **err_info)
{
int sec;
int dsec, pkt_len;
char direction[2];
char cap_src[13];
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/",
&sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: Can't parse packet-header");
return -1;
}
*cap_dir = (direction[0] == 'o' ? NETSCREEN_EGRESS : NETSCREEN_INGRESS);
phdr->ts.secs = sec;
phdr->ts.nsecs = dsec * 100000000;
phdr->len = pkt_len;
return pkt_len;
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12396
Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f
Reviewed-on: https://code.wireshark.org/review/15176
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int,
static gboolean
parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
char *line, int *err, gchar **err_info)
{
int sec;
int dsec;
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
char direction[2];
guint pkt_len;
char cap_src[13];
char cap_dst[13];
guint8 *pd;
gchar *p;
int n, i = 0;
guint offset = 0;
gchar dststr[13];
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9u:%12s->%12s/",
&sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: Can't parse packet-header");
return -1;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
/*
* If direction[0] is 'o', the direction is NETSCREEN_EGRESS,
* otherwise it's NETSCREEN_INGRESS.
*/
phdr->ts.secs = sec;
phdr->ts.nsecs = dsec * 100000000;
phdr->len = pkt_len;
| 167,149 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
Commit Message:
CWE ID: CWE-200 | int test_mod_exp(BIO *bp, BN_CTX *ctx)
{
BIGNUM *a, *b, *c, *d, *e;
int i;
a = BN_new();
b = BN_new();
c = BN_new();
d = BN_new();
e = BN_new();
BN_one(a);
BN_one(b);
BN_zero(c);
if (BN_mod_exp(d, a, b, c, ctx)) {
fprintf(stderr, "BN_mod_exp with zero modulus succeeded!\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp(d, a, b, c, ctx))
return (0);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
/* Regression test for carry propagation bug in sqr8x_reduction */
BN_hex2bn(&a, "050505050505");
BN_hex2bn(&b, "02");
BN_hex2bn(&c,
"4141414141414141414141274141414141414141414141414141414141414141"
"4141414141414141414141414141414141414141414141414141414141414141"
"4141414141414141414141800000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000001");
BN_mod_exp(d, a, b, c, ctx);
BN_mul(e, a, a, ctx);
if (BN_cmp(d, e)) {
fprintf(stderr, "BN_mod_exp and BN_mul produce different results!\n");
return 0;
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_zero(c);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with zero modulus "
"succeeded\n");
return 0;
}
BN_set_word(c, 16);
if (BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL)) {
fprintf(stderr, "BN_mod_exp_mont_consttime with even modulus "
"succeeded\n");
return 0;
}
BN_bntest_rand(c, 30, 0, 1); /* must be odd for montgomery */
for (i = 0; i < num2; i++) {
BN_bntest_rand(a, 20 + i * 5, 0, 0);
BN_bntest_rand(b, 2 + i, 0, 0);
if (!BN_mod_exp_mont_consttime(d, a, b, c, ctx, NULL))
return (00);
if (bp != NULL) {
if (!results) {
BN_print(bp, a);
BIO_puts(bp, " ^ ");
BN_print(bp, b);
BIO_puts(bp, " % ");
BN_print(bp, c);
BIO_puts(bp, " - ");
}
BN_print(bp, d);
BIO_puts(bp, "\n");
}
BN_exp(e, a, b, ctx);
BN_sub(e, e, d);
BN_div(a, b, e, c, ctx);
if (!BN_is_zero(b)) {
fprintf(stderr, "Modulo exponentiation test failed!\n");
return 0;
}
}
BN_free(a);
BN_free(b);
BN_free(c);
BN_free(d);
BN_free(e);
return (1);
}
| 164,721 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 enable(void) {
LOG_INFO("%s", __func__);
if (!interface_ready())
return BT_STATUS_NOT_READY;
stack_manager_get_interface()->start_up_stack_async();
return BT_STATUS_SUCCESS;
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20 | static int enable(void) {
static int enable(bool start_restricted) {
LOG_INFO(LOG_TAG, "%s: start restricted = %d", __func__, start_restricted);
restricted_mode = start_restricted;
if (!interface_ready())
return BT_STATUS_NOT_READY;
stack_manager_get_interface()->start_up_stack_async();
return BT_STATUS_SUCCESS;
}
| 173,551 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chapters::Edition::~Edition()
{
}
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 | Chapters::Edition::~Edition()
Chapters::Atom::~Atom() {}
unsigned long long Chapters::Atom::GetUID() const { return m_uid; }
const char* Chapters::Atom::GetStringUID() const { return m_string_uid; }
long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; }
long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; }
long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const {
return GetTime(pChapters, m_start_timecode);
}
| 174,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: sec_decrypt(uint8 * data, int length)
{
if (g_sec_decrypt_use_count == 4096)
{
sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);
rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len);
g_sec_decrypt_use_count = 0;
}
rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length);
g_sec_decrypt_use_count++;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | sec_decrypt(uint8 * data, int length)
{
if (length <= 0)
return;
if (g_sec_decrypt_use_count == 4096)
{
sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key);
rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len);
g_sec_decrypt_use_count = 0;
}
rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length);
g_sec_decrypt_use_count++;
}
| 169,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: void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del(&pin->m_list);
hlist_del(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
}
Commit Message: fs_pin: Allow for the possibility that m_list or s_list go unused.
This is needed to support lazily umounting locked mounts. Because the
entire unmounted subtree needs to stay together until there are no
users with references to any part of the subtree.
To support this guarantee that the fs_pin m_list and s_list nodes
are initialized by initializing them in init_fs_pin allowing
for the possibility that pin_insert_group does not touch them.
Further use hlist_del_init in pin_remove so that there is
a hlist_unhashed test before the list we attempt to update
the previous list item.
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: | void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del_init(&pin->m_list);
hlist_del_init(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
}
| 167,562 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::RequestPinCode(
const dbus::ObjectPath& device_path,
const PinCodeCallback& callback) {
DCHECK(agent_.get());
DCHECK(device_path == object_path_);
VLOG(1) << object_path_.value() << ": RequestPinCode";
UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod",
UMA_PAIRING_METHOD_REQUEST_PINCODE,
UMA_PAIRING_METHOD_COUNT);
DCHECK(pairing_delegate_);
DCHECK(pincode_callback_.is_null());
pincode_callback_ = callback;
pairing_delegate_->RequestPinCode(this);
pairing_delegate_used_ = true;
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::RequestPinCode(
| 171,237 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DownloadItemImpl::OnIntermediatePathDetermined(
DownloadFileManager* file_manager,
const FilePath& intermediate_path,
bool ok_to_overwrite) {
DownloadFileManager::RenameCompletionCallback callback =
base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
weak_ptr_factory_.GetWeakPtr());
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&DownloadFileManager::RenameInProgressDownloadFile,
file_manager, GetGlobalId(), intermediate_path,
ok_to_overwrite, callback));
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void DownloadItemImpl::OnIntermediatePathDetermined(
DownloadFileManager* file_manager,
const FilePath& intermediate_path,
bool ok_to_overwrite) {
DownloadFileManager::RenameCompletionCallback callback =
base::Bind(&DownloadItemImpl::OnDownloadRenamedToIntermediateName,
weak_ptr_factory_.GetWeakPtr());
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
base::Bind(&DownloadFileManager::RenameDownloadFile,
file_manager, GetGlobalId(), intermediate_path,
ok_to_overwrite, callback));
}
| 170,884 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HasPermissionsForFile(const FilePath& file, int permissions) {
FilePath current_path = file.StripTrailingSeparators();
FilePath last_path;
while (current_path != last_path) {
if (file_permissions_.find(current_path) != file_permissions_.end())
return (file_permissions_[current_path] & permissions) == permissions;
last_path = current_path;
current_path = current_path.DirName();
}
return false;
}
Commit Message: Apply missing kParentDirectory check
BUG=161564
Review URL: https://chromiumcodereview.appspot.com/11414046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@168692 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool HasPermissionsForFile(const FilePath& file, int permissions) {
FilePath current_path = file.StripTrailingSeparators();
FilePath last_path;
int skip = 0;
while (current_path != last_path) {
FilePath base_name = current_path.BaseName();
if (base_name.value() == FilePath::kParentDirectory) {
++skip;
} else if (skip > 0) {
if (base_name.value() != FilePath::kCurrentDirectory)
--skip;
} else {
if (file_permissions_.find(current_path) != file_permissions_.end())
return (file_permissions_[current_path] & permissions) == permissions;
}
last_path = current_path;
current_path = current_path.DirName();
}
return false;
}
| 170,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
ScriptContext* context)
: ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
RouteFunction(
"GetExtensionAPIDefinitionsForTest",
base::Bind(&ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | ApiDefinitionsNatives::ApiDefinitionsNatives(Dispatcher* dispatcher,
ScriptContext* context)
: ObjectBackedNativeHandler(context), dispatcher_(dispatcher) {
RouteFunction(
"GetExtensionAPIDefinitionsForTest", "test",
base::Bind(&ApiDefinitionsNatives::GetExtensionAPIDefinitionsForTest,
base::Unretained(this)));
}
| 172,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BluetoothDeviceChromeOS::OnRegisterAgent(
const base::Closure& callback,
const ConnectErrorCallback& error_callback) {
VLOG(1) << object_path_.value() << ": Agent registered, now pairing";
DBusThreadManager::Get()->GetBluetoothDeviceClient()->
Pair(object_path_,
base::Bind(&BluetoothDeviceChromeOS::OnPair,
weak_ptr_factory_.GetWeakPtr(),
callback, error_callback),
base::Bind(&BluetoothDeviceChromeOS::OnPairError,
weak_ptr_factory_.GetWeakPtr(),
error_callback));
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void BluetoothDeviceChromeOS::OnRegisterAgent(
| 171,229 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GDataCache::CreateCacheDirectories(
const std::vector<FilePath>& paths_to_create) {
bool success = true;
for (size_t i = 0; i < paths_to_create.size(); ++i) {
if (file_util::DirectoryExists(paths_to_create[i]))
continue;
if (!file_util::CreateDirectory(paths_to_create[i])) {
success = false;
PLOG(ERROR) << "Error creating directory " << paths_to_create[i].value();
} else {
DVLOG(1) << "Created directory " << paths_to_create[i].value();
}
}
return success;
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | bool GDataCache::CreateCacheDirectories(
| 170,861 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb,
struct mcryptd_queue *queue)
{
struct hashd_instance_ctx *ctx;
struct ahash_instance *inst;
struct hash_alg_common *halg;
struct crypto_alg *alg;
u32 type = 0;
u32 mask = 0;
int err;
mcryptd_check_internal(tb, &type, &mask);
halg = ahash_attr_alg(tb[1], type, mask);
if (IS_ERR(halg))
return PTR_ERR(halg);
alg = &halg->base;
pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name);
inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(),
sizeof(*ctx));
err = PTR_ERR(inst);
if (IS_ERR(inst))
goto out_put_alg;
ctx = ahash_instance_ctx(inst);
ctx->queue = queue;
err = crypto_init_ahash_spawn(&ctx->spawn, halg,
ahash_crypto_instance(inst));
if (err)
goto out_free_inst;
type = CRYPTO_ALG_ASYNC;
if (alg->cra_flags & CRYPTO_ALG_INTERNAL)
type |= CRYPTO_ALG_INTERNAL;
inst->alg.halg.base.cra_flags = type;
inst->alg.halg.digestsize = halg->digestsize;
inst->alg.halg.statesize = halg->statesize;
inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx);
inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm;
inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm;
inst->alg.init = mcryptd_hash_init_enqueue;
inst->alg.update = mcryptd_hash_update_enqueue;
inst->alg.final = mcryptd_hash_final_enqueue;
inst->alg.finup = mcryptd_hash_finup_enqueue;
inst->alg.export = mcryptd_hash_export;
inst->alg.import = mcryptd_hash_import;
inst->alg.setkey = mcryptd_hash_setkey;
inst->alg.digest = mcryptd_hash_digest_enqueue;
err = ahash_register_instance(tmpl, inst);
if (err) {
crypto_drop_ahash(&ctx->spawn);
out_free_inst:
kfree(inst);
}
out_put_alg:
crypto_mod_put(alg);
return err;
}
Commit Message: crypto: mcryptd - Check mcryptd algorithm compatibility
Algorithms not compatible with mcryptd could be spawned by mcryptd
with a direct crypto_alloc_tfm invocation using a "mcryptd(alg)" name
construct. This causes mcryptd to crash the kernel if an arbitrary
"alg" is incompatible and not intended to be used with mcryptd. It is
an issue if AF_ALG tries to spawn mcryptd(alg) to expose it externally.
But such algorithms must be used internally and not be exposed.
We added a check to enforce that only internal algorithms are allowed
with mcryptd at the time mcryptd is spawning an algorithm.
Link: http://marc.info/?l=linux-crypto-vger&m=148063683310477&w=2
Cc: [email protected]
Reported-by: Mikulas Patocka <[email protected]>
Signed-off-by: Tim Chen <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static int mcryptd_create_hash(struct crypto_template *tmpl, struct rtattr **tb,
struct mcryptd_queue *queue)
{
struct hashd_instance_ctx *ctx;
struct ahash_instance *inst;
struct hash_alg_common *halg;
struct crypto_alg *alg;
u32 type = 0;
u32 mask = 0;
int err;
if (!mcryptd_check_internal(tb, &type, &mask))
return -EINVAL;
halg = ahash_attr_alg(tb[1], type, mask);
if (IS_ERR(halg))
return PTR_ERR(halg);
alg = &halg->base;
pr_debug("crypto: mcryptd hash alg: %s\n", alg->cra_name);
inst = mcryptd_alloc_instance(alg, ahash_instance_headroom(),
sizeof(*ctx));
err = PTR_ERR(inst);
if (IS_ERR(inst))
goto out_put_alg;
ctx = ahash_instance_ctx(inst);
ctx->queue = queue;
err = crypto_init_ahash_spawn(&ctx->spawn, halg,
ahash_crypto_instance(inst));
if (err)
goto out_free_inst;
type = CRYPTO_ALG_ASYNC;
if (alg->cra_flags & CRYPTO_ALG_INTERNAL)
type |= CRYPTO_ALG_INTERNAL;
inst->alg.halg.base.cra_flags = type;
inst->alg.halg.digestsize = halg->digestsize;
inst->alg.halg.statesize = halg->statesize;
inst->alg.halg.base.cra_ctxsize = sizeof(struct mcryptd_hash_ctx);
inst->alg.halg.base.cra_init = mcryptd_hash_init_tfm;
inst->alg.halg.base.cra_exit = mcryptd_hash_exit_tfm;
inst->alg.init = mcryptd_hash_init_enqueue;
inst->alg.update = mcryptd_hash_update_enqueue;
inst->alg.final = mcryptd_hash_final_enqueue;
inst->alg.finup = mcryptd_hash_finup_enqueue;
inst->alg.export = mcryptd_hash_export;
inst->alg.import = mcryptd_hash_import;
inst->alg.setkey = mcryptd_hash_setkey;
inst->alg.digest = mcryptd_hash_digest_enqueue;
err = ahash_register_instance(tmpl, inst);
if (err) {
crypto_drop_ahash(&ctx->spawn);
out_free_inst:
kfree(inst);
}
out_put_alg:
crypto_mod_put(alg);
return err;
}
| 168,521 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "replace",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrReplaceFunction)) {
return 0;
}
return -1;
}
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 | exsltStrXpathCtxtRegister (xmlXPathContextPtr ctxt, const xmlChar *prefix)
{
if (ctxt
&& prefix
&& !xmlXPathRegisterNs(ctxt,
prefix,
(const xmlChar *) EXSLT_STRINGS_NAMESPACE)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "encode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrEncodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "decode-uri",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrDecodeUriFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "padding",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrPaddingFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "align",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrAlignFunction)
&& !xmlXPathRegisterFuncNS(ctxt,
(const xmlChar *) "concat",
(const xmlChar *) EXSLT_STRINGS_NAMESPACE,
exsltStrConcatFunction)) {
return 0;
}
return -1;
}
| 173,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_compat_entry_size_and_hooks(struct compat_ipt_entry *e,
struct xt_table_info *newinfo,
unsigned int *size,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
const char *name)
{
struct xt_entry_match *ematch;
struct xt_entry_target *t;
struct xt_target *target;
unsigned int entry_offset;
unsigned int j;
int ret, off, h;
duprintf("check_compat_entry_size_and_hooks %p\n", e);
if ((unsigned long)e % __alignof__(struct compat_ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct compat_ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p, limit = %p\n", e, limit);
return -EINVAL;
}
if (e->next_offset < sizeof(struct compat_ipt_entry) +
sizeof(struct compat_xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
/* For purposes of check_entry casting the compat entry is fine */
ret = check_entry((struct ipt_entry *)e);
if (ret)
return ret;
off = sizeof(struct ipt_entry) - sizeof(struct compat_ipt_entry);
entry_offset = (void *)e - (void *)base;
j = 0;
xt_ematch_foreach(ematch, e) {
ret = compat_find_calc_match(ematch, name, &e->ip, &off);
if (ret != 0)
goto release_matches;
++j;
}
t = compat_ipt_get_target(e);
target = xt_request_find_target(NFPROTO_IPV4, t->u.user.name,
t->u.user.revision);
if (IS_ERR(target)) {
duprintf("check_compat_entry_size_and_hooks: `%s' not found\n",
t->u.user.name);
ret = PTR_ERR(target);
goto release_matches;
}
t->u.kernel.target = target;
off += xt_compat_target_offset(target);
*size += off;
ret = xt_compat_add_offset(AF_INET, entry_offset, off);
if (ret)
goto out;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h])
newinfo->underflow[h] = underflows[h];
}
/* Clear counters and comefrom */
memset(&e->counters, 0, sizeof(e->counters));
e->comefrom = 0;
return 0;
out:
module_put(t->u.kernel.target->me);
release_matches:
xt_ematch_foreach(ematch, e) {
if (j-- == 0)
break;
module_put(ematch->u.kernel.match->me);
}
return ret;
}
| 167,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 TabletModeWindowManager::ForgetWindow(aura::Window* window,
bool destroyed) {
added_windows_.erase(window);
window->RemoveObserver(this);
WindowToState::iterator it = window_state_map_.find(window);
if (it == window_state_map_.end())
return;
if (destroyed) {
window_state_map_.erase(it);
} else {
it->second->LeaveTabletMode(wm::GetWindowState(it->first));
DCHECK(!IsTrackingWindow(window));
}
}
Commit Message: Fix the crash after clamshell -> tablet transition in overview mode.
This CL just reverted some changes that were made in
https://chromium-review.googlesource.com/c/chromium/src/+/1658955. In
that CL, we changed the clamshell <-> tablet transition when clamshell
split view mode is enabled, however, we should keep the old behavior
unchanged if the feature is not enabled, i.e., overview should be ended
if it's active before the transition. Otherwise, it will cause a nullptr
dereference crash since |split_view_drag_indicators_| is not created in
clamshell overview and will be used in tablet overview.
Bug: 982507
Change-Id: I238fe9472648a446cff4ab992150658c228714dd
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1705474
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Mitsuru Oshima (Slow - on/off site) <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679306}
CWE ID: CWE-362 | void TabletModeWindowManager::ForgetWindow(aura::Window* window,
bool destroyed,
bool was_in_overview) {
added_windows_.erase(window);
window->RemoveObserver(this);
WindowToState::iterator it = window_state_map_.find(window);
if (it == window_state_map_.end())
return;
if (destroyed) {
window_state_map_.erase(it);
} else {
it->second->LeaveTabletMode(wm::GetWindowState(it->first), was_in_overview);
DCHECK(!IsTrackingWindow(window));
}
}
| 172,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: long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim;j++)
a[i++]+=v[j];
}
}
return 0;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200 | long vorbis_book_decodev_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim && i < n;j++)
a[i++]+=v[j];
}
}
return 0;
}
| 173,986 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415 | static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
| 167,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() {
return brightness_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | BrightnessLibrary* CrosLibrary::GetBrightnessLibrary() {
| 170,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
| 169,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 user_match(const struct key *key, const struct key_match_data *match_data)
{
return strcmp(key->description, match_data->raw_data) == 0;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476 | int user_match(const struct key *key, const struct key_match_data *match_data)
| 168,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction(
const ExtensionHostMsg_Request_Params& params,
const Extension* extension,
int requesting_process_id,
const extensions::ProcessMap& process_map,
extensions::ExtensionAPI* api,
void* profile,
IPC::Sender* ipc_sender,
RenderViewHost* render_view_host,
int routing_id) {
if (!extension) {
LOG(ERROR) << "Specified extension does not exist.";
SendAccessDenied(ipc_sender, routing_id, params.request_id);
return NULL;
}
if (api->IsPrivileged(params.name) &&
!process_map.Contains(extension->id(), requesting_process_id)) {
LOG(ERROR) << "Extension API called from incorrect process "
<< requesting_process_id
<< " from URL " << params.source_url.spec();
SendAccessDenied(ipc_sender, routing_id, params.request_id);
return NULL;
}
ExtensionFunction* function =
ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name);
function->SetArgs(¶ms.arguments);
function->set_source_url(params.source_url);
function->set_request_id(params.request_id);
function->set_has_callback(params.has_callback);
function->set_user_gesture(params.user_gesture);
function->set_extension(extension);
function->set_profile_id(profile);
UIThreadExtensionFunction* function_ui =
function->AsUIThreadExtensionFunction();
if (function_ui) {
function_ui->SetRenderViewHost(render_view_host);
}
return function;
}
Commit Message: Tighten restrictions on hosted apps calling extension APIs
Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this).
BUG=172369
Review URL: https://chromiumcodereview.appspot.com/12095095
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | ExtensionFunction* ExtensionFunctionDispatcher::CreateExtensionFunction(
const ExtensionHostMsg_Request_Params& params,
const Extension* extension,
int requesting_process_id,
const extensions::ProcessMap& process_map,
extensions::ExtensionAPI* api,
void* profile,
IPC::Sender* ipc_sender,
RenderViewHost* render_view_host,
int routing_id) {
if (!extension) {
LOG(ERROR) << "Specified extension does not exist.";
SendAccessDenied(ipc_sender, routing_id, params.request_id);
return NULL;
}
// Most hosted apps can't call APIs.
bool allowed = true;
if (extension->is_hosted_app())
allowed = AllowHostedAppAPICall(*extension, params.source_url,
params.name);
// Privileged APIs can only be called from the process the extension
// is running in.
if (allowed && api->IsPrivileged(params.name))
allowed = process_map.Contains(extension->id(), requesting_process_id);
if (!allowed) {
LOG(ERROR) << "Extension API call disallowed - name:" << params.name
<< " pid:" << requesting_process_id
<< " from URL " << params.source_url.spec();
SendAccessDenied(ipc_sender, routing_id, params.request_id);
return NULL;
}
ExtensionFunction* function =
ExtensionFunctionRegistry::GetInstance()->NewFunction(params.name);
function->SetArgs(¶ms.arguments);
function->set_source_url(params.source_url);
function->set_request_id(params.request_id);
function->set_has_callback(params.has_callback);
function->set_user_gesture(params.user_gesture);
function->set_extension(extension);
function->set_profile_id(profile);
UIThreadExtensionFunction* function_ui =
function->AsUIThreadExtensionFunction();
if (function_ui) {
function_ui->SetRenderViewHost(render_view_host);
}
return function;
}
| 171,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: const Cluster* Segment::GetFirst() const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cluster* Segment::GetFirst() const
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
return pCluster;
}
| 174,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InRegionScrollableArea::InRegionScrollableArea(WebPagePrivate* webPage, RenderLayer* layer)
: m_webPage(webPage)
, m_layer(layer)
{
ASSERT(webPage);
ASSERT(layer);
m_isNull = false;
RenderObject* layerRenderer = layer->renderer();
ASSERT(layerRenderer);
if (layerRenderer->isRenderView()) { // #document case
FrameView* view = toRenderView(layerRenderer)->frameView();
ASSERT(view);
Frame* frame = view->frame();
ASSERT_UNUSED(frame, frame);
m_scrollPosition = m_webPage->mapToTransformed(view->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(view->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(view->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_webPage->mapToTransformed(m_webPage->getRecursiveVisibleWindowRect(view));
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = view->contentsWidth() > view->visibleWidth();
m_scrollsVertically = view->contentsHeight() > view->visibleHeight();
m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition(
view->visibleContentRect().size(),
0.0 /*overscrollLimit*/));
m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition(
view->visibleContentRect().size(),
view->contentsSize(),
0.0 /*overscrollLimit*/));
} else { // RenderBox-based elements case (scrollable boxes (div's, p's, textarea's, etc)).
RenderBox* box = m_layer->renderBox();
ASSERT(box);
ASSERT(box->canBeScrolledAndHasScrollableArea());
ScrollableArea* scrollableArea = static_cast<ScrollableArea*>(m_layer);
m_scrollPosition = m_webPage->mapToTransformed(scrollableArea->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(scrollableArea->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(scrollableArea->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_layer->renderer()->absoluteClippedOverflowRect();
m_visibleWindowRect = m_layer->renderer()->frame()->view()->contentsToWindow(m_visibleWindowRect);
IntRect visibleFrameWindowRect = m_webPage->getRecursiveVisibleWindowRect(m_layer->renderer()->frame()->view());
m_visibleWindowRect.intersect(visibleFrameWindowRect);
m_visibleWindowRect = m_webPage->mapToTransformed(m_visibleWindowRect);
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = box->scrollWidth() != box->clientWidth() && box->scrollsOverflowX();
m_scrollsVertically = box->scrollHeight() != box->clientHeight() && box->scrollsOverflowY();
m_minimumScrollPosition = m_webPage->mapToTransformed(calculateMinimumScrollPosition(
Platform::IntSize(box->clientWidth(), box->clientHeight()),
0.0 /*overscrollLimit*/));
m_maximumScrollPosition = m_webPage->mapToTransformed(calculateMaximumScrollPosition(
Platform::IntSize(box->clientWidth(), box->clientHeight()),
Platform::IntSize(box->scrollWidth(), box->scrollHeight()),
0.0 /*overscrollLimit*/));
}
}
Commit Message: Remove minimum and maximum scroll position as they are no
longer required due to changes in ScrollViewBase.
https://bugs.webkit.org/show_bug.cgi?id=87298
Patch by Genevieve Mak <[email protected]> on 2012-05-23
Reviewed by Antonio Gomes.
* WebKitSupport/InRegionScrollableArea.cpp:
(BlackBerry::WebKit::InRegionScrollableArea::InRegionScrollableArea):
* WebKitSupport/InRegionScrollableArea.h:
(InRegionScrollableArea):
git-svn-id: svn://svn.chromium.org/blink/trunk@118233 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | InRegionScrollableArea::InRegionScrollableArea(WebPagePrivate* webPage, RenderLayer* layer)
: m_webPage(webPage)
, m_layer(layer)
{
ASSERT(webPage);
ASSERT(layer);
m_isNull = false;
RenderObject* layerRenderer = layer->renderer();
ASSERT(layerRenderer);
if (layerRenderer->isRenderView()) { // #document case
FrameView* view = toRenderView(layerRenderer)->frameView();
ASSERT(view);
Frame* frame = view->frame();
ASSERT_UNUSED(frame, frame);
m_scrollPosition = m_webPage->mapToTransformed(view->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(view->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(view->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_webPage->mapToTransformed(m_webPage->getRecursiveVisibleWindowRect(view));
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = view->contentsWidth() > view->visibleWidth();
m_scrollsVertically = view->contentsHeight() > view->visibleHeight();
m_overscrollLimitFactor = 0.0; // FIXME eventually support overscroll
} else { // RenderBox-based elements case (scrollable boxes (div's, p's, textarea's, etc)).
RenderBox* box = m_layer->renderBox();
ASSERT(box);
ASSERT(box->canBeScrolledAndHasScrollableArea());
ScrollableArea* scrollableArea = static_cast<ScrollableArea*>(m_layer);
m_scrollPosition = m_webPage->mapToTransformed(scrollableArea->scrollPosition());
m_contentsSize = m_webPage->mapToTransformed(scrollableArea->contentsSize());
m_viewportSize = m_webPage->mapToTransformed(scrollableArea->visibleContentRect(false /*includeScrollbars*/)).size();
m_visibleWindowRect = m_layer->renderer()->absoluteClippedOverflowRect();
m_visibleWindowRect = m_layer->renderer()->frame()->view()->contentsToWindow(m_visibleWindowRect);
IntRect visibleFrameWindowRect = m_webPage->getRecursiveVisibleWindowRect(m_layer->renderer()->frame()->view());
m_visibleWindowRect.intersect(visibleFrameWindowRect);
m_visibleWindowRect = m_webPage->mapToTransformed(m_visibleWindowRect);
IntRect transformedWindowRect = IntRect(IntPoint::zero(), m_webPage->transformedViewportSize());
m_visibleWindowRect.intersect(transformedWindowRect);
m_scrollsHorizontally = box->scrollWidth() != box->clientWidth() && box->scrollsOverflowX();
m_scrollsVertically = box->scrollHeight() != box->clientHeight() && box->scrollsOverflowY();
m_overscrollLimitFactor = 0.0; // FIXME eventually support overscroll
}
}
| 170,431 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Verify_MakeGroupObsolete() {
EXPECT_TRUE(delegate()->obsoleted_success_);
EXPECT_EQ(group_.get(), delegate()->obsoleted_group_.get());
EXPECT_TRUE(group_->is_obsolete());
EXPECT_TRUE(storage()->usage_map_.empty());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_FALSE(database()->FindGroup(1, &group_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
std::vector<AppCacheDatabase::EntryRecord> entry_records;
database()->FindEntriesForCache(1, &entry_records);
EXPECT_TRUE(entry_records.empty());
std::vector<AppCacheDatabase::NamespaceRecord> intercept_records;
std::vector<AppCacheDatabase::NamespaceRecord> fallback_records;
database()->FindNamespacesForCache(1, &intercept_records,
&fallback_records);
EXPECT_TRUE(fallback_records.empty());
std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelist_records;
database()->FindOnlineWhiteListForCache(1, &whitelist_records);
EXPECT_TRUE(whitelist_records.empty());
EXPECT_TRUE(storage()->usage_map_.empty());
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(-kDefaultEntrySize, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void Verify_MakeGroupObsolete() {
EXPECT_TRUE(delegate()->obsoleted_success_);
EXPECT_EQ(group_.get(), delegate()->obsoleted_group_.get());
EXPECT_TRUE(group_->is_obsolete());
EXPECT_TRUE(storage()->usage_map_.empty());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_FALSE(database()->FindGroup(1, &group_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
std::vector<AppCacheDatabase::EntryRecord> entry_records;
database()->FindEntriesForCache(1, &entry_records);
EXPECT_TRUE(entry_records.empty());
std::vector<AppCacheDatabase::NamespaceRecord> intercept_records;
std::vector<AppCacheDatabase::NamespaceRecord> fallback_records;
database()->FindNamespacesForCache(1, &intercept_records,
&fallback_records);
EXPECT_TRUE(fallback_records.empty());
std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelist_records;
database()->FindOnlineWhiteListForCache(1, &whitelist_records);
EXPECT_TRUE(whitelist_records.empty());
EXPECT_TRUE(storage()->usage_map_.empty());
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(-(kDefaultEntrySize + kDefaultEntryPadding),
mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
| 172,992 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
ContentSecurityPolicy* policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
}
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732 | void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) {
//// the first parameter specifies a policy to use as the document csp meaning
//// the document will take ownership of the policy
//// the second parameter specifies a policy to inherit meaning the document
//// will attempt to copy over the policy
void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else if (frame_) {
Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
}
}
// Plugin documents inherit their parent/opener's 'plugin-types' directive
// regardless of URL.
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
GetContentSecurityPolicy()->BindToExecutionContext(this);
}
| 172,299 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 snd_usbmidi_create(struct snd_card *card,
struct usb_interface *iface,
struct list_head *midi_list,
const struct snd_usb_audio_quirk *quirk)
{
struct snd_usb_midi *umidi;
struct snd_usb_midi_endpoint_info endpoints[MIDI_MAX_ENDPOINTS];
int out_ports, in_ports;
int i, err;
umidi = kzalloc(sizeof(*umidi), GFP_KERNEL);
if (!umidi)
return -ENOMEM;
umidi->dev = interface_to_usbdev(iface);
umidi->card = card;
umidi->iface = iface;
umidi->quirk = quirk;
umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
spin_lock_init(&umidi->disc_lock);
init_rwsem(&umidi->disc_rwsem);
mutex_init(&umidi->mutex);
umidi->usb_id = USB_ID(le16_to_cpu(umidi->dev->descriptor.idVendor),
le16_to_cpu(umidi->dev->descriptor.idProduct));
setup_timer(&umidi->error_timer, snd_usbmidi_error_timer,
(unsigned long)umidi);
/* detect the endpoint(s) to use */
memset(endpoints, 0, sizeof(endpoints));
switch (quirk ? quirk->type : QUIRK_MIDI_STANDARD_INTERFACE) {
case QUIRK_MIDI_STANDARD_INTERFACE:
err = snd_usbmidi_get_ms_info(umidi, endpoints);
if (umidi->usb_id == USB_ID(0x0763, 0x0150)) /* M-Audio Uno */
umidi->usb_protocol_ops =
&snd_usbmidi_maudio_broken_running_status_ops;
break;
case QUIRK_MIDI_US122L:
umidi->usb_protocol_ops = &snd_usbmidi_122l_ops;
/* fall through */
case QUIRK_MIDI_FIXED_ENDPOINT:
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
break;
case QUIRK_MIDI_YAMAHA:
err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
break;
case QUIRK_MIDI_ROLAND:
err = snd_usbmidi_detect_roland(umidi, &endpoints[0]);
break;
case QUIRK_MIDI_MIDIMAN:
umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = 0;
break;
case QUIRK_MIDI_NOVATION:
umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_RAW_BYTES:
umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
/*
* Interface 1 contains isochronous endpoints, but with the same
* numbers as in interface 0. Since it is interface 1 that the
* USB core has most recently seen, these descriptors are now
* associated with the endpoint numbers. This will foul up our
* attempts to submit bulk/interrupt URBs to the endpoints in
* interface 0, so we have to make sure that the USB core looks
* again at interface 0 by calling usb_set_interface() on it.
*/
if (umidi->usb_id == USB_ID(0x07fd, 0x0001)) /* MOTU Fastlane */
usb_set_interface(umidi->dev, 0, 0);
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_EMAGIC:
umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
break;
case QUIRK_MIDI_CME:
umidi->usb_protocol_ops = &snd_usbmidi_cme_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_AKAI:
umidi->usb_protocol_ops = &snd_usbmidi_akai_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
/* endpoint 1 is input-only */
endpoints[1].out_cables = 0;
break;
case QUIRK_MIDI_FTDI:
umidi->usb_protocol_ops = &snd_usbmidi_ftdi_ops;
/* set baud rate to 31250 (48 MHz / 16 / 96) */
err = usb_control_msg(umidi->dev, usb_sndctrlpipe(umidi->dev, 0),
3, 0x40, 0x60, 0, NULL, 0, 1000);
if (err < 0)
break;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_CH345:
umidi->usb_protocol_ops = &snd_usbmidi_ch345_broken_sysex_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
default:
dev_err(&umidi->dev->dev, "invalid quirk type %d\n",
quirk->type);
err = -ENXIO;
break;
}
if (err < 0) {
kfree(umidi);
return err;
}
/* create rawmidi device */
out_ports = 0;
in_ports = 0;
for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
out_ports += hweight16(endpoints[i].out_cables);
in_ports += hweight16(endpoints[i].in_cables);
}
err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
if (err < 0) {
kfree(umidi);
return err;
}
/* create endpoint/port structures */
if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
else
err = snd_usbmidi_create_endpoints(umidi, endpoints);
if (err < 0) {
snd_usbmidi_free(umidi);
return err;
}
usb_autopm_get_interface_no_resume(umidi->iface);
list_add_tail(&umidi->list, midi_list);
return 0;
}
Commit Message: ALSA: usb-audio: avoid freeing umidi object twice
The 'umidi' object will be free'd on the error path by snd_usbmidi_free()
when tearing down the rawmidi interface. So we shouldn't try to free it
in snd_usbmidi_create() after having registered the rawmidi interface.
Found by KASAN.
Signed-off-by: Andrey Konovalov <[email protected]>
Acked-by: Clemens Ladisch <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | int snd_usbmidi_create(struct snd_card *card,
struct usb_interface *iface,
struct list_head *midi_list,
const struct snd_usb_audio_quirk *quirk)
{
struct snd_usb_midi *umidi;
struct snd_usb_midi_endpoint_info endpoints[MIDI_MAX_ENDPOINTS];
int out_ports, in_ports;
int i, err;
umidi = kzalloc(sizeof(*umidi), GFP_KERNEL);
if (!umidi)
return -ENOMEM;
umidi->dev = interface_to_usbdev(iface);
umidi->card = card;
umidi->iface = iface;
umidi->quirk = quirk;
umidi->usb_protocol_ops = &snd_usbmidi_standard_ops;
spin_lock_init(&umidi->disc_lock);
init_rwsem(&umidi->disc_rwsem);
mutex_init(&umidi->mutex);
umidi->usb_id = USB_ID(le16_to_cpu(umidi->dev->descriptor.idVendor),
le16_to_cpu(umidi->dev->descriptor.idProduct));
setup_timer(&umidi->error_timer, snd_usbmidi_error_timer,
(unsigned long)umidi);
/* detect the endpoint(s) to use */
memset(endpoints, 0, sizeof(endpoints));
switch (quirk ? quirk->type : QUIRK_MIDI_STANDARD_INTERFACE) {
case QUIRK_MIDI_STANDARD_INTERFACE:
err = snd_usbmidi_get_ms_info(umidi, endpoints);
if (umidi->usb_id == USB_ID(0x0763, 0x0150)) /* M-Audio Uno */
umidi->usb_protocol_ops =
&snd_usbmidi_maudio_broken_running_status_ops;
break;
case QUIRK_MIDI_US122L:
umidi->usb_protocol_ops = &snd_usbmidi_122l_ops;
/* fall through */
case QUIRK_MIDI_FIXED_ENDPOINT:
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
break;
case QUIRK_MIDI_YAMAHA:
err = snd_usbmidi_detect_yamaha(umidi, &endpoints[0]);
break;
case QUIRK_MIDI_ROLAND:
err = snd_usbmidi_detect_roland(umidi, &endpoints[0]);
break;
case QUIRK_MIDI_MIDIMAN:
umidi->usb_protocol_ops = &snd_usbmidi_midiman_ops;
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = 0;
break;
case QUIRK_MIDI_NOVATION:
umidi->usb_protocol_ops = &snd_usbmidi_novation_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_RAW_BYTES:
umidi->usb_protocol_ops = &snd_usbmidi_raw_ops;
/*
* Interface 1 contains isochronous endpoints, but with the same
* numbers as in interface 0. Since it is interface 1 that the
* USB core has most recently seen, these descriptors are now
* associated with the endpoint numbers. This will foul up our
* attempts to submit bulk/interrupt URBs to the endpoints in
* interface 0, so we have to make sure that the USB core looks
* again at interface 0 by calling usb_set_interface() on it.
*/
if (umidi->usb_id == USB_ID(0x07fd, 0x0001)) /* MOTU Fastlane */
usb_set_interface(umidi->dev, 0, 0);
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_EMAGIC:
umidi->usb_protocol_ops = &snd_usbmidi_emagic_ops;
memcpy(&endpoints[0], quirk->data,
sizeof(struct snd_usb_midi_endpoint_info));
err = snd_usbmidi_detect_endpoints(umidi, &endpoints[0], 1);
break;
case QUIRK_MIDI_CME:
umidi->usb_protocol_ops = &snd_usbmidi_cme_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_AKAI:
umidi->usb_protocol_ops = &snd_usbmidi_akai_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
/* endpoint 1 is input-only */
endpoints[1].out_cables = 0;
break;
case QUIRK_MIDI_FTDI:
umidi->usb_protocol_ops = &snd_usbmidi_ftdi_ops;
/* set baud rate to 31250 (48 MHz / 16 / 96) */
err = usb_control_msg(umidi->dev, usb_sndctrlpipe(umidi->dev, 0),
3, 0x40, 0x60, 0, NULL, 0, 1000);
if (err < 0)
break;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
case QUIRK_MIDI_CH345:
umidi->usb_protocol_ops = &snd_usbmidi_ch345_broken_sysex_ops;
err = snd_usbmidi_detect_per_port_endpoints(umidi, endpoints);
break;
default:
dev_err(&umidi->dev->dev, "invalid quirk type %d\n",
quirk->type);
err = -ENXIO;
break;
}
if (err < 0) {
kfree(umidi);
return err;
}
/* create rawmidi device */
out_ports = 0;
in_ports = 0;
for (i = 0; i < MIDI_MAX_ENDPOINTS; ++i) {
out_ports += hweight16(endpoints[i].out_cables);
in_ports += hweight16(endpoints[i].in_cables);
}
err = snd_usbmidi_create_rawmidi(umidi, out_ports, in_ports);
if (err < 0) {
kfree(umidi);
return err;
}
/* create endpoint/port structures */
if (quirk && quirk->type == QUIRK_MIDI_MIDIMAN)
err = snd_usbmidi_create_endpoints_midiman(umidi, &endpoints[0]);
else
err = snd_usbmidi_create_endpoints(umidi, endpoints);
if (err < 0) {
return err;
}
usb_autopm_get_interface_no_resume(umidi->iface);
list_add_tail(&umidi->list, midi_list);
return 0;
}
| 167,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: void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
const FilePath::StringType& filepath,
const std::string& output) {
VLOG(0) << "Writing renderer heap profile dump to: " << filepath;
file_util::WriteFile(FilePath(filepath), output.c_str(), output.size());
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile(
| 170,664 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p,
const struct http_conn *htc)
{
char *q, *r;
txt t = htc->rxbuf;
if (*p == '\r')
p++;
hp->nhd = HTTP_HDR_FIRST;
hp->conds = 0;
r = NULL; /* For FlexeLint */
for (; p < t.e; p = r) {
/* Find end of next header */
q = r = p;
while (r < t.e) {
if (!vct_iscrlf(*r)) {
r++;
continue;
}
q = r;
assert(r < t.e);
r += vct_skipcrlf(r);
if (r >= t.e)
break;
/* If line does not continue: got it. */
if (!vct_issp(*r))
break;
/* Clear line continuation LWS to spaces */
while (vct_islws(*q))
*q++ = ' ';
}
if (q - p > htc->maxhdr) {
VSC_C_main->losthdr++;
WSL(w, SLT_LostHeader, fd, "%.*s",
q - p > 20 ? 20 : q - p, p);
return (413);
}
/* Empty header = end of headers */
if (p == q)
break;
if ((p[0] == 'i' || p[0] == 'I') &&
(p[1] == 'f' || p[1] == 'F') &&
p[2] == '-')
hp->conds = 1;
while (q > p && vct_issp(q[-1]))
q--;
*q = '\0';
if (hp->nhd < hp->shd) {
hp->hdf[hp->nhd] = 0;
hp->hd[hp->nhd].b = p;
hp->hd[hp->nhd].e = q;
WSLH(w, fd, hp, hp->nhd);
hp->nhd++;
} else {
VSC_C_main->losthdr++;
WSL(w, SLT_LostHeader, fd, "%.*s",
q - p > 20 ? 20 : q - p, p);
return (413);
}
}
return (0);
}
Commit Message: Do not consider a CR by itself as a valid line terminator
Varnish (prior to version 4.0) was not following the standard with
regard to line separator.
Spotted and analyzed by: Régis Leroy [regilero] [email protected]
CWE ID: | http_dissect_hdrs(struct worker *w, struct http *hp, int fd, char *p,
const struct http_conn *htc)
{
char *q, *r;
txt t = htc->rxbuf;
if (*p == '\r')
p++;
hp->nhd = HTTP_HDR_FIRST;
hp->conds = 0;
r = NULL; /* For FlexeLint */
for (; p < t.e; p = r) {
/* Find end of next header */
q = r = p;
while (r < t.e) {
if (!vct_iscrlf(r)) {
r++;
continue;
}
q = r;
assert(r < t.e);
r += vct_skipcrlf(r);
if (r >= t.e)
break;
/* If line does not continue: got it. */
if (!vct_issp(*r))
break;
/* Clear line continuation LWS to spaces */
while (vct_islws(*q))
*q++ = ' ';
}
if (q - p > htc->maxhdr) {
VSC_C_main->losthdr++;
WSL(w, SLT_LostHeader, fd, "%.*s",
q - p > 20 ? 20 : q - p, p);
return (413);
}
/* Empty header = end of headers */
if (p == q)
break;
if ((p[0] == 'i' || p[0] == 'I') &&
(p[1] == 'f' || p[1] == 'F') &&
p[2] == '-')
hp->conds = 1;
while (q > p && vct_issp(q[-1]))
q--;
*q = '\0';
if (hp->nhd < hp->shd) {
hp->hdf[hp->nhd] = 0;
hp->hd[hp->nhd].b = p;
hp->hd[hp->nhd].e = q;
WSLH(w, fd, hp, hp->nhd);
hp->nhd++;
} else {
VSC_C_main->losthdr++;
WSL(w, SLT_LostHeader, fd, "%.*s",
q - p > 20 ? 20 : q - p, p);
return (413);
}
}
return (0);
}
| 169,997 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebViewTestClient::DidFocus() {
test_runner()->SetFocus(web_view_test_proxy_base_->web_view(), true);
}
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 WebViewTestClient::DidFocus() {
void WebViewTestClient::DidFocus(blink::WebLocalFrame* calling_frame) {
test_runner()->SetFocus(web_view_test_proxy_base_->web_view(), true);
}
| 172,721 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DebuggerDetachFunction::RunAsync() {
std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitClientHost())
return false;
client_host_->Close();
SendResponse(true);
return 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 | bool DebuggerDetachFunction::RunAsync() {
std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitClientHost())
return false;
client_host_->RespondDetachedToPendingRequests();
client_host_->Close();
SendResponse(true);
return true;
}
| 173,240 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WorkerFetchContext::DispatchWillSendRequest(
unsigned long identifier,
ResourceRequest& request,
const ResourceResponse& redirect_response,
const FetchInitiatorInfo& initiator_info) {
probe::willSendRequest(global_scope_, identifier, nullptr, request,
redirect_response, initiator_info);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | void WorkerFetchContext::DispatchWillSendRequest(
unsigned long identifier,
ResourceRequest& request,
const ResourceResponse& redirect_response,
Resource::Type resource_type,
const FetchInitiatorInfo& initiator_info) {
probe::willSendRequest(global_scope_, identifier, nullptr, request,
redirect_response, initiator_info, resource_type);
}
| 172,476 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ATSParser::PSISection::isCRCOkay() const {
if (!isComplete()) {
return false;
}
uint8_t* data = mBuffer->data();
if ((data[1] & 0x80) == 0) {
return true;
}
unsigned sectionLength = U16_AT(data + 1) & 0xfff;
ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
sectionLength -= mSkipBytes;
uint32_t crc = 0xffffffff;
for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
uint8_t b = data[i];
int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
crc = CRC_TABLE[index] ^ (crc << 8);
}
ALOGV("crc: %08x\n", crc);
return (crc == 0);
}
Commit Message: Check section size when verifying CRC
Bug: 28333006
Change-Id: Ief7a2da848face78f0edde21e2f2009316076679
CWE ID: CWE-119 | bool ATSParser::PSISection::isCRCOkay() const {
if (!isComplete()) {
return false;
}
uint8_t* data = mBuffer->data();
if ((data[1] & 0x80) == 0) {
return true;
}
unsigned sectionLength = U16_AT(data + 1) & 0xfff;
ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes);
if(sectionLength < mSkipBytes) {
ALOGE("b/28333006");
android_errorWriteLog(0x534e4554, "28333006");
return false;
}
sectionLength -= mSkipBytes;
uint32_t crc = 0xffffffff;
for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) {
uint8_t b = data[i];
int index = ((crc >> 24) ^ (b & 0xff)) & 0xff;
crc = CRC_TABLE[index] ^ (crc << 8);
}
ALOGV("crc: %08x\n", crc);
return (crc == 0);
}
| 173,769 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CameraSource::dataCallbackTimestamp(int64_t timestampUs,
int32_t msgType __unused, const sp<IMemory> &data) {
ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs);
Mutex::Autolock autoLock(mLock);
if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) {
ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs);
releaseOneRecordingFrame(data);
return;
}
if (skipCurrentFrame(timestampUs)) {
releaseOneRecordingFrame(data);
return;
}
if (mNumFramesReceived > 0) {
if (timestampUs <= mLastFrameTimestampUs) {
ALOGW("Dropping frame with backward timestamp %lld (last %lld)",
(long long)timestampUs, (long long)mLastFrameTimestampUs);
releaseOneRecordingFrame(data);
return;
}
if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) {
++mNumGlitches;
}
}
mLastFrameTimestampUs = timestampUs;
if (mNumFramesReceived == 0) {
mFirstFrameTimeUs = timestampUs;
if (mStartTimeUs > 0) {
if (timestampUs < mStartTimeUs) {
releaseOneRecordingFrame(data);
return;
}
mStartTimeUs = timestampUs - mStartTimeUs;
}
}
++mNumFramesReceived;
CHECK(data != NULL && data->size() > 0);
mFramesReceived.push_back(data);
int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs);
mFrameTimes.push_back(timeUs);
ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64,
mStartTimeUs, timeUs);
mFrameAvailableCondition.signal();
}
Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak
Subtract address of a random static object from pointers being routed
through app process.
Bug: 28466701
Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04
CWE ID: CWE-200 | void CameraSource::dataCallbackTimestamp(int64_t timestampUs,
int32_t msgType __unused, const sp<IMemory> &data) {
ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs);
Mutex::Autolock autoLock(mLock);
if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) {
ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs);
releaseOneRecordingFrame(data);
return;
}
if (skipCurrentFrame(timestampUs)) {
releaseOneRecordingFrame(data);
return;
}
if (mNumFramesReceived > 0) {
if (timestampUs <= mLastFrameTimestampUs) {
ALOGW("Dropping frame with backward timestamp %lld (last %lld)",
(long long)timestampUs, (long long)mLastFrameTimestampUs);
releaseOneRecordingFrame(data);
return;
}
if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) {
++mNumGlitches;
}
}
mLastFrameTimestampUs = timestampUs;
if (mNumFramesReceived == 0) {
mFirstFrameTimeUs = timestampUs;
if (mStartTimeUs > 0) {
if (timestampUs < mStartTimeUs) {
releaseOneRecordingFrame(data);
return;
}
mStartTimeUs = timestampUs - mStartTimeUs;
}
}
++mNumFramesReceived;
CHECK(data != NULL && data->size() > 0);
// b/28466701
adjustIncomingANWBuffer(data.get());
mFramesReceived.push_back(data);
int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs);
mFrameTimes.push_back(timeUs);
ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64,
mStartTimeUs, timeUs);
mFrameAvailableCondition.signal();
}
| 173,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {
jas_eprintf("all tiles are outside the image area\n");
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
Commit Message: Added some missing sanity checks on the data in a SIZ marker segment.
CWE ID: CWE-20 | static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
siz->comps = 0;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
goto error;
}
if (!siz->width || !siz->height) {
jas_eprintf("reference grid cannot have zero area\n");
goto error;
}
if (!siz->tilewidth || !siz->tileheight) {
jas_eprintf("tile cannot have zero area\n");
goto error;
}
if (!siz->numcomps || siz->numcomps > 16384) {
jas_eprintf("number of components not in permissible range\n");
goto error;
}
if (siz->xoff >= siz->width) {
jas_eprintf("XOsiz not in permissible range\n");
goto error;
}
if (siz->yoff >= siz->height) {
jas_eprintf("YOsiz not in permissible range\n");
goto error;
}
if (siz->tilexoff > siz->xoff || siz->tilexoff + siz->tilewidth <= siz->xoff) {
jas_eprintf("XTOsiz not in permissible range\n");
goto error;
}
if (siz->tileyoff > siz->yoff || siz->tileyoff + siz->tileheight <= siz->yoff) {
jas_eprintf("YTOsiz not in permissible range\n");
goto error;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
goto error;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
goto error;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
goto error;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
goto error;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
goto error;
}
return 0;
error:
if (siz->comps) {
jas_free(siz->comps);
}
return -1;
}
| 168,731 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BindSkiaToInProcessGL() {
static bool host_StubGL_installed = false;
if (!host_StubGL_installed) {
GrGLBinding binding;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationNone:
NOTREACHED();
return;
case gfx::kGLImplementationDesktopGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationOSMesaGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationEGLGLES2:
binding = kES2_GrGLBinding;
break;
case gfx::kGLImplementationMockGL:
NOTREACHED();
return;
}
static GrGLInterface host_gl_interface = {
binding,
kProbe_GrGLCapability, // NPOTRenderTargetSupport
kProbe_GrGLCapability, // MinRenderTargetHeight
kProbe_GrGLCapability, // MinRenderTargetWidth
StubGLActiveTexture,
StubGLAttachShader,
StubGLBindAttribLocation,
StubGLBindBuffer,
StubGLBindTexture,
StubGLBlendColor,
StubGLBlendFunc,
StubGLBufferData,
StubGLBufferSubData,
StubGLClear,
StubGLClearColor,
StubGLClearStencil,
NULL, // glClientActiveTexture
NULL, // glColor4ub
StubGLColorMask,
NULL, // glColorPointer
StubGLCompileShader,
StubGLCompressedTexImage2D,
StubGLCreateProgram,
StubGLCreateShader,
StubGLCullFace,
StubGLDeleteBuffers,
StubGLDeleteProgram,
StubGLDeleteShader,
StubGLDeleteTextures,
StubGLDepthMask,
StubGLDisable,
NULL, // glDisableClientState
StubGLDisableVertexAttribArray,
StubGLDrawArrays,
StubGLDrawElements,
StubGLEnable,
NULL, // glEnableClientState
StubGLEnableVertexAttribArray,
StubGLFrontFace,
StubGLGenBuffers,
StubGLGenTextures,
StubGLGetBufferParameteriv,
StubGLGetError,
StubGLGetIntegerv,
StubGLGetProgramInfoLog,
StubGLGetProgramiv,
StubGLGetShaderInfoLog,
StubGLGetShaderiv,
StubGLGetString,
StubGLGetUniformLocation,
StubGLLineWidth,
StubGLLinkProgram,
NULL, // glLoadMatrixf
NULL, // glMatrixMode
StubGLPixelStorei,
NULL, // glPointSize
StubGLReadPixels,
StubGLScissor,
NULL, // glShadeModel
StubGLShaderSource,
StubGLStencilFunc,
StubGLStencilFuncSeparate,
StubGLStencilMask,
StubGLStencilMaskSeparate,
StubGLStencilOp,
StubGLStencilOpSeparate,
NULL, // glTexCoordPointer
NULL, // glTexEnvi
StubGLTexImage2D,
StubGLTexParameteri,
StubGLTexSubImage2D,
StubGLUniform1f,
StubGLUniform1i,
StubGLUniform1fv,
StubGLUniform1iv,
StubGLUniform2f,
StubGLUniform2i,
StubGLUniform2fv,
StubGLUniform2iv,
StubGLUniform3f,
StubGLUniform3i,
StubGLUniform3fv,
StubGLUniform3iv,
StubGLUniform4f,
StubGLUniform4i,
StubGLUniform4fv,
StubGLUniform4iv,
StubGLUniformMatrix2fv,
StubGLUniformMatrix3fv,
StubGLUniformMatrix4fv,
StubGLUseProgram,
StubGLVertexAttrib4fv,
StubGLVertexAttribPointer,
NULL, // glVertexPointer
StubGLViewport,
StubGLBindFramebuffer,
StubGLBindRenderbuffer,
StubGLCheckFramebufferStatus,
StubGLDeleteFramebuffers,
StubGLDeleteRenderbuffers,
StubGLFramebufferRenderbuffer,
StubGLFramebufferTexture2D,
StubGLGenFramebuffers,
StubGLGenRenderbuffers,
StubGLRenderBufferStorage,
StubGLRenderbufferStorageMultisample,
StubGLBlitFramebuffer,
NULL, // glResolveMultisampleFramebuffer
StubGLMapBuffer,
StubGLUnmapBuffer,
NULL, // glBindFragDataLocationIndexed
GrGLInterface::kStaticInitEndGuard,
};
GrGLSetGLInterface(&host_gl_interface);
host_StubGL_installed = true;
}
}
Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror.
It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp)
Remove now-redudant code that's implied by chromium_code: 1.
Fix the warnings that have crept in since chromium_code: 1 was removed.
BUG=none
TEST=none
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598
Review URL: http://codereview.chromium.org/7227009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void BindSkiaToInProcessGL() {
static bool host_StubGL_installed = false;
if (!host_StubGL_installed) {
GrGLBinding binding;
switch (gfx::GetGLImplementation()) {
case gfx::kGLImplementationNone:
NOTREACHED();
return;
case gfx::kGLImplementationDesktopGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationOSMesaGL:
binding = kDesktop_GrGLBinding;
break;
case gfx::kGLImplementationEGLGLES2:
binding = kES2_GrGLBinding;
break;
case gfx::kGLImplementationMockGL:
NOTREACHED();
return;
default:
NOTREACHED();
return;
}
static GrGLInterface host_gl_interface = {
binding,
kProbe_GrGLCapability, // NPOTRenderTargetSupport
kProbe_GrGLCapability, // MinRenderTargetHeight
kProbe_GrGLCapability, // MinRenderTargetWidth
StubGLActiveTexture,
StubGLAttachShader,
StubGLBindAttribLocation,
StubGLBindBuffer,
StubGLBindTexture,
StubGLBlendColor,
StubGLBlendFunc,
StubGLBufferData,
StubGLBufferSubData,
StubGLClear,
StubGLClearColor,
StubGLClearStencil,
NULL, // glClientActiveTexture
NULL, // glColor4ub
StubGLColorMask,
NULL, // glColorPointer
StubGLCompileShader,
StubGLCompressedTexImage2D,
StubGLCreateProgram,
StubGLCreateShader,
StubGLCullFace,
StubGLDeleteBuffers,
StubGLDeleteProgram,
StubGLDeleteShader,
StubGLDeleteTextures,
StubGLDepthMask,
StubGLDisable,
NULL, // glDisableClientState
StubGLDisableVertexAttribArray,
StubGLDrawArrays,
StubGLDrawElements,
StubGLEnable,
NULL, // glEnableClientState
StubGLEnableVertexAttribArray,
StubGLFrontFace,
StubGLGenBuffers,
StubGLGenTextures,
StubGLGetBufferParameteriv,
StubGLGetError,
StubGLGetIntegerv,
StubGLGetProgramInfoLog,
StubGLGetProgramiv,
StubGLGetShaderInfoLog,
StubGLGetShaderiv,
StubGLGetString,
StubGLGetUniformLocation,
StubGLLineWidth,
StubGLLinkProgram,
NULL, // glLoadMatrixf
NULL, // glMatrixMode
StubGLPixelStorei,
NULL, // glPointSize
StubGLReadPixels,
StubGLScissor,
NULL, // glShadeModel
StubGLShaderSource,
StubGLStencilFunc,
StubGLStencilFuncSeparate,
StubGLStencilMask,
StubGLStencilMaskSeparate,
StubGLStencilOp,
StubGLStencilOpSeparate,
NULL, // glTexCoordPointer
NULL, // glTexEnvi
StubGLTexImage2D,
StubGLTexParameteri,
StubGLTexSubImage2D,
StubGLUniform1f,
StubGLUniform1i,
StubGLUniform1fv,
StubGLUniform1iv,
StubGLUniform2f,
StubGLUniform2i,
StubGLUniform2fv,
StubGLUniform2iv,
StubGLUniform3f,
StubGLUniform3i,
StubGLUniform3fv,
StubGLUniform3iv,
StubGLUniform4f,
StubGLUniform4i,
StubGLUniform4fv,
StubGLUniform4iv,
StubGLUniformMatrix2fv,
StubGLUniformMatrix3fv,
StubGLUniformMatrix4fv,
StubGLUseProgram,
StubGLVertexAttrib4fv,
StubGLVertexAttribPointer,
NULL, // glVertexPointer
StubGLViewport,
StubGLBindFramebuffer,
StubGLBindRenderbuffer,
StubGLCheckFramebufferStatus,
StubGLDeleteFramebuffers,
StubGLDeleteRenderbuffers,
StubGLFramebufferRenderbuffer,
StubGLFramebufferTexture2D,
StubGLGenFramebuffers,
StubGLGenRenderbuffers,
StubGLRenderBufferStorage,
StubGLRenderbufferStorageMultisample,
StubGLBlitFramebuffer,
NULL, // glResolveMultisampleFramebuffer
StubGLMapBuffer,
StubGLUnmapBuffer,
NULL, // glBindFragDataLocationIndexed
GrGLInterface::kStaticInitEndGuard,
};
GrGLSetGLInterface(&host_gl_interface);
host_StubGL_installed = true;
}
}
| 170,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long keyctl_update_key(key_serial_t id,
const void __user *_payload,
size_t plen)
{
key_ref_t key_ref;
void *payload;
long ret;
ret = -EINVAL;
if (plen > PAGE_SIZE)
goto error;
/* pull the payload in if one was supplied */
payload = NULL;
if (_payload) {
ret = -ENOMEM;
payload = kmalloc(plen, GFP_KERNEL);
if (!payload)
goto error;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error2;
}
/* find the target key (which must be writable) */
key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
if (IS_ERR(key_ref)) {
ret = PTR_ERR(key_ref);
goto error2;
}
/* update the key */
ret = key_update(key_ref, payload, plen);
key_ref_put(key_ref);
error2:
kfree(payload);
error:
return ret;
}
Commit Message: KEYS: fix dereferencing NULL payload with nonzero length
sys_add_key() and the KEYCTL_UPDATE operation of sys_keyctl() allowed a
NULL payload with nonzero length to be passed to the key type's
->preparse(), ->instantiate(), and/or ->update() methods. Various key
types including asymmetric, cifs.idmap, cifs.spnego, and pkcs7_test did
not handle this case, allowing an unprivileged user to trivially cause a
NULL pointer dereference (kernel oops) if one of these key types was
present. Fix it by doing the copy_from_user() when 'plen' is nonzero
rather than when '_payload' is non-NULL, causing the syscall to fail
with EFAULT as expected when an invalid buffer is specified.
Cc: [email protected] # 2.6.10+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-476 | long keyctl_update_key(key_serial_t id,
const void __user *_payload,
size_t plen)
{
key_ref_t key_ref;
void *payload;
long ret;
ret = -EINVAL;
if (plen > PAGE_SIZE)
goto error;
/* pull the payload in if one was supplied */
payload = NULL;
if (plen) {
ret = -ENOMEM;
payload = kmalloc(plen, GFP_KERNEL);
if (!payload)
goto error;
ret = -EFAULT;
if (copy_from_user(payload, _payload, plen) != 0)
goto error2;
}
/* find the target key (which must be writable) */
key_ref = lookup_user_key(id, 0, KEY_NEED_WRITE);
if (IS_ERR(key_ref)) {
ret = PTR_ERR(key_ref);
goto error2;
}
/* update the key */
ret = key_update(key_ref, payload, plen);
key_ref_put(key_ref);
error2:
kfree(payload);
error:
return ret;
}
| 167,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sgi_clock_set(clockid_t clockid, struct timespec *tp)
{
u64 nsec;
u64 rem;
nsec = rtc_time() * sgi_clock_period;
sgi_clock_offset.tv_sec = tp->tv_sec - div_long_long_rem(nsec, NSEC_PER_SEC, &rem);
if (rem <= tp->tv_nsec)
sgi_clock_offset.tv_nsec = tp->tv_sec - rem;
else {
sgi_clock_offset.tv_nsec = tp->tv_sec + NSEC_PER_SEC - rem;
sgi_clock_offset.tv_sec--;
}
return 0;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189 | static int sgi_clock_set(clockid_t clockid, struct timespec *tp)
{
u64 nsec;
u32 rem;
nsec = rtc_time() * sgi_clock_period;
sgi_clock_offset.tv_sec = tp->tv_sec - div_u64_rem(nsec, NSEC_PER_SEC, &rem);
if (rem <= tp->tv_nsec)
sgi_clock_offset.tv_nsec = tp->tv_sec - rem;
else {
sgi_clock_offset.tv_nsec = tp->tv_sec + NSEC_PER_SEC - rem;
sgi_clock_offset.tv_sec--;
}
return 0;
}
| 165,750 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 svc_rdma_handle_bc_reply(struct rpc_xprt *xprt, struct rpcrdma_msg *rmsgp,
struct xdr_buf *rcvbuf)
{
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt);
struct kvec *dst, *src = &rcvbuf->head[0];
struct rpc_rqst *req;
unsigned long cwnd;
u32 credits;
size_t len;
__be32 xid;
__be32 *p;
int ret;
p = (__be32 *)src->iov_base;
len = src->iov_len;
xid = rmsgp->rm_xid;
#ifdef SVCRDMA_BACKCHANNEL_DEBUG
pr_info("%s: xid=%08x, length=%zu\n",
__func__, be32_to_cpu(xid), len);
pr_info("%s: RPC/RDMA: %*ph\n",
__func__, (int)RPCRDMA_HDRLEN_MIN, rmsgp);
pr_info("%s: RPC: %*ph\n",
__func__, (int)len, p);
#endif
ret = -EAGAIN;
if (src->iov_len < 24)
goto out_shortreply;
spin_lock_bh(&xprt->transport_lock);
req = xprt_lookup_rqst(xprt, xid);
if (!req)
goto out_notfound;
dst = &req->rq_private_buf.head[0];
memcpy(&req->rq_private_buf, &req->rq_rcv_buf, sizeof(struct xdr_buf));
if (dst->iov_len < len)
goto out_unlock;
memcpy(dst->iov_base, p, len);
credits = be32_to_cpu(rmsgp->rm_credit);
if (credits == 0)
credits = 1; /* don't deadlock */
else if (credits > r_xprt->rx_buf.rb_bc_max_requests)
credits = r_xprt->rx_buf.rb_bc_max_requests;
cwnd = xprt->cwnd;
xprt->cwnd = credits << RPC_CWNDSHIFT;
if (xprt->cwnd > cwnd)
xprt_release_rqst_cong(req->rq_task);
ret = 0;
xprt_complete_rqst(req->rq_task, rcvbuf->len);
rcvbuf->len = 0;
out_unlock:
spin_unlock_bh(&xprt->transport_lock);
out:
return ret;
out_shortreply:
dprintk("svcrdma: short bc reply: xprt=%p, len=%zu\n",
xprt, src->iov_len);
goto out;
out_notfound:
dprintk("svcrdma: unrecognized bc reply: xprt=%p, xid=%08x\n",
xprt, be32_to_cpu(xid));
goto out_unlock;
}
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 | int svc_rdma_handle_bc_reply(struct rpc_xprt *xprt, struct rpcrdma_msg *rmsgp,
/**
* svc_rdma_handle_bc_reply - Process incoming backchannel reply
* @xprt: controlling backchannel transport
* @rdma_resp: pointer to incoming transport header
* @rcvbuf: XDR buffer into which to decode the reply
*
* Returns:
* %0 if @rcvbuf is filled in, xprt_complete_rqst called,
* %-EAGAIN if server should call ->recvfrom again.
*/
int svc_rdma_handle_bc_reply(struct rpc_xprt *xprt, __be32 *rdma_resp,
struct xdr_buf *rcvbuf)
{
struct rpcrdma_xprt *r_xprt = rpcx_to_rdmax(xprt);
struct kvec *dst, *src = &rcvbuf->head[0];
struct rpc_rqst *req;
unsigned long cwnd;
u32 credits;
size_t len;
__be32 xid;
__be32 *p;
int ret;
p = (__be32 *)src->iov_base;
len = src->iov_len;
xid = *rdma_resp;
#ifdef SVCRDMA_BACKCHANNEL_DEBUG
pr_info("%s: xid=%08x, length=%zu\n",
__func__, be32_to_cpu(xid), len);
pr_info("%s: RPC/RDMA: %*ph\n",
__func__, (int)RPCRDMA_HDRLEN_MIN, rdma_resp);
pr_info("%s: RPC: %*ph\n",
__func__, (int)len, p);
#endif
ret = -EAGAIN;
if (src->iov_len < 24)
goto out_shortreply;
spin_lock_bh(&xprt->transport_lock);
req = xprt_lookup_rqst(xprt, xid);
if (!req)
goto out_notfound;
dst = &req->rq_private_buf.head[0];
memcpy(&req->rq_private_buf, &req->rq_rcv_buf, sizeof(struct xdr_buf));
if (dst->iov_len < len)
goto out_unlock;
memcpy(dst->iov_base, p, len);
credits = be32_to_cpup(rdma_resp + 2);
if (credits == 0)
credits = 1; /* don't deadlock */
else if (credits > r_xprt->rx_buf.rb_bc_max_requests)
credits = r_xprt->rx_buf.rb_bc_max_requests;
cwnd = xprt->cwnd;
xprt->cwnd = credits << RPC_CWNDSHIFT;
if (xprt->cwnd > cwnd)
xprt_release_rqst_cong(req->rq_task);
ret = 0;
xprt_complete_rqst(req->rq_task, rcvbuf->len);
rcvbuf->len = 0;
out_unlock:
spin_unlock_bh(&xprt->transport_lock);
out:
return ret;
out_shortreply:
dprintk("svcrdma: short bc reply: xprt=%p, len=%zu\n",
xprt, src->iov_len);
goto out;
out_notfound:
dprintk("svcrdma: unrecognized bc reply: xprt=%p, xid=%08x\n",
xprt, be32_to_cpu(xid));
goto out_unlock;
}
| 168,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, strlen(dst) + 1);
return dst;
}
Commit Message:
CWE ID: CWE-200 | char *ldb_dn_escape_value(TALLOC_CTX *mem_ctx, struct ldb_val value)
{
char *dst;
size_t len;
if (!value.length)
return NULL;
/* allocate destination string, it will be at most 3 times the source */
dst = talloc_array(mem_ctx, char, value.length * 3 + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
len = ldb_dn_escape_internal(dst, (const char *)value.data, value.length);
dst = talloc_realloc(mem_ctx, dst, char, len + 1);
if ( ! dst) {
talloc_free(dst);
return NULL;
}
dst[len] = '\0';
return dst;
}
| 164,674 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.