instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
Commit Message:
CWE ID: | static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
{
const unsigned char *p;
int plen;
if (alg == NULL || alg->parameter == NULL)
return NULL;
if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
return NULL;
if (alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
return d2i_X509_ALGOR(NULL, &p, plen);
}
| 164,720 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
{
return pm->current_gamma != 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | modifier_color_encoding_is_set(PNG_CONST png_modifier *pm)
modifier_color_encoding_is_set(const png_modifier *pm)
{
return pm->current_gamma != 0;
}
| 173,668 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int svc_rdma_sendto(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
struct rpcrdma_msg *rdma_argp;
struct rpcrdma_msg *rdma_resp;
struct rpcrdma_write_array *wr_ary, *rp_ary;
int ret;
int inline_bytes;
struct page *res_page;
struct svc_rdma_req_map *vec;
u32 inv_rkey;
__be32 *p;
dprintk("svcrdma: sending response for rqstp=%p\n", rqstp);
/* Get the RDMA request header. The receive logic always
* places this at the start of page 0.
*/
rdma_argp = page_address(rqstp->rq_pages[0]);
svc_rdma_get_write_arrays(rdma_argp, &wr_ary, &rp_ary);
inv_rkey = 0;
if (rdma->sc_snd_w_inv)
inv_rkey = svc_rdma_get_inv_rkey(rdma_argp, wr_ary, rp_ary);
/* Build an req vec for the XDR */
vec = svc_rdma_get_req_map(rdma);
ret = svc_rdma_map_xdr(rdma, &rqstp->rq_res, vec, wr_ary != NULL);
if (ret)
goto err0;
inline_bytes = rqstp->rq_res.len;
/* Create the RDMA response header. xprt->xpt_mutex,
* acquired in svc_send(), serializes RPC replies. The
* code path below that inserts the credit grant value
* into each transport header runs only inside this
* critical section.
*/
ret = -ENOMEM;
res_page = alloc_page(GFP_KERNEL);
if (!res_page)
goto err0;
rdma_resp = page_address(res_page);
p = &rdma_resp->rm_xid;
*p++ = rdma_argp->rm_xid;
*p++ = rdma_argp->rm_vers;
*p++ = rdma->sc_fc_credits;
*p++ = rp_ary ? rdma_nomsg : rdma_msg;
/* Start with empty chunks */
*p++ = xdr_zero;
*p++ = xdr_zero;
*p = xdr_zero;
/* Send any write-chunk data and build resp write-list */
if (wr_ary) {
ret = send_write_chunks(rdma, wr_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret + xdr_padsize(ret);
}
/* Send any reply-list data and update resp reply-list */
if (rp_ary) {
ret = send_reply_chunks(rdma, rp_ary, rdma_resp, rqstp, vec);
if (ret < 0)
goto err1;
inline_bytes -= ret;
}
/* Post a fresh Receive buffer _before_ sending the reply */
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = send_reply(rdma, rqstp, res_page, rdma_resp, vec,
inline_bytes, inv_rkey);
if (ret < 0)
goto err0;
svc_rdma_put_req_map(rdma, vec);
dprintk("svcrdma: send_reply returns %d\n", ret);
return ret;
err1:
put_page(res_page);
err0:
svc_rdma_put_req_map(rdma, vec);
pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n",
ret);
set_bit(XPT_CLOSE, &rdma->sc_xprt.xpt_flags);
return -ENOTCONN;
}
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_sendto(struct svc_rqst *rqstp)
{
struct svc_xprt *xprt = rqstp->rq_xprt;
struct svcxprt_rdma *rdma =
container_of(xprt, struct svcxprt_rdma, sc_xprt);
__be32 *p, *rdma_argp, *rdma_resp, *wr_lst, *rp_ch;
struct xdr_buf *xdr = &rqstp->rq_res;
struct page *res_page;
int ret;
/* Find the call's chunk lists to decide how to send the reply.
* Receive places the Call's xprt header at the start of page 0.
*/
rdma_argp = page_address(rqstp->rq_pages[0]);
svc_rdma_get_write_arrays(rdma_argp, &wr_lst, &rp_ch);
dprintk("svcrdma: preparing response for XID 0x%08x\n",
be32_to_cpup(rdma_argp));
/* Create the RDMA response header. xprt->xpt_mutex,
* acquired in svc_send(), serializes RPC replies. The
* code path below that inserts the credit grant value
* into each transport header runs only inside this
* critical section.
*/
ret = -ENOMEM;
res_page = alloc_page(GFP_KERNEL);
if (!res_page)
goto err0;
rdma_resp = page_address(res_page);
p = rdma_resp;
*p++ = *rdma_argp;
*p++ = *(rdma_argp + 1);
*p++ = rdma->sc_fc_credits;
*p++ = rp_ch ? rdma_nomsg : rdma_msg;
/* Start with empty chunks */
*p++ = xdr_zero;
*p++ = xdr_zero;
*p = xdr_zero;
if (wr_lst) {
/* XXX: Presume the client sent only one Write chunk */
ret = svc_rdma_send_write_chunk(rdma, wr_lst, xdr);
if (ret < 0)
goto err2;
svc_rdma_xdr_encode_write_list(rdma_resp, wr_lst, ret);
}
if (rp_ch) {
ret = svc_rdma_send_reply_chunk(rdma, rp_ch, wr_lst, xdr);
if (ret < 0)
goto err2;
svc_rdma_xdr_encode_reply_chunk(rdma_resp, rp_ch, ret);
}
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = svc_rdma_send_reply_msg(rdma, rdma_argp, rdma_resp, rqstp,
wr_lst, rp_ch);
if (ret < 0)
goto err0;
return 0;
err2:
if (ret != -E2BIG)
goto err1;
ret = svc_rdma_post_recv(rdma, GFP_KERNEL);
if (ret)
goto err1;
ret = svc_rdma_send_error_msg(rdma, rdma_resp, rqstp);
if (ret < 0)
goto err0;
return 0;
err1:
put_page(res_page);
err0:
pr_err("svcrdma: Could not send reply, err=%d. Closing transport.\n",
ret);
set_bit(XPT_CLOSE, &xprt->xpt_flags);
return -ENOTCONN;
}
| 168,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: hstore_from_record(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec;
int32 buflen;
HStore *out;
Pairs *pairs;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tuple;
RecordIOData *my_extra;
int ncolumns;
int i,
j;
Datum *values;
bool *nulls;
if (PG_ARGISNULL(0))
{
Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
/*
* have no tuple to look at, so the only source of type info is the
* argtype. The lookup_rowtype_tupdesc call below will error out if we
* don't have a known composite type oid here.
*/
tupType = argtype;
tupTypmod = -1;
rec = NULL;
}
else
{
rec = PG_GETARG_HEAPTUPLEHEADER(0);
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
}
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/*
* We arrange to look up the needed I/O info just once per series of
* calls, assuming the record type doesn't change underneath us.
*/
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
if (my_extra == NULL ||
my_extra->ncolumns != ncolumns)
{
fcinfo->flinfo->fn_extra =
MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
my_extra->record_type = InvalidOid;
my_extra->record_typmod = 0;
}
if (my_extra->record_type != tupType ||
my_extra->record_typmod != tupTypmod)
{
MemSet(my_extra, 0,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra->record_type = tupType;
my_extra->record_typmod = tupTypmod;
my_extra->ncolumns = ncolumns;
}
pairs = palloc(ncolumns * sizeof(Pairs));
if (rec)
{
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
else
{
values = NULL;
nulls = NULL;
}
for (i = 0, j = 0; i < ncolumns; ++i)
{
ColumnIOData *column_info = &my_extra->columns[i];
Oid column_type = tupdesc->attrs[i]->atttypid;
char *value;
/* Ignore dropped columns in datatype */
if (tupdesc->attrs[i]->attisdropped)
continue;
pairs[j].key = NameStr(tupdesc->attrs[i]->attname);
pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));
if (!nulls || nulls[i])
{
pairs[j].val = NULL;
pairs[j].vallen = 4;
pairs[j].isnull = true;
pairs[j].needfree = false;
++j;
continue;
}
/*
* Convert the column value to text
*/
if (column_info->column_type != column_type)
{
bool typIsVarlena;
getTypeOutputInfo(column_type,
&column_info->typiofunc,
&typIsVarlena);
fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
fcinfo->flinfo->fn_mcxt);
column_info->column_type = column_type;
}
value = OutputFunctionCall(&column_info->proc, values[i]);
pairs[j].val = value;
pairs[j].vallen = hstoreCheckValLen(strlen(value));
pairs[j].isnull = false;
pairs[j].needfree = false;
++j;
}
ncolumns = hstoreUniquePairs(pairs, j, &buflen);
out = hstorePairs(pairs, ncolumns, buflen);
ReleaseTupleDesc(tupdesc);
PG_RETURN_POINTER(out);
}
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 | hstore_from_record(PG_FUNCTION_ARGS)
{
HeapTupleHeader rec;
int32 buflen;
HStore *out;
Pairs *pairs;
Oid tupType;
int32 tupTypmod;
TupleDesc tupdesc;
HeapTupleData tuple;
RecordIOData *my_extra;
int ncolumns;
int i,
j;
Datum *values;
bool *nulls;
if (PG_ARGISNULL(0))
{
Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
/*
* have no tuple to look at, so the only source of type info is the
* argtype. The lookup_rowtype_tupdesc call below will error out if we
* don't have a known composite type oid here.
*/
tupType = argtype;
tupTypmod = -1;
rec = NULL;
}
else
{
rec = PG_GETARG_HEAPTUPLEHEADER(0);
/* Extract type info from the tuple itself */
tupType = HeapTupleHeaderGetTypeId(rec);
tupTypmod = HeapTupleHeaderGetTypMod(rec);
}
tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
ncolumns = tupdesc->natts;
/*
* We arrange to look up the needed I/O info just once per series of
* calls, assuming the record type doesn't change underneath us.
*/
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
if (my_extra == NULL ||
my_extra->ncolumns != ncolumns)
{
fcinfo->flinfo->fn_extra =
MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra = (RecordIOData *) fcinfo->flinfo->fn_extra;
my_extra->record_type = InvalidOid;
my_extra->record_typmod = 0;
}
if (my_extra->record_type != tupType ||
my_extra->record_typmod != tupTypmod)
{
MemSet(my_extra, 0,
sizeof(RecordIOData) - sizeof(ColumnIOData)
+ ncolumns * sizeof(ColumnIOData));
my_extra->record_type = tupType;
my_extra->record_typmod = tupTypmod;
my_extra->ncolumns = ncolumns;
}
Assert(ncolumns <= MaxTupleAttributeNumber); /* thus, no overflow */
pairs = palloc(ncolumns * sizeof(Pairs));
if (rec)
{
/* Build a temporary HeapTuple control structure */
tuple.t_len = HeapTupleHeaderGetDatumLength(rec);
ItemPointerSetInvalid(&(tuple.t_self));
tuple.t_tableOid = InvalidOid;
tuple.t_data = rec;
values = (Datum *) palloc(ncolumns * sizeof(Datum));
nulls = (bool *) palloc(ncolumns * sizeof(bool));
/* Break down the tuple into fields */
heap_deform_tuple(&tuple, tupdesc, values, nulls);
}
else
{
values = NULL;
nulls = NULL;
}
for (i = 0, j = 0; i < ncolumns; ++i)
{
ColumnIOData *column_info = &my_extra->columns[i];
Oid column_type = tupdesc->attrs[i]->atttypid;
char *value;
/* Ignore dropped columns in datatype */
if (tupdesc->attrs[i]->attisdropped)
continue;
pairs[j].key = NameStr(tupdesc->attrs[i]->attname);
pairs[j].keylen = hstoreCheckKeyLen(strlen(NameStr(tupdesc->attrs[i]->attname)));
if (!nulls || nulls[i])
{
pairs[j].val = NULL;
pairs[j].vallen = 4;
pairs[j].isnull = true;
pairs[j].needfree = false;
++j;
continue;
}
/*
* Convert the column value to text
*/
if (column_info->column_type != column_type)
{
bool typIsVarlena;
getTypeOutputInfo(column_type,
&column_info->typiofunc,
&typIsVarlena);
fmgr_info_cxt(column_info->typiofunc, &column_info->proc,
fcinfo->flinfo->fn_mcxt);
column_info->column_type = column_type;
}
value = OutputFunctionCall(&column_info->proc, values[i]);
pairs[j].val = value;
pairs[j].vallen = hstoreCheckValLen(strlen(value));
pairs[j].isnull = false;
pairs[j].needfree = false;
++j;
}
ncolumns = hstoreUniquePairs(pairs, j, &buflen);
out = hstorePairs(pairs, ncolumns, buflen);
ReleaseTupleDesc(tupdesc);
PG_RETURN_POINTER(out);
}
| 166,398 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GDataEntry* GDataEntry::FromDocumentEntry(
GDataDirectory* parent,
DocumentEntry* doc,
GDataDirectoryService* directory_service) {
DCHECK(doc);
if (doc->is_folder())
return GDataDirectory::FromDocumentEntry(parent, doc, directory_service);
else if (doc->is_hosted_document() || doc->is_file())
return GDataFile::FromDocumentEntry(parent, doc, directory_service);
return NULL;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | GDataEntry* GDataEntry::FromDocumentEntry(
| 171,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
int index) {
CheckTabCount();
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void TabCountChangeObserver::TabDetachedAt(TabContents* contents,
void TabCountChangeObserver::TabDetachedAt(WebContents* contents,
int index) {
CheckTabCount();
}
| 171,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) {
NavigationEntry* pending_entry = controller_->GetPendingEntry();
bool pending_matches_fail_msg =
pending_entry &&
expected_pending_entry_id == pending_entry->GetUniqueID();
if (!pending_matches_fail_msg)
return;
bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
delegate_->ShouldPreserveAbortedURLs();
if (pending_entry != controller_->GetVisibleEntry() ||
!should_preserve_entry) {
controller_->DiscardPendingEntry(true);
controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
}
Commit Message: Don't preserve NavigationEntry for failed navigations with invalid URLs.
The formatting logic may rewrite such URLs into an unsafe state. This
is a first step before preventing navigations to invalid URLs entirely.
Bug: 850824
Change-Id: I71743bfb4b610d55ce901ee8902125f934a2bb23
Reviewed-on: https://chromium-review.googlesource.com/c/1252942
Reviewed-by: Alex Moshchuk <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597304}
CWE ID: CWE-20 | void NavigatorImpl::DiscardPendingEntryIfNeeded(int expected_pending_entry_id) {
NavigationEntry* pending_entry = controller_->GetPendingEntry();
bool pending_matches_fail_msg =
pending_entry &&
expected_pending_entry_id == pending_entry->GetUniqueID();
if (!pending_matches_fail_msg)
return;
// Do not leave the pending entry visible if it has an invalid URL, since this
// might be formatted in an unexpected or unsafe way.
// TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
//
bool should_preserve_entry = pending_entry->GetURL().is_valid() &&
(controller_->IsUnmodifiedBlankTab() ||
delegate_->ShouldPreserveAbortedURLs());
if (pending_entry != controller_->GetVisibleEntry() ||
!should_preserve_entry) {
controller_->DiscardPendingEntry(true);
controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
}
}
| 172,613 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BlockEntry::BlockEntry(Cluster* p, long idx) :
m_pCluster(p),
m_index(idx)
{
}
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 | BlockEntry::BlockEntry(Cluster* p, long idx) :
BlockEntry::~BlockEntry() {}
bool BlockEntry::EOS() const { return (GetKind() == kBlockEOS); }
const Cluster* BlockEntry::GetCluster() const { return m_pCluster; }
long BlockEntry::GetIndex() const { return m_index; }
SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start,
long long size)
: BlockEntry(pCluster, idx), m_block(start, size, 0) {}
long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); }
BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; }
const Block* SimpleBlock::GetBlock() const { return &m_block; }
BlockGroup::BlockGroup(Cluster* pCluster, long idx, long long block_start,
long long block_size, long long prev, long long next,
long long duration, long long discard_padding)
: BlockEntry(pCluster, idx),
m_block(block_start, block_size, discard_padding),
m_prev(prev),
m_next(next),
m_duration(duration) {}
long BlockGroup::Parse() {
const long status = m_block.Parse(m_pCluster);
if (status)
return status;
m_block.SetKey((m_prev > 0) && (m_next <= 0));
return 0;
}
| 174,241 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main(int argc, char *argv[]) {
char *fin, *fout;
FILE *fpin, *fpout;
uint8_t *inbuf, *outbuf;
uint8_t *inbuf_u, *outbuf_u;
uint8_t *inbuf_v, *outbuf_v;
int f, frames;
int width, height, target_width, target_height;
if (argc < 5) {
printf("Incorrect parameters:\n");
usage(argv[0]);
return 1;
}
fin = argv[1];
fout = argv[4];
if (!parse_dim(argv[2], &width, &height)) {
printf("Incorrect parameters: %s\n", argv[2]);
usage(argv[0]);
return 1;
}
if (!parse_dim(argv[3], &target_width, &target_height)) {
printf("Incorrect parameters: %s\n", argv[3]);
usage(argv[0]);
return 1;
}
fpin = fopen(fin, "rb");
if (fpin == NULL) {
printf("Can't open file %s to read\n", fin);
usage(argv[0]);
return 1;
}
fpout = fopen(fout, "wb");
if (fpout == NULL) {
printf("Can't open file %s to write\n", fout);
usage(argv[0]);
return 1;
}
if (argc >= 6)
frames = atoi(argv[5]);
else
frames = INT_MAX;
printf("Input size: %dx%d\n",
width, height);
printf("Target size: %dx%d, Frames: ",
target_width, target_height);
if (frames == INT_MAX)
printf("All\n");
else
printf("%d\n", frames);
inbuf = (uint8_t*)malloc(width * height * 3 / 2);
outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2);
inbuf_u = inbuf + width * height;
inbuf_v = inbuf_u + width * height / 4;
outbuf_u = outbuf + target_width * target_height;
outbuf_v = outbuf_u + target_width * target_height / 4;
f = 0;
while (f < frames) {
if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1)
break;
vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2,
height, width,
outbuf, target_width, outbuf_u, outbuf_v,
target_width / 2,
target_height, target_width);
fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout);
f++;
}
printf("%d frames processed\n", f);
fclose(fpin);
fclose(fpout);
free(inbuf);
free(outbuf);
return 0;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | int main(int argc, char *argv[]) {
char *fin, *fout;
FILE *fpin, *fpout;
uint8_t *inbuf, *outbuf;
uint8_t *inbuf_u, *outbuf_u;
uint8_t *inbuf_v, *outbuf_v;
int f, frames;
int width, height, target_width, target_height;
exec_name = argv[0];
if (argc < 5) {
printf("Incorrect parameters:\n");
usage();
return 1;
}
fin = argv[1];
fout = argv[4];
if (!parse_dim(argv[2], &width, &height)) {
printf("Incorrect parameters: %s\n", argv[2]);
usage();
return 1;
}
if (!parse_dim(argv[3], &target_width, &target_height)) {
printf("Incorrect parameters: %s\n", argv[3]);
usage();
return 1;
}
fpin = fopen(fin, "rb");
if (fpin == NULL) {
printf("Can't open file %s to read\n", fin);
usage();
return 1;
}
fpout = fopen(fout, "wb");
if (fpout == NULL) {
printf("Can't open file %s to write\n", fout);
usage();
return 1;
}
if (argc >= 6)
frames = atoi(argv[5]);
else
frames = INT_MAX;
printf("Input size: %dx%d\n",
width, height);
printf("Target size: %dx%d, Frames: ",
target_width, target_height);
if (frames == INT_MAX)
printf("All\n");
else
printf("%d\n", frames);
inbuf = (uint8_t*)malloc(width * height * 3 / 2);
outbuf = (uint8_t*)malloc(target_width * target_height * 3 / 2);
inbuf_u = inbuf + width * height;
inbuf_v = inbuf_u + width * height / 4;
outbuf_u = outbuf + target_width * target_height;
outbuf_v = outbuf_u + target_width * target_height / 4;
f = 0;
while (f < frames) {
if (fread(inbuf, width * height * 3 / 2, 1, fpin) != 1)
break;
vp9_resize_frame420(inbuf, width, inbuf_u, inbuf_v, width / 2,
height, width,
outbuf, target_width, outbuf_u, outbuf_v,
target_width / 2,
target_height, target_width);
fwrite(outbuf, target_width * target_height * 3 / 2, 1, fpout);
f++;
}
printf("%d frames processed\n", f);
fclose(fpin);
fclose(fpout);
free(inbuf);
free(outbuf);
return 0;
}
| 174,479 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info,
ogg_int32_t **in,int *nonzero,int ch){
int i,j,k,s,used=0;
codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup;
codebook *phrasebook=ci->book_param+info->groupbook;
int samples_per_partition=info->grouping;
int partitions_per_word=phrasebook->dim;
int pcmend=ci->blocksizes[vd->W];
if(info->type<2){
int max=pcmend>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
for(i=0;i<ch;i++)
if(nonzero[i])
in[used++]=in[i];
ch=used;
if(used){
char **partword=(char **)alloca(ch*sizeof(*partword));
for(j=0;j<ch;j++)
partword[j]=(char *)alloca(partwords*partitions_per_word*
sizeof(*partword[j]));
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
/* fetch the partition word for each channel */
partword[0][i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[0][i+k]=partword[0][i+k+1]*info->partitions;
for(j=1;j<ch;j++)
for(k=partitions_per_word-1;k>=0;k--)
partword[j][i+k]=partword[j-1][i+k];
for(j=0;j<ch;j++){
int temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[j][i+k];
partword[j][i+k]=temp/div;
temp-=partword[j][i+k]*div;
}
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
for(j=0;j<ch;j++){
long offset=info->begin+i*samples_per_partition;
if(info->stagemasks[(int)partword[j][i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[j][i]<<3)+s];
if(info->type){
if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}else{
if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
}
}
}else{
int max=(pcmend*ch)>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
char *partword=
(char *)alloca(partwords*partitions_per_word*sizeof(*partword));
int beginoff=info->begin/ch;
for(i=0;i<ch;i++)if(nonzero[i])break;
if(i==ch)return(0); /* no nonzero vectors */
samples_per_partition/=ch;
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
int temp;
partword[i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[i+k]=partword[i+k+1]*info->partitions;
/* fetch the partition word */
temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[i+k];
partword[i+k]=temp/div;
temp-=partword[i+k]*div;
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
if(info->stagemasks[(int)partword[i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[i]<<3)+s];
if(vorbis_book_decodevv_add(stagebook,in,
i*samples_per_partition+beginoff,ch,
&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
eopbreak:
return 0;
}
Commit Message: Check partword is in range for # of partitions
and reformat tabs->spaces for readability.
Bug: 28556125
Change-Id: Id02819a6a5bcc24ba4f8a502081e5cb45272681c
CWE ID: CWE-20 | int res_inverse(vorbis_dsp_state *vd,vorbis_info_residue *info,
ogg_int32_t **in,int *nonzero,int ch){
int i,j,k,s,used=0;
codec_setup_info *ci=(codec_setup_info *)vd->vi->codec_setup;
codebook *phrasebook=ci->book_param+info->groupbook;
int samples_per_partition=info->grouping;
int partitions_per_word=phrasebook->dim;
int pcmend=ci->blocksizes[vd->W];
if(info->type<2){
int max=pcmend>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
for(i=0;i<ch;i++)
if(nonzero[i])
in[used++]=in[i];
ch=used;
if(used){
char **partword=(char **)alloca(ch*sizeof(*partword));
for(j=0;j<ch;j++)
partword[j]=(char *)alloca(partwords*partitions_per_word*
sizeof(*partword[j]));
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
/* fetch the partition word for each channel */
partword[0][i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[0][i+k]=partword[0][i+k+1]*info->partitions;
for(j=1;j<ch;j++)
for(k=partitions_per_word-1;k>=0;k--)
partword[j][i+k]=partword[j-1][i+k];
for(j=0;j<ch;j++){
int temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[j][i+k];
partword[j][i+k]=temp/div;
temp-=partword[j][i+k]*div;
}
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
for(j=0;j<ch;j++){
long offset=info->begin+i*samples_per_partition;
int idx = (int)partword[j][i];
if(idx < info->partitions && info->stagemasks[idx]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[j][i]<<3)+s];
if(info->type){
if(vorbis_book_decodev_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}else{
if(vorbis_book_decodevs_add(stagebook,in[j]+offset,&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
}
}
}else{
int max=(pcmend*ch)>>1;
int end=(info->end<max?info->end:max);
int n=end-info->begin;
if(n>0){
int partvals=n/samples_per_partition;
int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
char *partword=
(char *)alloca(partwords*partitions_per_word*sizeof(*partword));
int beginoff=info->begin/ch;
for(i=0;i<ch;i++)if(nonzero[i])break;
if(i==ch)return(0); /* no nonzero vectors */
samples_per_partition/=ch;
for(s=0;s<info->stages;s++){
for(i=0;i<partvals;){
if(s==0){
int temp;
partword[i+partitions_per_word-1]=1;
for(k=partitions_per_word-2;k>=0;k--)
partword[i+k]=partword[i+k+1]*info->partitions;
/* fetch the partition word */
temp=vorbis_book_decode(phrasebook,&vd->opb);
if(temp==-1)goto eopbreak;
/* this can be done quickly in assembly due to the quotient
always being at most six bits */
for(k=0;k<partitions_per_word;k++){
ogg_uint32_t div=partword[i+k];
partword[i+k]=temp/div;
temp-=partword[i+k]*div;
}
}
/* now we decode residual values for the partitions */
for(k=0;k<partitions_per_word && i<partvals;k++,i++)
if(info->stagemasks[(int)partword[i]]&(1<<s)){
codebook *stagebook=ci->book_param+
info->stagebooks[(partword[i]<<3)+s];
if(vorbis_book_decodevv_add(stagebook,in,
i*samples_per_partition+beginoff,ch,
&vd->opb,
samples_per_partition,-8)==-1)
goto eopbreak;
}
}
}
}
}
eopbreak:
return 0;
}
| 173,561 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::OnRegisterAgentError(
const ConnectErrorCallback& error_callback,
const std::string& error_name,
const std::string& error_message) {
if (--num_connecting_calls_ == 0)
adapter_->NotifyDeviceChanged(this);
DCHECK(num_connecting_calls_ >= 0);
LOG(WARNING) << object_path_.value() << ": Failed to register agent: "
<< error_name << ": " << error_message;
VLOG(1) << object_path_.value() << ": " << num_connecting_calls_
<< " still in progress";
UnregisterAgent();
ConnectErrorCode error_code = ERROR_UNKNOWN;
if (error_name == bluetooth_agent_manager::kErrorAlreadyExists)
error_code = ERROR_INPROGRESS;
RecordPairingResult(error_code);
error_callback.Run(error_code);
}
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::OnRegisterAgentError(
| 171,230 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,
int mode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *dibh;
int error;
u64 start = offset >> PAGE_CACHE_SHIFT;
unsigned int start_offset = offset & ~PAGE_CACHE_MASK;
u64 end = (offset + len - 1) >> PAGE_CACHE_SHIFT;
pgoff_t curr;
struct page *page;
unsigned int end_offset = (offset + len) & ~PAGE_CACHE_MASK;
unsigned int from, to;
if (!end_offset)
end_offset = PAGE_CACHE_SIZE;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(error))
goto out;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip, NULL);
if (unlikely(error))
goto out;
}
curr = start;
offset = start << PAGE_CACHE_SHIFT;
from = start_offset;
to = PAGE_CACHE_SIZE;
while (curr <= end) {
page = grab_cache_page_write_begin(inode->i_mapping, curr,
AOP_FLAG_NOFS);
if (unlikely(!page)) {
error = -ENOMEM;
goto out;
}
if (curr == end)
to = end_offset;
error = write_empty_blocks(page, from, to, mode);
if (!error && offset + to > inode->i_size &&
!(mode & FALLOC_FL_KEEP_SIZE)) {
i_size_write(inode, offset + to);
}
unlock_page(page);
page_cache_release(page);
if (error)
goto out;
curr++;
offset += PAGE_CACHE_SIZE;
from = 0;
}
mark_inode_dirty(inode);
brelse(dibh);
out:
return error;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119 | static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len,
int mode)
{
struct gfs2_inode *ip = GFS2_I(inode);
struct buffer_head *dibh;
int error;
unsigned int nr_blks;
sector_t lblock = offset >> inode->i_blkbits;
error = gfs2_meta_inode_buffer(ip, &dibh);
if (unlikely(error))
return error;
gfs2_trans_add_bh(ip->i_gl, dibh, 1);
if (gfs2_is_stuffed(ip)) {
error = gfs2_unstuff_dinode(ip, NULL);
if (unlikely(error))
goto out;
}
while (len) {
struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 };
bh_map.b_size = len;
set_buffer_zeronew(&bh_map);
error = gfs2_block_map(inode, lblock, &bh_map, 1);
if (unlikely(error))
goto out;
len -= bh_map.b_size;
nr_blks = bh_map.b_size >> inode->i_blkbits;
lblock += nr_blks;
if (!buffer_new(&bh_map))
continue;
if (unlikely(!buffer_zeronew(&bh_map))) {
error = -EIO;
goto out;
}
}
if (offset + len > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE))
i_size_write(inode, offset + len);
mark_inode_dirty(inode);
out:
brelse(dibh);
return error;
}
| 166,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OnImageDecoded(const gfx::Image& decoded_image) {
image_decoded_callback_.Run(decoded_image.AsBitmap());
delete this;
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | void OnImageDecoded(const gfx::Image& decoded_image) {
| 171,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));
memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));
switch (open_flags) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags)
static void nfs_set_open_stateid_locked(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode)
{
if (test_bit(NFS_DELEGATED_STATE, &state->flags) == 0)
memcpy(state->stateid.data, stateid->data, sizeof(state->stateid.data));
memcpy(state->open_stateid.data, stateid->data, sizeof(state->open_stateid.data));
switch (fmode) {
case FMODE_READ:
set_bit(NFS_O_RDONLY_STATE, &state->flags);
break;
case FMODE_WRITE:
set_bit(NFS_O_WRONLY_STATE, &state->flags);
break;
case FMODE_READ|FMODE_WRITE:
set_bit(NFS_O_RDWR_STATE, &state->flags);
}
}
| 165,706 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
struct flowi6 fl6;
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);
if (!dst)
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
opt = ireq->ipv6_opt;
if (!opt)
opt = rcu_dereference(np->opt);
if (opt) {
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (opt)
inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen +
opt->opt_flen;
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
dccp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
/* Clone pktoptions received with SYN, if we own the req */
if (*own_req && ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
return newsk;
out_overflow:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
}
Commit Message: ipv6/dccp: do not inherit ipv6_mc_list from parent
Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent")
we should clear ipv6_mc_list etc. for IPv6 sockets too.
Cc: Eric Dumazet <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Acked-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static struct sock *dccp_v6_request_recv_sock(const struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst,
struct request_sock *req_unhash,
bool *own_req)
{
struct inet_request_sock *ireq = inet_rsk(req);
struct ipv6_pinfo *newnp;
const struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt;
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst,
req_unhash, own_req);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newnp->saddr = newsk->sk_v6_rcv_saddr;
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->ipv6_mc_list = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (!dst) {
struct flowi6 fl6;
dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP);
if (!dst)
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr;
newnp->saddr = ireq->ir_v6_loc_addr;
newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr;
newsk->sk_bound_dev_if = ireq->ir_iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
newnp->ipv6_mc_list = NULL;
newnp->ipv6_ac_list = NULL;
newnp->ipv6_fl_list = NULL;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
opt = ireq->ipv6_opt;
if (!opt)
opt = rcu_dereference(np->opt);
if (opt) {
opt = ipv6_dup_options(newsk, opt);
RCU_INIT_POINTER(newnp->opt, opt);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (opt)
inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen +
opt->opt_flen;
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
inet_csk_prepare_forced_close(newsk);
dccp_done(newsk);
goto out;
}
*own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash));
/* Clone pktoptions received with SYN, if we own the req */
if (*own_req && ireq->pktopts) {
newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC);
consume_skb(ireq->pktopts);
ireq->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
return newsk;
out_overflow:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
__NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS);
return NULL;
}
| 168,127 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
Commit Message: set_interface_var() doesn't check interface name and blindly does
fopen(path "/" ifname, "w") on it. As "ifname" is an untrusted input, it
should be checked for ".." and/or "/" in it. Otherwise, an infected
unprivileged daemon may overwrite contents of file named "mtu",
"hoplimit", etc. in arbitrary location with arbitrary 32-bit value in
decimal representation ("%d"). If an attacker has a local account or
may create arbitrary symlinks with these names in any location (e.g.
/tmp), any file may be overwritten with a decimal value.
CWE ID: CWE-22 | set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
/* No path traversal */
if (strstr(name, "..") || strchr(name, '/'))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
| 166,550 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
unsigned int flags)
{
struct fuse_file *ff = file->private_data;
struct fuse_conn *fc = ff->fc;
struct fuse_ioctl_in inarg = {
.fh = ff->fh,
.cmd = cmd,
.arg = arg,
.flags = flags
};
struct fuse_ioctl_out outarg;
struct fuse_req *req = NULL;
struct page **pages = NULL;
struct page *iov_page = NULL;
struct iovec *in_iov = NULL, *out_iov = NULL;
unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
size_t in_size, out_size, transferred;
int err;
/* assume all the iovs returned by client always fits in a page */
BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
err = -ENOMEM;
pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
iov_page = alloc_page(GFP_KERNEL);
if (!pages || !iov_page)
goto out;
/*
* If restricted, initialize IO parameters as encoded in @cmd.
* RETRY from server is not allowed.
*/
if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
struct iovec *iov = page_address(iov_page);
iov->iov_base = (void __user *)arg;
iov->iov_len = _IOC_SIZE(cmd);
if (_IOC_DIR(cmd) & _IOC_WRITE) {
in_iov = iov;
in_iovs = 1;
}
if (_IOC_DIR(cmd) & _IOC_READ) {
out_iov = iov;
out_iovs = 1;
}
}
retry:
inarg.in_size = in_size = iov_length(in_iov, in_iovs);
inarg.out_size = out_size = iov_length(out_iov, out_iovs);
/*
* Out data can be used either for actual out data or iovs,
* make sure there always is at least one page.
*/
out_size = max_t(size_t, out_size, PAGE_SIZE);
max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
/* make sure there are enough buffer pages and init request with them */
err = -ENOMEM;
if (max_pages > FUSE_MAX_PAGES_PER_REQ)
goto out;
while (num_pages < max_pages) {
pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[num_pages])
goto out;
num_pages++;
}
req = fuse_get_req(fc);
if (IS_ERR(req)) {
err = PTR_ERR(req);
req = NULL;
goto out;
}
memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
req->num_pages = num_pages;
/* okay, let's send it to the client */
req->in.h.opcode = FUSE_IOCTL;
req->in.h.nodeid = ff->nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
if (in_size) {
req->in.numargs++;
req->in.args[1].size = in_size;
req->in.argpages = 1;
err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
false);
if (err)
goto out;
}
req->out.numargs = 2;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
req->out.args[1].size = out_size;
req->out.argpages = 1;
req->out.argvar = 1;
fuse_request_send(fc, req);
err = req->out.h.error;
transferred = req->out.args[1].size;
fuse_put_request(fc, req);
req = NULL;
if (err)
goto out;
/* did it ask for retry? */
if (outarg.flags & FUSE_IOCTL_RETRY) {
char *vaddr;
/* no retry if in restricted mode */
err = -EIO;
if (!(flags & FUSE_IOCTL_UNRESTRICTED))
goto out;
in_iovs = outarg.in_iovs;
out_iovs = outarg.out_iovs;
/*
* Make sure things are in boundary, separate checks
* are to protect against overflow.
*/
err = -ENOMEM;
if (in_iovs > FUSE_IOCTL_MAX_IOV ||
out_iovs > FUSE_IOCTL_MAX_IOV ||
in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
goto out;
vaddr = kmap_atomic(pages[0], KM_USER0);
err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr,
transferred, in_iovs + out_iovs,
(flags & FUSE_IOCTL_COMPAT) != 0);
kunmap_atomic(vaddr, KM_USER0);
if (err)
goto out;
in_iov = page_address(iov_page);
out_iov = in_iov + in_iovs;
goto retry;
}
err = -EIO;
if (transferred > inarg.out_size)
goto out;
err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
out:
if (req)
fuse_put_request(fc, req);
if (iov_page)
__free_page(iov_page);
while (num_pages)
__free_page(pages[--num_pages]);
kfree(pages);
return err ? err : outarg.result;
}
Commit Message: fuse: verify ioctl retries
Verify that the total length of the iovec returned in FUSE_IOCTL_RETRY
doesn't overflow iov_length().
Signed-off-by: Miklos Szeredi <[email protected]>
CC: Tejun Heo <[email protected]>
CC: <[email protected]> [2.6.31+]
CWE ID: CWE-119 | long fuse_do_ioctl(struct file *file, unsigned int cmd, unsigned long arg,
unsigned int flags)
{
struct fuse_file *ff = file->private_data;
struct fuse_conn *fc = ff->fc;
struct fuse_ioctl_in inarg = {
.fh = ff->fh,
.cmd = cmd,
.arg = arg,
.flags = flags
};
struct fuse_ioctl_out outarg;
struct fuse_req *req = NULL;
struct page **pages = NULL;
struct page *iov_page = NULL;
struct iovec *in_iov = NULL, *out_iov = NULL;
unsigned int in_iovs = 0, out_iovs = 0, num_pages = 0, max_pages;
size_t in_size, out_size, transferred;
int err;
/* assume all the iovs returned by client always fits in a page */
BUILD_BUG_ON(sizeof(struct iovec) * FUSE_IOCTL_MAX_IOV > PAGE_SIZE);
err = -ENOMEM;
pages = kzalloc(sizeof(pages[0]) * FUSE_MAX_PAGES_PER_REQ, GFP_KERNEL);
iov_page = alloc_page(GFP_KERNEL);
if (!pages || !iov_page)
goto out;
/*
* If restricted, initialize IO parameters as encoded in @cmd.
* RETRY from server is not allowed.
*/
if (!(flags & FUSE_IOCTL_UNRESTRICTED)) {
struct iovec *iov = page_address(iov_page);
iov->iov_base = (void __user *)arg;
iov->iov_len = _IOC_SIZE(cmd);
if (_IOC_DIR(cmd) & _IOC_WRITE) {
in_iov = iov;
in_iovs = 1;
}
if (_IOC_DIR(cmd) & _IOC_READ) {
out_iov = iov;
out_iovs = 1;
}
}
retry:
inarg.in_size = in_size = iov_length(in_iov, in_iovs);
inarg.out_size = out_size = iov_length(out_iov, out_iovs);
/*
* Out data can be used either for actual out data or iovs,
* make sure there always is at least one page.
*/
out_size = max_t(size_t, out_size, PAGE_SIZE);
max_pages = DIV_ROUND_UP(max(in_size, out_size), PAGE_SIZE);
/* make sure there are enough buffer pages and init request with them */
err = -ENOMEM;
if (max_pages > FUSE_MAX_PAGES_PER_REQ)
goto out;
while (num_pages < max_pages) {
pages[num_pages] = alloc_page(GFP_KERNEL | __GFP_HIGHMEM);
if (!pages[num_pages])
goto out;
num_pages++;
}
req = fuse_get_req(fc);
if (IS_ERR(req)) {
err = PTR_ERR(req);
req = NULL;
goto out;
}
memcpy(req->pages, pages, sizeof(req->pages[0]) * num_pages);
req->num_pages = num_pages;
/* okay, let's send it to the client */
req->in.h.opcode = FUSE_IOCTL;
req->in.h.nodeid = ff->nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
if (in_size) {
req->in.numargs++;
req->in.args[1].size = in_size;
req->in.argpages = 1;
err = fuse_ioctl_copy_user(pages, in_iov, in_iovs, in_size,
false);
if (err)
goto out;
}
req->out.numargs = 2;
req->out.args[0].size = sizeof(outarg);
req->out.args[0].value = &outarg;
req->out.args[1].size = out_size;
req->out.argpages = 1;
req->out.argvar = 1;
fuse_request_send(fc, req);
err = req->out.h.error;
transferred = req->out.args[1].size;
fuse_put_request(fc, req);
req = NULL;
if (err)
goto out;
/* did it ask for retry? */
if (outarg.flags & FUSE_IOCTL_RETRY) {
char *vaddr;
/* no retry if in restricted mode */
err = -EIO;
if (!(flags & FUSE_IOCTL_UNRESTRICTED))
goto out;
in_iovs = outarg.in_iovs;
out_iovs = outarg.out_iovs;
/*
* Make sure things are in boundary, separate checks
* are to protect against overflow.
*/
err = -ENOMEM;
if (in_iovs > FUSE_IOCTL_MAX_IOV ||
out_iovs > FUSE_IOCTL_MAX_IOV ||
in_iovs + out_iovs > FUSE_IOCTL_MAX_IOV)
goto out;
vaddr = kmap_atomic(pages[0], KM_USER0);
err = fuse_copy_ioctl_iovec(page_address(iov_page), vaddr,
transferred, in_iovs + out_iovs,
(flags & FUSE_IOCTL_COMPAT) != 0);
kunmap_atomic(vaddr, KM_USER0);
if (err)
goto out;
in_iov = page_address(iov_page);
out_iov = in_iov + in_iovs;
err = fuse_verify_ioctl_iov(in_iov, in_iovs);
if (err)
goto out;
err = fuse_verify_ioctl_iov(out_iov, out_iovs);
if (err)
goto out;
goto retry;
}
err = -EIO;
if (transferred > inarg.out_size)
goto out;
err = fuse_ioctl_copy_user(pages, out_iov, out_iovs, transferred, true);
out:
if (req)
fuse_put_request(fc, req);
if (iov_page)
__free_page(iov_page);
while (num_pages)
__free_page(pages[--num_pages]);
kfree(pages);
return err ? err : outarg.result;
}
| 165,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GesturePoint::IsOverMinFlickSpeed() {
return velocity_calculator_.VelocitySquared() > kMinFlickSpeedSquared;
}
Commit Message: Add setters for the aura gesture recognizer constants.
BUG=113227
TEST=none
Review URL: http://codereview.chromium.org/9372040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool GesturePoint::IsOverMinFlickSpeed() {
return velocity_calculator_.VelocitySquared() >
GestureConfiguration::min_flick_speed_squared();
}
| 171,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: authentic_set_current_files(struct sc_card *card, struct sc_path *path,
unsigned char *resp, size_t resplen, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (resplen) {
switch (resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (path)
file->path = *path;
rv = authentic_process_fci(card, file, resp, resplen);
LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error");
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path cur_df_path;
memset(&cur_df_path, 0, sizeof(cur_df_path));
if (card->cache.valid && card->cache.current_df) {
cur_df_path = card->cache.current_df->path;
sc_file_free(card->cache.current_df);
}
card->cache.current_df = NULL;
sc_file_dup(&card->cache.current_df, file);
if (cur_df_path.len) {
memcpy(card->cache.current_df->path.value + cur_df_path.len,
card->cache.current_df->path.value,
card->cache.current_df->path.len);
memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len);
card->cache.current_df->path.len += cur_df_path.len;
}
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
else {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out)
*file_out = file;
else
sc_file_free(file);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | authentic_set_current_files(struct sc_card *card, struct sc_path *path,
unsigned char *resp, size_t resplen, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
if (resplen) {
switch (resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
if (path)
file->path = *path;
rv = authentic_process_fci(card, file, resp, resplen);
LOG_TEST_RET(ctx, rv, "cannot set 'current file': FCI process error");
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
if (file->type == SC_FILE_TYPE_DF) {
struct sc_path cur_df_path;
memset(&cur_df_path, 0, sizeof(cur_df_path));
if (card->cache.valid && card->cache.current_df) {
cur_df_path = card->cache.current_df->path;
sc_file_free(card->cache.current_df);
}
card->cache.current_df = NULL;
sc_file_dup(&card->cache.current_df, file);
if (cur_df_path.len) {
if (cur_df_path.len + card->cache.current_df->path.len > sizeof card->cache.current_df->path.value
|| cur_df_path.len > sizeof card->cache.current_df->path.value)
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
memcpy(card->cache.current_df->path.value + cur_df_path.len,
card->cache.current_df->path.value,
card->cache.current_df->path.len);
memcpy(card->cache.current_df->path.value, cur_df_path.value, cur_df_path.len);
card->cache.current_df->path.len += cur_df_path.len;
}
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
else {
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out)
*file_out = file;
else
sc_file_free(file);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
| 169,049 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _prolog_error(batch_job_launch_msg_t *req, int rc)
{
char *err_name_ptr, err_name[256], path_name[MAXPATHLEN];
char *fmt_char;
int fd;
if (req->std_err || req->std_out) {
if (req->std_err)
strncpy(err_name, req->std_err, sizeof(err_name));
else
strncpy(err_name, req->std_out, sizeof(err_name));
if ((fmt_char = strchr(err_name, (int) '%')) &&
(fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) {
char tmp_name[256];
fmt_char[1] = 'u';
snprintf(tmp_name, sizeof(tmp_name), err_name,
req->job_id);
strncpy(err_name, tmp_name, sizeof(err_name));
}
} else {
snprintf(err_name, sizeof(err_name), "slurm-%u.out",
req->job_id);
}
err_name_ptr = err_name;
if (err_name_ptr[0] == '/')
snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr);
else if (req->work_dir)
snprintf(path_name, MAXPATHLEN, "%s/%s",
req->work_dir, err_name_ptr);
else
snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr);
if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) {
error("Unable to open %s: %s", path_name,
slurm_strerror(errno));
return;
}
snprintf(err_name, sizeof(err_name),
"Error running slurm prolog: %d\n", WEXITSTATUS(rc));
safe_write(fd, err_name, strlen(err_name));
if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) {
snprintf(err_name, sizeof(err_name),
"Couldn't change fd owner to %u:%u: %m\n",
req->uid, req->gid);
}
rwfail:
close(fd);
}
Commit Message: Fix security issue in _prolog_error().
Fix security issue caused by insecure file path handling triggered by
the failure of a Prolog script. To exploit this a user needs to
anticipate or cause the Prolog to fail for their job.
(This commit is slightly different from the fix to the 15.08 branch.)
CVE-2016-10030.
CWE ID: CWE-284 | _prolog_error(batch_job_launch_msg_t *req, int rc)
{
char *err_name_ptr, err_name[256], path_name[MAXPATHLEN];
char *fmt_char;
int fd;
if (req->std_err || req->std_out) {
if (req->std_err)
strncpy(err_name, req->std_err, sizeof(err_name));
else
strncpy(err_name, req->std_out, sizeof(err_name));
if ((fmt_char = strchr(err_name, (int) '%')) &&
(fmt_char[1] == 'j') && !strchr(fmt_char+1, (int) '%')) {
char tmp_name[256];
fmt_char[1] = 'u';
snprintf(tmp_name, sizeof(tmp_name), err_name,
req->job_id);
strncpy(err_name, tmp_name, sizeof(err_name));
}
} else {
snprintf(err_name, sizeof(err_name), "slurm-%u.out",
req->job_id);
}
err_name_ptr = err_name;
if (err_name_ptr[0] == '/')
snprintf(path_name, MAXPATHLEN, "%s", err_name_ptr);
else if (req->work_dir)
snprintf(path_name, MAXPATHLEN, "%s/%s",
req->work_dir, err_name_ptr);
else
snprintf(path_name, MAXPATHLEN, "/%s", err_name_ptr);
if ((fd = _open_as_other(path_name, req)) == -1) {
error("Unable to open %s: Permission denied", path_name);
return;
}
snprintf(err_name, sizeof(err_name),
"Error running slurm prolog: %d\n", WEXITSTATUS(rc));
safe_write(fd, err_name, strlen(err_name));
if (fchown(fd, (uid_t) req->uid, (gid_t) req->gid) == -1) {
snprintf(err_name, sizeof(err_name),
"Couldn't change fd owner to %u:%u: %m\n",
req->uid, req->gid);
}
rwfail:
close(fd);
}
| 168,646 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (0 == plen) {
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[1], (plen + 7) / 8);
memcpy(&route_target, &pptr[1], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)),
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
Commit Message: CVE-2017-13053/BGP: fix VPN route target bounds checks
decode_rt_routing_info() didn't check bounds before fetching 4 octets of
the origin AS field and could over-read the input buffer, put it right.
It also fetched the varying number of octets of the route target field
from 4 octets lower than the correct offset, put it right.
It also used the same temporary buffer explicitly through as_printf()
and implicitly through bgp_vpn_rd_print() so the end result of snprintf()
was not what was originally intended.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
| 167,820 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 EC_GROUP_clear_free(EC_GROUP *group)
{
if (!group) return;
if (group->meth->group_clear_finish != 0)
group->meth->group_clear_finish(group);
else if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_POINT_clear_free(group->generator);
BN_clear_free(&group->order);
OPENSSL_cleanse(group, sizeof *group);
OPENSSL_free(group);
}
Commit Message:
CWE ID: CWE-320 | void EC_GROUP_clear_free(EC_GROUP *group)
{
if (!group) return;
if (group->meth->group_clear_finish != 0)
group->meth->group_clear_finish(group);
else if (group->meth->group_finish != 0)
group->meth->group_finish(group);
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->generator != NULL)
EC_EX_DATA_clear_free_all_data(&group->extra_data);
if (group->mont_data)
BN_MONT_CTX_free(group->mont_data);
if (group->generator != NULL)
EC_POINT_clear_free(group->generator);
BN_clear_free(&group->order);
OPENSSL_cleanse(group, sizeof *group);
OPENSSL_free(group);
}
| 165,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: int socket_create(uint16_t port)
{
int sfd = -1;
int yes = 1;
#ifdef WIN32
WSADATA wsa_data;
if (!wsa_init) {
if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
fprintf(stderr, "WSAStartup failed!\n");
ExitProcess(-1);
}
wsa_init = 1;
}
#endif
struct sockaddr_in saddr;
if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
perror("socket()");
return -1;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
memset((void *) &saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);
if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) {
perror("bind()");
socket_close(sfd);
return -1;
}
if (listen(sfd, 1) == -1) {
perror("listen()");
socket_close(sfd);
return -1;
}
return sfd;
}
Commit Message: common: [security fix] Make sure sockets only listen locally
CWE ID: CWE-284 | int socket_create(uint16_t port)
{
int sfd = -1;
int yes = 1;
#ifdef WIN32
WSADATA wsa_data;
if (!wsa_init) {
if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) {
fprintf(stderr, "WSAStartup failed!\n");
ExitProcess(-1);
}
wsa_init = 1;
}
#endif
struct sockaddr_in saddr;
if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) {
perror("socket()");
return -1;
}
if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#ifdef SO_NOSIGPIPE
if (setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&yes, sizeof(int)) == -1) {
perror("setsockopt()");
socket_close(sfd);
return -1;
}
#endif
memset((void *) &saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
saddr.sin_port = htons(port);
if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) {
perror("bind()");
socket_close(sfd);
return -1;
}
if (listen(sfd, 1) == -1) {
perror("listen()");
socket_close(sfd);
return -1;
}
return sfd;
}
| 169,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool tailmatch(const char *little, const char *bigone)
{
size_t littlelen = strlen(little);
size_t biglen = strlen(bigone);
if(littlelen > biglen)
return FALSE;
return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE;
}
Commit Message: cookie: fix tailmatching to prevent cross-domain leakage
Cookies set for 'example.com' could accidentaly also be sent by libcurl
to the 'bexample.com' (ie with a prefix to the first domain name).
This is a security vulnerabilty, CVE-2013-1944.
Bug: http://curl.haxx.se/docs/adv_20130412.html
CWE ID: CWE-200 | static bool tailmatch(const char *little, const char *bigone)
static bool tailmatch(const char *cooke_domain, const char *hostname)
{
size_t cookie_domain_len = strlen(cooke_domain);
size_t hostname_len = strlen(hostname);
if(hostname_len < cookie_domain_len)
return FALSE;
if(!Curl_raw_equal(cooke_domain, hostname+hostname_len-cookie_domain_len))
return FALSE;
/* A lead char of cookie_domain is not '.'.
RFC6265 4.1.2.3. The Domain Attribute says:
For example, if the value of the Domain attribute is
"example.com", the user agent will include the cookie in the Cookie
header when making HTTP requests to example.com, www.example.com, and
www.corp.example.com.
*/
if(hostname_len == cookie_domain_len)
return TRUE;
if('.' == *(hostname + hostname_len - cookie_domain_len - 1))
return TRUE;
return FALSE;
}
| 166,098 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_write_start_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
png_size_t buf_size;
png_debug(1, "in png_write_start_row");
buf_size = (png_size_t)(PNG_ROWBYTES(
png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
/* Set up row buffer */
png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)buf_size);
png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
#ifdef PNG_WRITE_FILTER_SUPPORTED
/* Set up filtering buffer, if using this filter */
if (png_ptr->do_filter & PNG_FILTER_SUB)
{
png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
}
/* We only need to keep the previous row if we are using one of these. */
if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
{
/* Set up previous row buffer */
png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
(png_uint_32)buf_size);
if (png_ptr->do_filter & PNG_FILTER_UP)
{
png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
}
if (png_ptr->do_filter & PNG_FILTER_AVG)
{
png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
}
if (png_ptr->do_filter & PNG_FILTER_PAETH)
{
png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
}
}
#endif /* PNG_WRITE_FILTER_SUPPORTED */
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, we need to set up width and height of pass */
if (png_ptr->interlaced)
{
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
png_pass_ystart[0]) / png_pass_yinc[0];
png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
png_pass_start[0]) / png_pass_inc[0];
}
else
{
png_ptr->num_rows = png_ptr->height;
png_ptr->usr_width = png_ptr->width;
}
}
else
#endif
{
png_ptr->num_rows = png_ptr->height;
png_ptr->usr_width = png_ptr->width;
}
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_write_start_row(png_structp png_ptr)
{
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
#ifndef PNG_USE_GLOBAL_ARRAYS
/* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */
/* Start of interlace block */
int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
/* Offset to next interlace block */
int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
/* Start of interlace block in the y direction */
int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
/* Offset to next interlace block in the y direction */
int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
#endif
#endif
png_size_t buf_size;
png_debug(1, "in png_write_start_row");
buf_size = (png_size_t)(PNG_ROWBYTES(
png_ptr->usr_channels*png_ptr->usr_bit_depth, png_ptr->width) + 1);
/* Set up row buffer */
png_ptr->row_buf = (png_bytep)png_malloc(png_ptr,
(png_uint_32)buf_size);
png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
#ifdef PNG_WRITE_FILTER_SUPPORTED
/* Set up filtering buffer, if using this filter */
if (png_ptr->do_filter & PNG_FILTER_SUB)
{
png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
}
/* We only need to keep the previous row if we are using one of these. */
if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
{
/* Set up previous row buffer */
png_ptr->prev_row = (png_bytep)png_calloc(png_ptr,
(png_uint_32)buf_size);
if (png_ptr->do_filter & PNG_FILTER_UP)
{
png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
}
if (png_ptr->do_filter & PNG_FILTER_AVG)
{
png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
}
if (png_ptr->do_filter & PNG_FILTER_PAETH)
{
png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
(png_uint_32)(png_ptr->rowbytes + 1));
png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
}
}
#endif /* PNG_WRITE_FILTER_SUPPORTED */
#ifdef PNG_WRITE_INTERLACING_SUPPORTED
/* If interlaced, we need to set up width and height of pass */
if (png_ptr->interlaced)
{
if (!(png_ptr->transformations & PNG_INTERLACE))
{
png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
png_pass_ystart[0]) / png_pass_yinc[0];
png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
png_pass_start[0]) / png_pass_inc[0];
}
else
{
png_ptr->num_rows = png_ptr->height;
png_ptr->usr_width = png_ptr->width;
}
}
else
#endif
{
png_ptr->num_rows = png_ptr->height;
png_ptr->usr_width = png_ptr->width;
}
png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
png_ptr->zstream.next_out = png_ptr->zbuf;
}
| 172,196 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: setkey_principal_2_svc(setkey_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name,
service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_SETKEY, arg->princ, NULL)) {
ret.code = kadm5_setkey_principal((void *)handle, arg->princ,
arg->keyblocks, arg->n_keys);
} else {
log_unauth("kadm5_setkey_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_SETKEY;
}
if(ret.code != KADM5_AUTH_SETKEY) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_setkey_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | setkey_principal_2_svc(setkey_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (!(CHANGEPW_SERVICE(rqstp)) &&
kadm5int_acl_check(handle->context, rqst2name(rqstp),
ACL_SETKEY, arg->princ, NULL)) {
ret.code = kadm5_setkey_principal((void *)handle, arg->princ,
arg->keyblocks, arg->n_keys);
} else {
log_unauth("kadm5_setkey_principal", prime_arg,
&client_name, &service_name, rqstp);
ret.code = KADM5_AUTH_SETKEY;
}
if(ret.code != KADM5_AUTH_SETKEY) {
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_setkey_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 utf32_to_utf8(const char32_t* src, size_t src_len, char* dst)
{
if (src == NULL || src_len == 0 || dst == NULL) {
return;
}
const char32_t *cur_utf32 = src;
const char32_t *end_utf32 = src + src_len;
char *cur = dst;
while (cur_utf32 < end_utf32) {
size_t len = utf32_codepoint_utf8_length(*cur_utf32);
utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len);
cur += len;
}
*cur = '\0';
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119 | void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst)
void utf32_to_utf8(const char32_t* src, size_t src_len, char* dst, size_t dst_len)
{
if (src == NULL || src_len == 0 || dst == NULL) {
return;
}
const char32_t *cur_utf32 = src;
const char32_t *end_utf32 = src + src_len;
char *cur = dst;
while (cur_utf32 < end_utf32) {
size_t len = utf32_codepoint_utf8_length(*cur_utf32);
LOG_ALWAYS_FATAL_IF(dst_len < len, "%zu < %zu", dst_len, len);
utf32_codepoint_to_utf8((uint8_t *)cur, *cur_utf32++, len);
cur += len;
dst_len -= len;
}
LOG_ALWAYS_FATAL_IF(dst_len < 1, "dst_len < 1: %zu < 1", dst_len);
*cur = '\0';
}
| 173,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 ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
{
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
}
/* Copy overread bytes from last frame into buffer. */
for(; pc->overread>0; pc->overread--){
pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
}
/* flush remaining if EOF */
if(!*buf_size && next == END_NOT_FOUND){
next= 0;
}
pc->last_index= pc->index;
/* copy into buffer end return */
if(next == END_NOT_FOUND){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer)
return AVERROR(ENOMEM);
pc->buffer = new_buffer;
memcpy(&pc->buffer[pc->index], *buf, *buf_size);
pc->index += *buf_size;
return -1;
}
*buf_size=
pc->overread_index= pc->index + next;
/* append to buffer */
if(pc->index){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer)
return AVERROR(ENOMEM);
pc->buffer = new_buffer;
if (next > -FF_INPUT_BUFFER_PADDING_SIZE)
memcpy(&pc->buffer[pc->index], *buf,
next + FF_INPUT_BUFFER_PADDING_SIZE);
pc->index = 0;
*buf= pc->buffer;
}
/* store overread bytes */
for(;next < 0; next++){
pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];
pc->overread++;
}
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
}
return 0;
}
Commit Message: avcodec/parser: reset indexes on realloc failure
Fixes Ticket2982
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size)
{
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]);
}
/* Copy overread bytes from last frame into buffer. */
for(; pc->overread>0; pc->overread--){
pc->buffer[pc->index++]= pc->buffer[pc->overread_index++];
}
/* flush remaining if EOF */
if(!*buf_size && next == END_NOT_FOUND){
next= 0;
}
pc->last_index= pc->index;
/* copy into buffer end return */
if(next == END_NOT_FOUND){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer) {
pc->index = 0;
return AVERROR(ENOMEM);
}
pc->buffer = new_buffer;
memcpy(&pc->buffer[pc->index], *buf, *buf_size);
pc->index += *buf_size;
return -1;
}
*buf_size=
pc->overread_index= pc->index + next;
/* append to buffer */
if(pc->index){
void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE);
if(!new_buffer) {
pc->overread_index =
pc->index = 0;
return AVERROR(ENOMEM);
}
pc->buffer = new_buffer;
if (next > -FF_INPUT_BUFFER_PADDING_SIZE)
memcpy(&pc->buffer[pc->index], *buf,
next + FF_INPUT_BUFFER_PADDING_SIZE);
pc->index = 0;
*buf= pc->buffer;
}
/* store overread bytes */
for(;next < 0; next++){
pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next];
pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next];
pc->overread++;
}
if(pc->overread){
av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n",
pc->overread, pc->state, next, pc->index, pc->overread_index);
av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]);
}
return 0;
}
| 165,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XRRGetMonitors(Display *dpy, Window window, Bool get_active, int *nmonitors)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetMonitorsReply rep;
xRRGetMonitorsReq *req;
int nbytes, nbytesRead, rbytes;
int nmon, noutput;
int m, o;
char *buf, *buf_head;
xRRMonitorInfo *xmon;
CARD32 *xoutput;
XRRMonitorInfo *mon = NULL;
RROutput *output;
RRCheckExtension (dpy, info, NULL);
*nmonitors = -1;
LockDisplay (dpy);
GetReq (RRGetMonitors, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetMonitors;
req->window = window;
req->get_active = get_active;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
nbytes = (long) rep.length << 2;
nmon = rep.nmonitors;
noutput = rep.noutputs;
rbytes = nmon * sizeof (XRRMonitorInfo) + noutput * sizeof(RROutput);
buf = buf_head = Xmalloc (nbytesRead);
mon = Xmalloc (rbytes);
if (buf == NULL || mon == NULL) {
Xfree(buf);
Xfree(mon);
_XEatDataWords (dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
_XReadPad(dpy, buf, nbytesRead);
output = (RROutput *) (mon + nmon);
for (m = 0; m < nmon; m++) {
xmon = (xRRMonitorInfo *) buf;
mon[m].name = xmon->name;
mon[m].primary = xmon->primary;
mon[m].automatic = xmon->automatic;
mon[m].noutput = xmon->noutput;
mon[m].x = xmon->x;
mon[m].y = xmon->y;
mon[m].width = xmon->width;
mon[m].height = xmon->height;
mon[m].mwidth = xmon->widthInMillimeters;
mon[m].mheight = xmon->heightInMillimeters;
mon[m].outputs = output;
buf += SIZEOF (xRRMonitorInfo);
xoutput = (CARD32 *) buf;
for (o = 0; o < xmon->noutput; o++)
output[o] = xoutput[o];
output += xmon->noutput;
buf += xmon->noutput * 4;
}
Xfree(buf_head);
}
Commit Message:
CWE ID: CWE-787 | XRRGetMonitors(Display *dpy, Window window, Bool get_active, int *nmonitors)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetMonitorsReply rep;
xRRGetMonitorsReq *req;
int nbytes, nbytesRead, rbytes;
int nmon, noutput;
int m, o;
char *buf, *buf_head;
xRRMonitorInfo *xmon;
CARD32 *xoutput;
XRRMonitorInfo *mon = NULL;
RROutput *output;
RRCheckExtension (dpy, info, NULL);
*nmonitors = -1;
LockDisplay (dpy);
GetReq (RRGetMonitors, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetMonitors;
req->window = window;
req->get_active = get_active;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
{
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
return NULL;
}
if (rep.length > INT_MAX >> 2 ||
rep.nmonitors > INT_MAX / SIZEOF(xRRMonitorInfo) ||
rep.noutputs > INT_MAX / 4 ||
rep.nmonitors * SIZEOF(xRRMonitorInfo) > INT_MAX - rep.noutputs * 4) {
_XEatData (dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
nbytes = (long) rep.length << 2;
nmon = rep.nmonitors;
noutput = rep.noutputs;
rbytes = nmon * sizeof (XRRMonitorInfo) + noutput * sizeof(RROutput);
buf = buf_head = Xmalloc (nbytesRead);
mon = Xmalloc (rbytes);
if (buf == NULL || mon == NULL) {
Xfree(buf);
Xfree(mon);
_XEatDataWords (dpy, rep.length);
UnlockDisplay (dpy);
SyncHandle ();
return NULL;
}
_XReadPad(dpy, buf, nbytesRead);
output = (RROutput *) (mon + nmon);
for (m = 0; m < nmon; m++) {
xmon = (xRRMonitorInfo *) buf;
mon[m].name = xmon->name;
mon[m].primary = xmon->primary;
mon[m].automatic = xmon->automatic;
mon[m].noutput = xmon->noutput;
mon[m].x = xmon->x;
mon[m].y = xmon->y;
mon[m].width = xmon->width;
mon[m].height = xmon->height;
mon[m].mwidth = xmon->widthInMillimeters;
mon[m].mheight = xmon->heightInMillimeters;
mon[m].outputs = output;
buf += SIZEOF (xRRMonitorInfo);
xoutput = (CARD32 *) buf;
for (o = 0; o < xmon->noutput; o++)
output[o] = xoutput[o];
output += xmon->noutput;
buf += xmon->noutput * 4;
}
Xfree(buf_head);
}
| 164,914 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int check_sticky(struct inode *dir, struct inode *inode)
{
kuid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (uid_eq(inode->i_uid, fsuid))
return 0;
if (uid_eq(dir->i_uid, fsuid))
return 0;
return !inode_capable(inode, CAP_FOWNER);
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | static inline int check_sticky(struct inode *dir, struct inode *inode)
{
kuid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (uid_eq(inode->i_uid, fsuid))
return 0;
if (uid_eq(dir->i_uid, fsuid))
return 0;
return !capable_wrt_inode_uidgid(inode, CAP_FOWNER);
}
| 166,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
old_cs = get_segment_selector(ctxt, VCPU_SREG_CS);
old_eip = ctxt->_eip;
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
if (load_segment_descriptor(ctxt, sel, VCPU_SREG_CS))
return X86EMUL_CONTINUE;
ctxt->_eip = 0;
memcpy(&ctxt->_eip, ctxt->src.valptr, ctxt->op_bytes);
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
return rc;
ctxt->src.val = old_eip;
return em_push(ctxt);
}
Commit Message: KVM: x86: Handle errors when RIP is set during far jumps
Far jmp/call/ret may fault while loading a new RIP. Currently KVM does not
handle this case, and may result in failed vm-entry once the assignment is
done. The tricky part of doing so is that loading the new CS affects the
VMCS/VMCB state, so if we fail during loading the new RIP, we are left in
unconsistent state. Therefore, this patch saves on 64-bit the old CS
descriptor and restores it if loading RIP failed.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_call_far(struct x86_emulate_ctxt *ctxt)
{
u16 sel, old_cs;
ulong old_eip;
int rc;
struct desc_struct old_desc, new_desc;
const struct x86_emulate_ops *ops = ctxt->ops;
int cpl = ctxt->ops->cpl(ctxt);
old_eip = ctxt->_eip;
ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS);
memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2);
rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false,
&new_desc);
if (rc != X86EMUL_CONTINUE)
return X86EMUL_CONTINUE;
rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_cs;
rc = em_push(ctxt);
if (rc != X86EMUL_CONTINUE)
goto fail;
ctxt->src.val = old_eip;
rc = em_push(ctxt);
/* If we failed, we tainted the memory, but the very least we should
restore cs */
if (rc != X86EMUL_CONTINUE)
goto fail;
return rc;
fail:
ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS);
return rc;
}
| 166,338 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintWebViewHelper::CheckForCancel() {
bool cancel = false;
Send(new PrintHostMsg_CheckForCancel(
routing_id(),
print_pages_params_->params.preview_ui_addr,
print_pages_params_->params.preview_request_id,
&cancel));
if (cancel)
notify_browser_of_print_failure_ = false;
return cancel;
}
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 | bool PrintWebViewHelper::CheckForCancel() {
const PrintMsg_Print_Params& print_params = print_pages_params_->params;
bool cancel = false;
Send(new PrintHostMsg_CheckForCancel(routing_id(),
print_params.preview_ui_id,
print_params.preview_request_id,
&cancel));
if (cancel)
notify_browser_of_print_failure_ = false;
return cancel;
}
| 170,856 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 NetworkHandler::ClearBrowserCache(
std::unique_ptr<ClearBrowserCacheCallback> callback) {
if (!process_) {
callback->sendFailure(Response::InternalError());
return;
}
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(
process_->GetBrowserContext());
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
new DevtoolsClearCacheObserver(remover, std::move(callback)));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20 | void NetworkHandler::ClearBrowserCache(
std::unique_ptr<ClearBrowserCacheCallback> callback) {
if (!browser_context_) {
callback->sendFailure(Response::InternalError());
return;
}
content::BrowsingDataRemover* remover =
content::BrowserContext::GetBrowsingDataRemover(browser_context_);
remover->RemoveAndReply(
base::Time(), base::Time::Max(),
content::BrowsingDataRemover::DATA_TYPE_CACHE,
content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB,
new DevtoolsClearCacheObserver(remover, std::move(callback)));
}
| 172,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Compositor::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {
}
Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor
Bug: 893850
Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43
Reviewed-on: https://chromium-review.googlesource.com/c/1293712
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Saman Sami <[email protected]>
Cr-Commit-Position: refs/heads/master@{#601629}
CWE ID: CWE-20 | void Compositor::OnFirstSurfaceActivation(
const viz::SurfaceInfo& surface_info) {
NOTREACHED();
}
| 172,563 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
WritePixel(i, &context, casspecial); npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
Commit Message: fix "pixel overrun"
fixes #3
CWE ID: CWE-119 | static int DecodeGifImg(struct ngiflib_img * i) {
struct ngiflib_decode_context context;
long npix;
u8 * stackp;
u8 * stack_top;
u16 clr;
u16 eof;
u16 free;
u16 act_code = 0;
u16 old_code = 0;
u16 read_byt;
u16 ab_prfx[4096];
u8 ab_suffx[4096];
u8 ab_stack[4096];
u8 flags;
u8 casspecial = 0;
if(!i) return -1;
i->posX = GetWord(i->parent); /* offsetX */
i->posY = GetWord(i->parent); /* offsetY */
i->width = GetWord(i->parent); /* SizeX */
i->height = GetWord(i->parent); /* SizeY */
if((i->width > i->parent->width) || (i->height > i->parent->height)) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** ERROR *** Image bigger than global GIF canvas !\n");
#endif
return -1;
}
if((i->posX + i->width) > i->parent->width) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting X position\n");
#endif
i->posX = i->parent->width - i->width;
}
if((i->posY + i->height) > i->parent->height) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent->log) fprintf(i->parent->log, "*** WARNING *** Adjusting Y position\n");
#endif
i->posY = i->parent->height - i->height;
}
context.Xtogo = i->width;
context.curY = i->posY;
#ifdef NGIFLIB_INDEXED_ONLY
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#else
if(i->parent->mode & NGIFLIB_MODE_INDEXED) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width;
context.frbuff_p.p8 = context.line_p.p8 + i->posX;
#else
context.frbuff_p.p8 = i->parent->frbuff.p8 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context.line_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width;
context.frbuff_p.p32 = context.line_p.p32 + i->posX;
#else
context.frbuff_p.p32 = i->parent->frbuff.p32 + (u32)i->posY*i->parent->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
npix = (long)i->width * i->height;
flags = GetByte(i->parent);
i->interlaced = (flags & 64) >> 6;
context.pass = i->interlaced ? 1 : 0;
i->sort_flag = (flags & 32) >> 5; /* is local palette sorted by color frequency ? */
i->localpalbits = (flags & 7) + 1;
if(flags&128) { /* palette locale */
int k;
int localpalsize = 1 << i->localpalbits;
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Local palette\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
i->palette = (struct ngiflib_rgb *)ngiflib_malloc(sizeof(struct ngiflib_rgb)*localpalsize);
for(k=0; k<localpalsize; k++) {
i->palette[k].r = GetByte(i->parent);
i->palette[k].g = GetByte(i->parent);
i->palette[k].b = GetByte(i->parent);
}
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(i->parent->palette_cb) i->parent->palette_cb(i->parent, i->palette, localpalsize);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
} else {
i->palette = i->parent->palette;
i->localpalbits = i->parent->imgbits;
}
i->ncolors = 1 << i->localpalbits;
i->imgbits = GetByte(i->parent); /* LZW Minimum Code Size */
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) {
if(i->interlaced) fprintf(i->parent->log, "interlaced ");
fprintf(i->parent->log, "img pos(%hu,%hu) size %hux%hu palbits=%hhu imgbits=%hhu ncolors=%hu\n",
i->posX, i->posY, i->width, i->height, i->localpalbits, i->imgbits, i->ncolors);
}
#endif /* !defined(NGIFLIB_NO_FILE) */
if(i->imgbits==1) { /* fix for 1bit images ? */
i->imgbits = 2;
}
clr = 1 << i->imgbits;
eof = clr + 1;
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
stackp = stack_top = ab_stack + 4096;
context.restbits = 0; /* initialise le "buffer" de lecture */
context.restbyte = 0; /* des codes LZW */
context.lbyte = 0;
for(;;) {
act_code = GetGifWord(i, &context);
if(act_code==eof) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "End of image code\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 0;
}
if(npix==0) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "assez de pixels, On se casse !\n");
#endif /* !defined(NGIFLIB_NO_FILE) */
return 1;
}
if(act_code==clr) {
#if !defined(NGIFLIB_NO_FILE)
if(i->parent && i->parent->log) fprintf(i->parent->log, "Code clear (free=%hu) npix=%ld\n", free, npix);
#endif /* !defined(NGIFLIB_NO_FILE) */
/* clear */
free = clr + 2;
context.nbbit = i->imgbits + 1;
context.max = clr + clr - 1; /* (1 << context.nbbit) - 1 */
act_code = GetGifWord(i, &context);
casspecial = (u8)act_code;
old_code = act_code;
if(npix > 0) WritePixel(i, &context, casspecial);
npix--;
} else {
read_byt = act_code;
if(act_code >= free) { /* code pas encore dans alphabet */
/* printf("Code pas dans alphabet : %d>=%d push %d\n", act_code, free, casspecial); */
*(--stackp) = casspecial; /* dernier debut de chaine ! */
act_code = old_code;
}
/* printf("actcode=%d\n", act_code); */
while(act_code > clr) { /* code non concret */
/* fillstackloop empile les suffixes ! */
*(--stackp) = ab_suffx[act_code];
act_code = ab_prfx[act_code]; /* prefixe */
}
/* act_code est concret */
casspecial = (u8)act_code; /* dernier debut de chaine ! */
*(--stackp) = casspecial; /* push on stack */
if(npix >= (stack_top - stackp)) {
WritePixels(i, &context, stackp, stack_top - stackp); /* unstack all pixels at once */
} else if(npix > 0) { /* "pixel overflow" */
WritePixels(i, &context, stackp, npix);
}
npix -= (stack_top - stackp);
stackp = stack_top;
/* putchar('\n'); */
if(free < 4096) { /* la taille du dico est 4096 max ! */
ab_prfx[free] = old_code;
ab_suffx[free] = (u8)act_code;
free++;
if((free > context.max) && (context.nbbit < 12)) {
context.nbbit++; /* 1 bit de plus pour les codes LZW */
context.max += context.max + 1;
}
}
old_code = read_byt;
}
}
return 0;
}
| 169,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: int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
Commit Message: Fix potential SQL Injection with postgis TIME filters (#4834)
CWE ID: CWE-89 | int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
if( strchr(timestring,'\'') || strchr(timestring, '\\') ) {
msSetError(MS_MISCERR, "Invalid time filter.", "msPostGISLayerSetTimeFilter()");
return MS_FALSE;
}
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
| 166,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type()))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
OnRobustJPEGDecodeImage)
#endif // defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff,
OnPatchFileBsdiff)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette,
OnPatchFileCourgette)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
#if defined(FULL_SAFE_BROWSING)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
OnAnalyzeZipFileForDownloadProtection)
#endif
#if defined(ENABLE_EXTENSIONS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
OnParseMediaMetadata)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
for (Handlers::iterator it = handlers_.begin();
!handled && it != handlers_.end(); ++it) {
handled = (*it)->OnMessageReceived(message);
}
return handled;
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | bool ChromeContentUtilityClient::OnMessageReceived(
const IPC::Message& message) {
if (filter_messages_ && !ContainsKey(message_id_whitelist_, message.type()))
return false;
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ChromeContentUtilityClient, message)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_DecodeImage, OnDecodeImage)
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RobustJPEGDecodeImage,
OnRobustJPEGDecodeImage)
#endif // defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileBsdiff,
OnPatchFileBsdiff)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_PatchFileCourgette,
OnPatchFileCourgette)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing)
#if defined(FULL_SAFE_BROWSING)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeZipFileForDownloadProtection,
OnAnalyzeZipFileForDownloadProtection)
#if defined(OS_MACOSX)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_AnalyzeDmgFileForDownloadProtection,
OnAnalyzeDmgFileForDownloadProtection)
#endif
#endif
#if defined(ENABLE_EXTENSIONS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_ParseMediaMetadata,
OnParseMediaMetadata)
#endif
#if defined(OS_CHROMEOS)
IPC_MESSAGE_HANDLER(ChromeUtilityMsg_CreateZipFile, OnCreateZipFile)
#endif
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
for (Handlers::iterator it = handlers_.begin();
!handled && it != handlers_.end(); ++it) {
handled = (*it)->OnMessageReceived(message);
}
return handled;
}
| 171,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: std::string SanitizeFrontendPath(const std::string& path) {
for (size_t i = 0; i < path.length(); i++) {
if (path[i] != '/' && path[i] != '-' && path[i] != '_'
&& path[i] != '.' && path[i] != '@'
&& !(path[i] >= '0' && path[i] <= '9')
&& !(path[i] >= 'a' && path[i] <= 'z')
&& !(path[i] >= 'A' && path[i] <= 'Z')) {
return std::string();
}
}
return path;
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | std::string SanitizeFrontendPath(const std::string& path) {
| 172,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
{
struct iphdr *iph;
int room;
struct icmp_bxm icmp_param;
struct rtable *rt = skb_rtable(skb_in);
struct ipcm_cookie ipc;
__be32 saddr;
u8 tos;
struct net *net;
struct sock *sk;
if (!rt)
goto out;
net = dev_net(rt->dst.dev);
/*
* Find the original header. It is expected to be valid, of course.
* Check this, icmp_send is called from the most obscure devices
* sometimes.
*/
iph = ip_hdr(skb_in);
if ((u8 *)iph < skb_in->head ||
(skb_in->network_header + sizeof(*iph)) > skb_in->tail)
goto out;
/*
* No replies to physical multicast/broadcast
*/
if (skb_in->pkt_type != PACKET_HOST)
goto out;
/*
* Now check at the protocol level
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto out;
/*
* Only reply to fragment 0. We byte re-order the constant
* mask for efficiency.
*/
if (iph->frag_off & htons(IP_OFFSET))
goto out;
/*
* If we send an ICMP error to an ICMP error a mess would result..
*/
if (icmp_pointers[type].error) {
/*
* We are an error, check if we are replying to an
* ICMP error
*/
if (iph->protocol == IPPROTO_ICMP) {
u8 _inner_type, *itp;
itp = skb_header_pointer(skb_in,
skb_network_header(skb_in) +
(iph->ihl << 2) +
offsetof(struct icmphdr,
type) -
skb_in->data,
sizeof(_inner_type),
&_inner_type);
if (itp == NULL)
goto out;
/*
* Assume any unknown ICMP type is an error. This
* isn't specified by the RFC, but think about it..
*/
if (*itp > NR_ICMP_TYPES ||
icmp_pointers[*itp].error)
goto out;
}
}
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
/*
* Construct source address and options.
*/
saddr = iph->daddr;
if (!(rt->rt_flags & RTCF_LOCAL)) {
struct net_device *dev = NULL;
rcu_read_lock();
if (rt_is_input_route(rt) &&
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
dev = dev_get_by_index_rcu(net, rt->rt_iif);
if (dev)
saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
else
saddr = 0;
rcu_read_unlock();
}
tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
IPTOS_PREC_INTERNETCONTROL) :
iph->tos;
if (ip_options_echo(&icmp_param.replyopts, skb_in))
goto out_unlock;
/*
* Prepare data for ICMP header.
*/
icmp_param.data.icmph.type = type;
icmp_param.data.icmph.code = code;
icmp_param.data.icmph.un.gateway = info;
icmp_param.data.icmph.checksum = 0;
icmp_param.skb = skb_in;
icmp_param.offset = skb_network_offset(skb_in);
inet_sk(sk)->tos = tos;
ipc.addr = iph->saddr;
ipc.opt = &icmp_param.replyopts;
ipc.tx_flags = 0;
rt = icmp_route_lookup(net, skb_in, iph, saddr, tos,
type, code, &icmp_param);
if (IS_ERR(rt))
goto out_unlock;
if (!icmpv4_xrlim_allow(net, rt, type, code))
goto ende;
/* RFC says return as much as we can without exceeding 576 bytes. */
room = dst_mtu(&rt->dst);
if (room > 576)
room = 576;
room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen;
room -= sizeof(struct icmphdr);
icmp_param.data_len = skb_in->len - icmp_param.offset;
if (icmp_param.data_len > room)
icmp_param.data_len = room;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_push_reply(&icmp_param, &ipc, &rt);
ende:
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
out:;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
{
struct iphdr *iph;
int room;
struct icmp_bxm icmp_param;
struct rtable *rt = skb_rtable(skb_in);
struct ipcm_cookie ipc;
__be32 saddr;
u8 tos;
struct net *net;
struct sock *sk;
if (!rt)
goto out;
net = dev_net(rt->dst.dev);
/*
* Find the original header. It is expected to be valid, of course.
* Check this, icmp_send is called from the most obscure devices
* sometimes.
*/
iph = ip_hdr(skb_in);
if ((u8 *)iph < skb_in->head ||
(skb_in->network_header + sizeof(*iph)) > skb_in->tail)
goto out;
/*
* No replies to physical multicast/broadcast
*/
if (skb_in->pkt_type != PACKET_HOST)
goto out;
/*
* Now check at the protocol level
*/
if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
goto out;
/*
* Only reply to fragment 0. We byte re-order the constant
* mask for efficiency.
*/
if (iph->frag_off & htons(IP_OFFSET))
goto out;
/*
* If we send an ICMP error to an ICMP error a mess would result..
*/
if (icmp_pointers[type].error) {
/*
* We are an error, check if we are replying to an
* ICMP error
*/
if (iph->protocol == IPPROTO_ICMP) {
u8 _inner_type, *itp;
itp = skb_header_pointer(skb_in,
skb_network_header(skb_in) +
(iph->ihl << 2) +
offsetof(struct icmphdr,
type) -
skb_in->data,
sizeof(_inner_type),
&_inner_type);
if (itp == NULL)
goto out;
/*
* Assume any unknown ICMP type is an error. This
* isn't specified by the RFC, but think about it..
*/
if (*itp > NR_ICMP_TYPES ||
icmp_pointers[*itp].error)
goto out;
}
}
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
/*
* Construct source address and options.
*/
saddr = iph->daddr;
if (!(rt->rt_flags & RTCF_LOCAL)) {
struct net_device *dev = NULL;
rcu_read_lock();
if (rt_is_input_route(rt) &&
net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
dev = dev_get_by_index_rcu(net, rt->rt_iif);
if (dev)
saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
else
saddr = 0;
rcu_read_unlock();
}
tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
IPTOS_PREC_INTERNETCONTROL) :
iph->tos;
if (ip_options_echo(&icmp_param.replyopts.opt.opt, skb_in))
goto out_unlock;
/*
* Prepare data for ICMP header.
*/
icmp_param.data.icmph.type = type;
icmp_param.data.icmph.code = code;
icmp_param.data.icmph.un.gateway = info;
icmp_param.data.icmph.checksum = 0;
icmp_param.skb = skb_in;
icmp_param.offset = skb_network_offset(skb_in);
inet_sk(sk)->tos = tos;
ipc.addr = iph->saddr;
ipc.opt = &icmp_param.replyopts.opt;
ipc.tx_flags = 0;
rt = icmp_route_lookup(net, skb_in, iph, saddr, tos,
type, code, &icmp_param);
if (IS_ERR(rt))
goto out_unlock;
if (!icmpv4_xrlim_allow(net, rt, type, code))
goto ende;
/* RFC says return as much as we can without exceeding 576 bytes. */
room = dst_mtu(&rt->dst);
if (room > 576)
room = 576;
room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
room -= sizeof(struct icmphdr);
icmp_param.data_len = skb_in->len - icmp_param.offset;
if (icmp_param.data_len > room)
icmp_param.data_len = room;
icmp_param.head_len = sizeof(struct icmphdr);
icmp_push_reply(&icmp_param, &ipc, &rt);
ende:
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
out:;
}
| 165,554 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheBackendImpl::SelectCacheForWorker(
int host_id, int parent_process_id, int parent_host_id) {
AppCacheHost* host = GetHost(host_id);
if (!host || host->was_select_cache_called())
return false;
host->SelectCacheForWorker(parent_process_id, parent_host_id);
return true;
}
Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer.
BUG=551044
Review URL: https://codereview.chromium.org/1418783005
Cr-Commit-Position: refs/heads/master@{#358815}
CWE ID: | bool AppCacheBackendImpl::SelectCacheForWorker(
int host_id, int parent_process_id, int parent_host_id) {
AppCacheHost* host = GetHost(host_id);
if (!host)
return false;
return host->SelectCacheForWorker(parent_process_id, parent_host_id);
}
| 171,738 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: _asn1_extract_der_octet (asn1_node node, const unsigned char *der,
int der_len, unsigned flags)
{
int len2, len3;
int counter, counter_end;
int result;
len2 = asn1_get_length_der (der, der_len, &len3);
if (len2 < -1)
return ASN1_DER_ERROR;
counter = len3 + 1;
DECR_LEN(der_len, len3);
if (len2 == -1)
counter_end = der_len - 2;
else
counter_end = der_len;
while (counter < counter_end)
{
DECR_LEN(der_len, 1);
if (len2 >= 0)
{
DECR_LEN(der_len, len2+len3);
_asn1_append_value (node, der + counter + len3, len2);
}
else
{ /* indefinite */
DECR_LEN(der_len, len3);
result =
_asn1_extract_der_octet (node, der + counter + len3,
der_len, flags);
if (result != ASN1_SUCCESS)
return result;
len2 = 0;
}
counter += len2 + len3 + 1;
}
return ASN1_SUCCESS;
cleanup:
return result;
}
Commit Message:
CWE ID: CWE-399 | _asn1_extract_der_octet (asn1_node node, const unsigned char *der,
int der_len, unsigned flags)
{
int len2, len3;
int counter, counter_end;
int result;
len2 = asn1_get_length_der (der, der_len, &len3);
if (len2 < -1)
return ASN1_DER_ERROR;
counter = len3 + 1;
DECR_LEN(der_len, len3);
if (len2 == -1)
{
if (der_len < 2)
return ASN1_DER_ERROR;
counter_end = der_len - 2;
}
else
counter_end = der_len;
if (counter_end < counter)
return ASN1_DER_ERROR;
while (counter < counter_end)
{
DECR_LEN(der_len, 1);
if (len2 >= 0)
{
DECR_LEN(der_len, len2+len3);
_asn1_append_value (node, der + counter + len3, len2);
}
else
{ /* indefinite */
DECR_LEN(der_len, len3);
result =
_asn1_extract_der_octet (node, der + counter + len3,
der_len, flags);
if (result != ASN1_SUCCESS)
return result;
len2 = 0;
}
counter += len2 + len3 + 1;
}
return ASN1_SUCCESS;
cleanup:
return result;
}
| 165,077 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
}
Commit Message: purple: Fix crash on ft requests from unknown contacts
Followup to 701ab81 (included in 3.5) which was a partial fix which only
improved things for non-libpurple file transfers (that is, just jabber)
CWE ID: CWE-476 | static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
if (!px->ft) {
return FALSE;
}
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
}
| 168,380 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bmp_getint32(jas_stream_t *in, int_fast32_t *val)
{
int n;
uint_fast32_t v;
int c;
for (n = 4, v = 0;;) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v |= (c << 24);
if (--n <= 0) {
break;
}
v >>= 8;
}
if (val) {
*val = v;
}
return 0;
}
Commit Message: Fixed a sanitizer failure in the BMP codec.
Also, added a --debug-level command line option to the imginfo command
for debugging purposes.
CWE ID: CWE-476 | static int bmp_getint32(jas_stream_t *in, int_fast32_t *val)
{
int n;
uint_fast32_t v;
int c;
for (n = 4, v = 0;;) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v |= (JAS_CAST(uint_fast32_t, c) << 24);
if (--n <= 0) {
break;
}
v >>= 8;
}
if (val) {
*val = v;
}
return 0;
}
| 168,763 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UninstallExtension(ExtensionService* service, const std::string& id) {
if (service && service->GetInstalledExtension(id)) {
service->UninstallExtension(id,
extensions::UNINSTALL_REASON_SYNC,
base::Bind(&base::DoNothing),
NULL);
}
}
Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry
This CL adds GetInstalledExtension() method to ExtensionRegistry and
uses it instead of deprecated ExtensionService::GetInstalledExtension()
in chrome/browser/ui/app_list/.
Part of removing the deprecated GetInstalledExtension() call
from the ExtensionService.
BUG=489687
Review URL: https://codereview.chromium.org/1130353010
Cr-Commit-Position: refs/heads/master@{#333036}
CWE ID: | void UninstallExtension(ExtensionService* service, const std::string& id) {
if (service) {
ExtensionService::UninstallExtensionHelper(
service, id, extensions::UNINSTALL_REASON_SYNC);
}
}
| 171,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) {
int new_mi_size;
vp9_set_mb_mi(cm, width, height);
new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
if (cm->mi_alloc_size < new_mi_size) {
cm->free_mi(cm);
if (cm->alloc_mi(cm, new_mi_size))
goto fail;
}
if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) {
free_seg_map(cm);
if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols))
goto fail;
}
if (cm->above_context_alloc_cols < cm->mi_cols) {
vpx_free(cm->above_context);
cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc(
2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE,
sizeof(*cm->above_context));
if (!cm->above_context) goto fail;
vpx_free(cm->above_seg_context);
cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc(
mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context));
if (!cm->above_seg_context) goto fail;
cm->above_context_alloc_cols = cm->mi_cols;
}
return 0;
fail:
vp9_free_context_buffers(cm);
return 1;
}
Commit Message: DO NOT MERGE libvpx: Cherry-pick 8b4c315 from upstream
Description from upstream:
vp9_alloc_context_buffers: clear cm->mi* on failure
this fixes a crash in vp9_dec_setup_mi() via
vp9_init_context_buffers() should decoding continue and the decoder
resyncs on a smaller frame
Bug: 30593752
Change-Id: Iafbf1c4114062bf796f51a6b03be71328f7bcc69
(cherry picked from commit 737c8493693243838128788fe9c3abc51f17338e)
(cherry picked from commit 3e88ffac8c80b76e15286ef8a7b3bd8fa246c761)
CWE ID: CWE-20 | int vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) {
int new_mi_size;
vp9_set_mb_mi(cm, width, height);
new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows);
if (cm->mi_alloc_size < new_mi_size) {
cm->free_mi(cm);
if (cm->alloc_mi(cm, new_mi_size))
goto fail;
}
if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) {
free_seg_map(cm);
if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols))
goto fail;
}
if (cm->above_context_alloc_cols < cm->mi_cols) {
vpx_free(cm->above_context);
cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc(
2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE,
sizeof(*cm->above_context));
if (!cm->above_context) goto fail;
vpx_free(cm->above_seg_context);
cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc(
mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context));
if (!cm->above_seg_context) goto fail;
cm->above_context_alloc_cols = cm->mi_cols;
}
return 0;
fail:
vp9_set_mb_mi(cm, 0, 0);
vp9_free_context_buffers(cm);
return 1;
}
| 173,381 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable )
{
SQLHSTMT hStmt;
SQLTCHAR szSepLine[32001];
SQLTCHAR szUcSQL[32001];
SQLSMALLINT cols;
SQLINTEGER ret;
SQLLEN nRows = 0;
szSepLine[ 0 ] = 0;
ansi_to_unicode( szSQL, szUcSQL );
/****************************
* EXECUTE SQL
***************************/
if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" );
return 0;
}
if ( buseED ) {
ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS );
if ( ret == SQL_NO_DATA )
{
fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" );
}
else if ( ret == SQL_SUCCESS_WITH_INFO )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" );
}
else if ( ret != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" );
SQLFreeStmt( hStmt, SQL_DROP );
free(szSepLine);
return 0;
}
}
else {
if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
ret = SQLExecute( hStmt );
if ( ret == SQL_NO_DATA )
{
fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" );
}
else if ( ret == SQL_SUCCESS_WITH_INFO )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" );
}
else if ( ret != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
}
do
{
/*
* check to see if it has generated a result set
*/
if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
if ( cols > 0 )
{
/****************************
* WRITE HEADER
***************************/
if ( bHTMLTable )
WriteHeaderHTMLTable( hStmt );
else if ( cDelimiter == 0 )
UWriteHeaderNormal( hStmt, szSepLine );
else if ( cDelimiter && bColumnNames )
WriteHeaderDelimited( hStmt, cDelimiter );
/****************************
* WRITE BODY
***************************/
if ( bHTMLTable )
WriteBodyHTMLTable( hStmt );
else if ( cDelimiter == 0 )
nRows = WriteBodyNormal( hStmt );
else
WriteBodyDelimited( hStmt, cDelimiter );
}
/****************************
* WRITE FOOTER
***************************/
if ( bHTMLTable )
WriteFooterHTMLTable( hStmt );
else if ( cDelimiter == 0 )
UWriteFooterNormal( hStmt, szSepLine, nRows );
}
while ( SQL_SUCCEEDED( SQLMoreResults( hStmt )));
/****************************
* CLEANUP
***************************/
SQLFreeStmt( hStmt, SQL_DROP );
return 1;
}
Commit Message: New Pre Source
CWE ID: CWE-119 | static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable )
{
SQLHSTMT hStmt;
SQLTCHAR szSepLine[32001];
SQLTCHAR szUcSQL[32001];
SQLSMALLINT cols;
SQLINTEGER ret;
SQLLEN nRows = 0;
szSepLine[ 0 ] = 0;
ansi_to_unicode( szSQL, szUcSQL );
/****************************
* EXECUTE SQL
***************************/
if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 );
fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" );
return 0;
}
if ( buseED ) {
ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS );
if ( ret == SQL_NO_DATA )
{
fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" );
}
else if ( ret == SQL_SUCCESS_WITH_INFO )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" );
}
else if ( ret != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
}
else {
if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
ret = SQLExecute( hStmt );
if ( ret == SQL_NO_DATA )
{
fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" );
}
else if ( ret == SQL_SUCCESS_WITH_INFO )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" );
}
else if ( ret != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
}
do
{
/*
* check to see if it has generated a result set
*/
if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS )
{
if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt );
fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" );
SQLFreeStmt( hStmt, SQL_DROP );
return 0;
}
if ( cols > 0 )
{
/****************************
* WRITE HEADER
***************************/
if ( bHTMLTable )
WriteHeaderHTMLTable( hStmt );
else if ( cDelimiter == 0 )
UWriteHeaderNormal( hStmt, szSepLine );
else if ( cDelimiter && bColumnNames )
WriteHeaderDelimited( hStmt, cDelimiter );
/****************************
* WRITE BODY
***************************/
if ( bHTMLTable )
WriteBodyHTMLTable( hStmt );
else if ( cDelimiter == 0 )
nRows = WriteBodyNormal( hStmt );
else
WriteBodyDelimited( hStmt, cDelimiter );
}
/****************************
* WRITE FOOTER
***************************/
if ( bHTMLTable )
WriteFooterHTMLTable( hStmt );
else if ( cDelimiter == 0 )
UWriteFooterNormal( hStmt, szSepLine, nRows );
}
while ( SQL_SUCCEEDED( SQLMoreResults( hStmt )));
/****************************
* CLEANUP
***************************/
SQLFreeStmt( hStmt, SQL_DROP );
return 1;
}
| 169,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 proc_keys_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key *key = rb_entry(_p, struct key, serial_node);
struct timespec now;
unsigned long timo;
key_ref_t key_ref, skey_ref;
char xbuf[16];
int rc;
struct keyring_search_context ctx = {
.index_key.type = key->type,
.index_key.description = key->description,
.cred = m->file->f_cred,
.match_data.cmp = lookup_user_key_possessed,
.match_data.raw_data = key,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
key_ref = make_key_ref(key, 0);
/* determine if the key is possessed by this process (a test we can
* skip if the key does not indicate the possessor can view it
*/
if (key->perm & KEY_POS_VIEW) {
skey_ref = search_my_process_keyrings(&ctx);
if (!IS_ERR(skey_ref)) {
key_ref_put(skey_ref);
key_ref = make_key_ref(key, 1);
}
}
/* check whether the current task is allowed to view the key */
rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
if (rc < 0)
return 0;
now = current_kernel_time();
rcu_read_lock();
/* come up with a suitable timeout value */
if (key->expiry == 0) {
memcpy(xbuf, "perm", 5);
} else if (now.tv_sec >= key->expiry) {
memcpy(xbuf, "expd", 5);
} else {
timo = key->expiry - now.tv_sec;
if (timo < 60)
sprintf(xbuf, "%lus", timo);
else if (timo < 60*60)
sprintf(xbuf, "%lum", timo / 60);
else if (timo < 60*60*24)
sprintf(xbuf, "%luh", timo / (60*60));
else if (timo < 60*60*24*7)
sprintf(xbuf, "%lud", timo / (60*60*24));
else
sprintf(xbuf, "%luw", timo / (60*60*24*7));
}
#define showflag(KEY, LETTER, FLAG) \
(test_bit(FLAG, &(KEY)->flags) ? LETTER : '-')
seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
key->serial,
showflag(key, 'I', KEY_FLAG_INSTANTIATED),
showflag(key, 'R', KEY_FLAG_REVOKED),
showflag(key, 'D', KEY_FLAG_DEAD),
showflag(key, 'Q', KEY_FLAG_IN_QUOTA),
showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT),
showflag(key, 'N', KEY_FLAG_NEGATIVE),
showflag(key, 'i', KEY_FLAG_INVALIDATED),
refcount_read(&key->usage),
xbuf,
key->perm,
from_kuid_munged(seq_user_ns(m), key->uid),
from_kgid_munged(seq_user_ns(m), key->gid),
key->type->name);
#undef showflag
if (key->type->describe)
key->type->describe(key, m);
seq_putc(m, '\n');
rcu_read_unlock();
return 0;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20 | static int proc_keys_show(struct seq_file *m, void *v)
{
struct rb_node *_p = v;
struct key *key = rb_entry(_p, struct key, serial_node);
struct timespec now;
unsigned long timo;
key_ref_t key_ref, skey_ref;
char xbuf[16];
short state;
int rc;
struct keyring_search_context ctx = {
.index_key.type = key->type,
.index_key.description = key->description,
.cred = m->file->f_cred,
.match_data.cmp = lookup_user_key_possessed,
.match_data.raw_data = key,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_NO_STATE_CHECK,
};
key_ref = make_key_ref(key, 0);
/* determine if the key is possessed by this process (a test we can
* skip if the key does not indicate the possessor can view it
*/
if (key->perm & KEY_POS_VIEW) {
skey_ref = search_my_process_keyrings(&ctx);
if (!IS_ERR(skey_ref)) {
key_ref_put(skey_ref);
key_ref = make_key_ref(key, 1);
}
}
/* check whether the current task is allowed to view the key */
rc = key_task_permission(key_ref, ctx.cred, KEY_NEED_VIEW);
if (rc < 0)
return 0;
now = current_kernel_time();
rcu_read_lock();
/* come up with a suitable timeout value */
if (key->expiry == 0) {
memcpy(xbuf, "perm", 5);
} else if (now.tv_sec >= key->expiry) {
memcpy(xbuf, "expd", 5);
} else {
timo = key->expiry - now.tv_sec;
if (timo < 60)
sprintf(xbuf, "%lus", timo);
else if (timo < 60*60)
sprintf(xbuf, "%lum", timo / 60);
else if (timo < 60*60*24)
sprintf(xbuf, "%luh", timo / (60*60));
else if (timo < 60*60*24*7)
sprintf(xbuf, "%lud", timo / (60*60*24));
else
sprintf(xbuf, "%luw", timo / (60*60*24*7));
}
state = key_read_state(key);
#define showflag(KEY, LETTER, FLAG) \
(test_bit(FLAG, &(KEY)->flags) ? LETTER : '-')
seq_printf(m, "%08x %c%c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ",
key->serial,
state != KEY_IS_UNINSTANTIATED ? 'I' : '-',
showflag(key, 'R', KEY_FLAG_REVOKED),
showflag(key, 'D', KEY_FLAG_DEAD),
showflag(key, 'Q', KEY_FLAG_IN_QUOTA),
showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT),
state < 0 ? 'N' : '-',
showflag(key, 'i', KEY_FLAG_INVALIDATED),
refcount_read(&key->usage),
xbuf,
key->perm,
from_kuid_munged(seq_user_ns(m), key->uid),
from_kgid_munged(seq_user_ns(m), key->gid),
key->type->name);
#undef showflag
if (key->type->describe)
key->type->describe(key, m);
seq_putc(m, '\n');
rcu_read_unlock();
return 0;
}
| 167,704 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: main(void)
{
unsigned int i;
unsigned char buf[MAX_LENGTH];
unsigned long crc;
unsigned char c;
int inchar;
/* Skip 8-byte signature */
for (i=8; i; i--)
{
c=GETBREAK;
putchar(c);
}
if (inchar != EOF)
for (;;)
{
/* Read the length */
unsigned long length; /* must be 32 bits! */
c=GETBREAK; buf[0] = c; length = c; length <<= 8;
c=GETBREAK; buf[1] = c; length += c; length <<= 8;
c=GETBREAK; buf[2] = c; length += c; length <<= 8;
c=GETBREAK; buf[3] = c; length += c;
/* Read the chunkname */
c=GETBREAK; buf[4] = c;
c=GETBREAK; buf[5] = c;
c=GETBREAK; buf[6] = c;
c=GETBREAK; buf[7] = c;
/* The iTXt chunk type expressed as integers is (105, 84, 88, 116) */
if (buf[4] == 105 && buf[5] == 84 && buf[6] == 88 && buf[7] == 116)
{
if (length >= MAX_LENGTH-12)
break; /* To do: handle this more gracefully */
/* Initialize the CRC */
crc = crc32(0, Z_NULL, 0);
/* Copy the data bytes */
for (i=8; i < length + 12; i++)
{
c=GETBREAK; buf[i] = c;
}
/* Calculate the CRC */
crc = crc32(crc, buf+4, (uInt)length+4);
for (;;)
{
/* Check the CRC */
if (((crc >> 24) & 0xff) == buf[length+8] &&
((crc >> 16) & 0xff) == buf[length+9] &&
((crc >> 8) & 0xff) == buf[length+10] &&
((crc ) & 0xff) == buf[length+11])
break;
length++;
if (length >= MAX_LENGTH-12)
break;
c=GETBREAK;
buf[length+11]=c;
/* Update the CRC */
crc = crc32(crc, buf+7+length, 1);
}
/* Update length bytes */
buf[0] = (unsigned char)((length << 24) & 0xff);
buf[1] = (unsigned char)((length << 16) & 0xff);
buf[2] = (unsigned char)((length << 8) & 0xff);
buf[3] = (unsigned char)((length ) & 0xff);
/* Write the fixed iTXt chunk (length, name, data, crc) */
for (i=0; i<length+12; i++)
putchar(buf[i]);
}
else
{
/* Copy bytes that were already read (length and chunk name) */
for (i=0; i<8; i++)
putchar(buf[i]);
/* Copy data bytes and CRC */
for (i=8; i< length+12; i++)
{
c=GETBREAK;
putchar(c);
}
if (inchar == EOF)
{
break;
}
/* The IEND chunk type expressed as integers is (73, 69, 78, 68) */
if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68)
break;
}
if (inchar == EOF)
break;
if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68)
break;
}
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | main(void)
{
unsigned int i;
unsigned char buf[MAX_LENGTH];
unsigned long crc;
unsigned char c;
int inchar;
/* Skip 8-byte signature */
for (i=8; i; i--)
{
GETBREAK;
putchar(c);
}
if (inchar == c) /* !EOF */
for (;;)
{
/* Read the length */
unsigned long length; /* must be 32 bits! */
GETBREAK; buf[0] = c; length = c; length <<= 8;
GETBREAK; buf[1] = c; length += c; length <<= 8;
GETBREAK; buf[2] = c; length += c; length <<= 8;
GETBREAK; buf[3] = c; length += c;
/* Read the chunkname */
GETBREAK; buf[4] = c;
GETBREAK; buf[5] = c;
GETBREAK; buf[6] = c;
GETBREAK; buf[7] = c;
/* The iTXt chunk type expressed as integers is (105, 84, 88, 116) */
if (buf[4] == 105 && buf[5] == 84 && buf[6] == 88 && buf[7] == 116)
{
if (length >= MAX_LENGTH-12)
break; /* To do: handle this more gracefully */
/* Initialize the CRC */
crc = crc32(0, Z_NULL, 0);
/* Copy the data bytes */
for (i=8; i < length + 12; i++)
{
GETBREAK; buf[i] = c;
}
if (inchar != c) /* EOF */
break;
/* Calculate the CRC */
crc = crc32(crc, buf+4, (uInt)length+4);
for (;;)
{
/* Check the CRC */
if (((crc >> 24) & 0xffU) == buf[length+8] &&
((crc >> 16) & 0xffU) == buf[length+9] &&
((crc >> 8) & 0xffU) == buf[length+10] &&
((crc ) & 0xffU) == buf[length+11])
break;
length++;
if (length >= MAX_LENGTH-12)
break;
GETBREAK;
buf[length+11] = c;
/* Update the CRC */
crc = crc32(crc, buf+7+length, 1);
}
if (inchar != c) /* EOF */
break;
/* Update length bytes */
buf[0] = (unsigned char)((length >> 24) & 0xffU);
buf[1] = (unsigned char)((length >> 16) & 0xffU);
buf[2] = (unsigned char)((length >> 8) & 0xffU);
buf[3] = (unsigned char)((length ) & 0xffU);
/* Write the fixed iTXt chunk (length, name, data, crc) */
for (i=0; i<length+12; i++)
putchar(buf[i]);
}
else
{
if (inchar != c) /* EOF */
break;
/* Copy bytes that were already read (length and chunk name) */
for (i=0; i<8; i++)
putchar(buf[i]);
/* Copy data bytes and CRC */
for (i=8; i< length+12; i++)
{
GETBREAK;
putchar(c);
}
if (inchar != c) /* EOF */
{
break;
}
/* The IEND chunk type expressed as integers is (73, 69, 78, 68) */
if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68)
break;
}
if (inchar != c) /* EOF */
break;
if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68)
break;
}
return 0;
}
| 173,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: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; ғ > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Add more to confusables list
U+04FB (ӻ) to f
U+050F (ԏ) to t
U+050B (ԋ) and U+0527 (ԧ) to h
U+0437(з) and U+04E1(ӡ) to 3
Add tests for the above entries and tests for ASCII-digit spoofing.
Bug: 816769,820068
Test: components_unittests --gtest_filter=*IDN*
Change-Id: I6cd0a7e97cd0ec2df522ce30f632acfd7b78eee2
Reviewed-on: https://chromium-review.googlesource.com/962875
Reviewed-by: Peter Kasting <[email protected]>
Commit-Queue: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543600}
CWE ID: | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
// U+04C8 (ӈ), U+04CA (ӊ), U+050B (ԋ), U+0527 (ԧ), U+0529 (ԩ)} => h
// - {U+0167 (ŧ), U+0442 (т), U+04AD (ҭ), U+050F (ԏ)} => t
// - {U+0493 (ғ), U+04FB (ӻ)} => f
// - {U+0437 (з), U+04E1 (ӡ)} => 3
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8("[þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋп] > n; [ŧтҭԏ] > t;"
"[ƅьҍв] > b; [ωшщฟ] > w; [мӎ] > m;"
"[єҽҿၔ] > e; ґ > r; [ғӻ] > f; [ҫင] > c;"
"ұ > y; [χҳӽӿ] > x;"
#if defined(OS_WIN)
"ӏ > i;"
#else
"ӏ > l;"
#endif
"ԃ > d; [ԍဌ] > g; [ടร] > s; ၂ > j;"
"[зӡ] > 3"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 172,736 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpg_dec_parseopts(char *optstr, jpg_dec_importopts_t *opts)
{
jas_tvparser_t *tvp;
opts->max_size = 0;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
return -1;
}
while (!jas_tvparser_next(tvp)) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_MAXSIZE:
opts->max_size = atoi(jas_tvparser_getval(tvp));
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
return 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190 | static int jpg_dec_parseopts(char *optstr, jpg_dec_importopts_t *opts)
{
jas_tvparser_t *tvp;
opts->max_samples = 64 * JAS_MEBI;
if (!(tvp = jas_tvparser_create(optstr ? optstr : ""))) {
return -1;
}
while (!jas_tvparser_next(tvp)) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(decopts,
jas_tvparser_gettag(tvp)))->id) {
case OPT_MAXSIZE:
opts->max_samples = atoi(jas_tvparser_getval(tvp));
break;
default:
jas_eprintf("warning: ignoring invalid option %s\n",
jas_tvparser_gettag(tvp));
break;
}
}
jas_tvparser_destroy(tvp);
return 0;
}
| 168,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 on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
Commit Message: Merge pull request #131 from benjaminchodroff/master
fix memory corruption and other 32bit overflows
CWE ID: CWE-190 | static int on_http_message_complete(http_parser* parser)
{
struct clt_info *info = parser->data;
ws_svr *svr = ws_svr_from_ses(info->ses);
info->request->version_major = parser->http_major;
info->request->version_minor = parser->http_minor;
info->request->method = parser->method;
dict_entry *entry;
dict_iterator *iter = dict_get_iterator(info->request->headers);
while ((entry = dict_next(iter)) != NULL) {
log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val);
}
dict_release_iterator(iter);
if (info->request->method != HTTP_GET)
goto error;
if (http_request_get_header(info->request, "Host") == NULL)
goto error;
double version = info->request->version_major + info->request->version_minor * 0.1;
if (version < 1.1)
goto error;
const char *upgrade = http_request_get_header(info->request, "Upgrade");
if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0)
goto error;
const char *connection = http_request_get_header(info->request, "Connection");
if (connection == NULL || strlen(connection) > UT_WS_SVR_MAX_HEADER_SIZE)
goto error;
else {
bool found_upgrade = false;
int count;
sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count);
if (tokens == NULL)
goto error;
for (int i = 0; i < count; i++) {
sds token = tokens[i];
sdstrim(token, " ");
if (strcasecmp(token, "Upgrade") == 0) {
found_upgrade = true;
break;
}
}
sdsfreesplitres(tokens, count);
if (!found_upgrade)
goto error;
}
const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version");
if (ws_version == NULL || strcmp(ws_version, "13") != 0)
goto error;
const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key");
if (ws_key == NULL)
goto error;
const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol");
if (protocol_list && !is_good_protocol(protocol_list, svr->protocol))
goto error;
if (strlen(svr->origin) > 0) {
const char *origin = http_request_get_header(info->request, "Origin");
if (origin == NULL || !is_good_origin(origin, svr->origin))
goto error;
}
if (svr->type.on_privdata_alloc) {
info->privdata = svr->type.on_privdata_alloc(svr);
if (info->privdata == NULL)
goto error;
}
info->upgrade = true;
info->remote = sdsnew(http_get_remote_ip(info->ses, info->request));
info->url = sdsnew(info->request->url);
if (svr->type.on_upgrade) {
svr->type.on_upgrade(info->ses, info->remote);
}
if (protocol_list) {
send_hand_shake_reply(info->ses, svr->protocol, ws_key);
} else {
send_hand_shake_reply(info->ses, NULL, ws_key);
}
return 0;
error:
ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses);
return -1;
}
| 169,018 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BluetoothAdapterChromeOS::BluetoothAdapterChromeOS()
: weak_ptr_factory_(this) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this);
std::vector<dbus::ObjectPath> object_paths =
DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters();
if (!object_paths.empty()) {
VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available.";
SetAdapter(object_paths[0]);
}
}
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: | BluetoothAdapterChromeOS::BluetoothAdapterChromeOS()
: weak_ptr_factory_(this) {
DBusThreadManager::Get()->GetBluetoothAdapterClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothDeviceClient()->AddObserver(this);
DBusThreadManager::Get()->GetBluetoothInputClient()->AddObserver(this);
std::vector<dbus::ObjectPath> object_paths =
DBusThreadManager::Get()->GetBluetoothAdapterClient()->GetAdapters();
if (!object_paths.empty()) {
VLOG(1) << object_paths.size() << " Bluetooth adapter(s) available.";
SetAdapter(object_paths[0]);
}
// Register the pairing agent.
dbus::Bus* system_bus = DBusThreadManager::Get()->GetSystemBus();
agent_.reset(BluetoothAgentServiceProvider::Create(
system_bus, dbus::ObjectPath(kAgentPath), this));
DCHECK(agent_.get());
VLOG(1) << "Registering pairing agent";
DBusThreadManager::Get()->GetBluetoothAgentManagerClient()->
RegisterAgent(
dbus::ObjectPath(kAgentPath),
bluetooth_agent_manager::kKeyboardDisplayCapability,
base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgent,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&BluetoothAdapterChromeOS::OnRegisterAgentError,
weak_ptr_factory_.GetWeakPtr()));
}
| 171,214 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SSH_PACKET_CALLBACK(ssh_packet_dh_reply){
int rc;
(void)type;
(void)user;
SSH_LOG(SSH_LOG_PROTOCOL,"Received SSH_KEXDH_REPLY");
if(session->session_state!= SSH_SESSION_STATE_DH &&
session->dh_handshake_state != DH_STATE_INIT_SENT){
ssh_set_error(session,SSH_FATAL,"ssh_packet_dh_reply called in wrong state : %d:%d",
session->session_state,session->dh_handshake_state);
goto error;
}
switch(session->next_crypto->kex_type){
case SSH_KEX_DH_GROUP1_SHA1:
case SSH_KEX_DH_GROUP14_SHA1:
rc=ssh_client_dh_reply(session, packet);
break;
#ifdef HAVE_ECDH
case SSH_KEX_ECDH_SHA2_NISTP256:
rc = ssh_client_ecdh_reply(session, packet);
break;
#endif
#ifdef HAVE_CURVE25519
case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG:
rc = ssh_client_curve25519_reply(session, packet);
break;
#endif
default:
ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_dh_reply");
goto error;
}
if(rc==SSH_OK) {
session->dh_handshake_state = DH_STATE_NEWKEYS_SENT;
return SSH_PACKET_USED;
}
error:
session->session_state=SSH_SESSION_STATE_ERROR;
return SSH_PACKET_USED;
}
Commit Message:
CWE ID: | SSH_PACKET_CALLBACK(ssh_packet_dh_reply){
int rc;
(void)type;
(void)user;
SSH_LOG(SSH_LOG_PROTOCOL,"Received SSH_KEXDH_REPLY");
if (session->session_state != SSH_SESSION_STATE_DH ||
session->dh_handshake_state != DH_STATE_INIT_SENT){
ssh_set_error(session,SSH_FATAL,"ssh_packet_dh_reply called in wrong state : %d:%d",
session->session_state,session->dh_handshake_state);
goto error;
}
switch(session->next_crypto->kex_type){
case SSH_KEX_DH_GROUP1_SHA1:
case SSH_KEX_DH_GROUP14_SHA1:
rc=ssh_client_dh_reply(session, packet);
break;
#ifdef HAVE_ECDH
case SSH_KEX_ECDH_SHA2_NISTP256:
rc = ssh_client_ecdh_reply(session, packet);
break;
#endif
#ifdef HAVE_CURVE25519
case SSH_KEX_CURVE25519_SHA256_LIBSSH_ORG:
rc = ssh_client_curve25519_reply(session, packet);
break;
#endif
default:
ssh_set_error(session,SSH_FATAL,"Wrong kex type in ssh_packet_dh_reply");
goto error;
}
if(rc==SSH_OK) {
session->dh_handshake_state = DH_STATE_NEWKEYS_SENT;
return SSH_PACKET_USED;
}
error:
session->session_state=SSH_SESSION_STATE_ERROR;
return SSH_PACKET_USED;
}
| 165,323 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: isoclns_print(netdissect_options *ndo,
const uint8_t *p, u_int length, u_int caplen)
{
if (caplen <= 1) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", caplen);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (caplen > 1)
print_unknown_data(ndo, p, "\n\t", caplen);
break;
}
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | isoclns_print(netdissect_options *ndo,
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
| 167,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 encode_share_access(struct xdr_stream *xdr, int open_flags)
{
__be32 *p;
RESERVE_SPACE(8);
switch (open_flags & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
WRITE32(NFS4_SHARE_ACCESS_READ);
break;
case FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_WRITE);
break;
case FMODE_READ|FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_BOTH);
break;
default:
BUG();
}
WRITE32(0); /* for linux, share_deny = 0 always */
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | static void encode_share_access(struct xdr_stream *xdr, int open_flags)
static void encode_share_access(struct xdr_stream *xdr, fmode_t fmode)
{
__be32 *p;
RESERVE_SPACE(8);
switch (fmode & (FMODE_READ|FMODE_WRITE)) {
case FMODE_READ:
WRITE32(NFS4_SHARE_ACCESS_READ);
break;
case FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_WRITE);
break;
case FMODE_READ|FMODE_WRITE:
WRITE32(NFS4_SHARE_ACCESS_BOTH);
break;
default:
WRITE32(0);
}
WRITE32(0); /* for linux, share_deny = 0 always */
}
| 165,715 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 snd_ctl_tlv_ioctl(struct snd_ctl_file *file,
struct snd_ctl_tlv __user *_tlv,
int op_flag)
{
struct snd_card *card = file->card;
struct snd_ctl_tlv tlv;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int len;
int err = 0;
if (copy_from_user(&tlv, _tlv, sizeof(tlv)))
return -EFAULT;
if (tlv.length < sizeof(unsigned int) * 2)
return -EINVAL;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_numid(card, tlv.numid);
if (kctl == NULL) {
err = -ENOENT;
goto __kctl_end;
}
if (kctl->tlv.p == NULL) {
err = -ENXIO;
goto __kctl_end;
}
vd = &kctl->vd[tlv.numid - kctl->id.numid];
if ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) ||
(op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) ||
(op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) {
err = -ENXIO;
goto __kctl_end;
}
if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
if (vd->owner != NULL && vd->owner != file) {
err = -EPERM;
goto __kctl_end;
}
err = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv);
if (err > 0) {
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &kctl->id);
return 0;
}
} else {
if (op_flag) {
err = -ENXIO;
goto __kctl_end;
}
len = kctl->tlv.p[1] + 2 * sizeof(unsigned int);
if (tlv.length < len) {
err = -ENOMEM;
goto __kctl_end;
}
if (copy_to_user(_tlv->tlv, kctl->tlv.p, len))
err = -EFAULT;
}
__kctl_end:
up_read(&card->controls_rwsem);
return err;
}
Commit Message: ALSA: control: Don't access controls outside of protected regions
A control that is visible on the card->controls list can be freed at any time.
This means we must not access any of its memory while not holding the
controls_rw_lock. Otherwise we risk a use after free access.
Signed-off-by: Lars-Peter Clausen <[email protected]>
Acked-by: Jaroslav Kysela <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: | static int snd_ctl_tlv_ioctl(struct snd_ctl_file *file,
struct snd_ctl_tlv __user *_tlv,
int op_flag)
{
struct snd_card *card = file->card;
struct snd_ctl_tlv tlv;
struct snd_kcontrol *kctl;
struct snd_kcontrol_volatile *vd;
unsigned int len;
int err = 0;
if (copy_from_user(&tlv, _tlv, sizeof(tlv)))
return -EFAULT;
if (tlv.length < sizeof(unsigned int) * 2)
return -EINVAL;
down_read(&card->controls_rwsem);
kctl = snd_ctl_find_numid(card, tlv.numid);
if (kctl == NULL) {
err = -ENOENT;
goto __kctl_end;
}
if (kctl->tlv.p == NULL) {
err = -ENXIO;
goto __kctl_end;
}
vd = &kctl->vd[tlv.numid - kctl->id.numid];
if ((op_flag == 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_READ) == 0) ||
(op_flag > 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_WRITE) == 0) ||
(op_flag < 0 && (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_COMMAND) == 0)) {
err = -ENXIO;
goto __kctl_end;
}
if (vd->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) {
if (vd->owner != NULL && vd->owner != file) {
err = -EPERM;
goto __kctl_end;
}
err = kctl->tlv.c(kctl, op_flag, tlv.length, _tlv->tlv);
if (err > 0) {
struct snd_ctl_elem_id id = kctl->id;
up_read(&card->controls_rwsem);
snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_TLV, &id);
return 0;
}
} else {
if (op_flag) {
err = -ENXIO;
goto __kctl_end;
}
len = kctl->tlv.p[1] + 2 * sizeof(unsigned int);
if (tlv.length < len) {
err = -ENOMEM;
goto __kctl_end;
}
if (copy_to_user(_tlv->tlv, kctl->tlv.p, len))
err = -EFAULT;
}
__kctl_end:
up_read(&card->controls_rwsem);
return err;
}
| 166,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample_index)
{
png_uint_32 bit_index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
bit_index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
bit_index *= 3;
if (colour_type & 4)
bit_index += x; /* Alpha channel */
/* Multiple channels; select one: */
if (colour_type & (2+4))
bit_index += sample_index * bit_depth;
}
/* Return the sample from the row as an integer. */
row += bit_index >> 3;
result = *row;
if (bit_depth == 8)
return result;
else if (bit_depth > 8)
return (result << 8) + *++row;
/* Less than 8 bits per sample. */
bit_index &= 7;
return (result >> (8-bit_index-bit_depth)) & ((1U<<bit_depth)-1);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth,
png_uint_32 x, unsigned int sample_index, int swap16, int littleendian)
{
png_uint_32 bit_index, result;
/* Find a sample index for the desired sample: */
x *= bit_depth;
bit_index = x;
if ((colour_type & 1) == 0) /* !palette */
{
if (colour_type & 2)
bit_index *= 3;
if (colour_type & 4)
bit_index += x; /* Alpha channel */
/* Multiple channels; select one: */
if (colour_type & (2+4))
bit_index += sample_index * bit_depth;
}
/* Return the sample from the row as an integer. */
row += bit_index >> 3;
result = *row;
if (bit_depth == 8)
return result;
else if (bit_depth > 8)
{
if (swap16)
return (*++row << 8) + result;
else
return (result << 8) + *++row;
}
/* Less than 8 bits per sample. By default PNG has the big end of
* the egg on the left of the screen, but if littleendian is set
* then the big end is on the right.
*/
bit_index &= 7;
if (!littleendian)
bit_index = 8-bit_index-bit_depth;
return (result >> bit_index) & ((1U<<bit_depth)-1);
}
| 173,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 const char *GetMagickFeatures(void)
{
return "DPC"
#if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL)
" Modules"
#endif
#if defined(MAGICKCORE_HDRI_SUPPORT)
" HDRI"
#endif
#if defined(MAGICKCORE_OPENCL_SUPPORT)
" OpenCL"
#endif
#if defined(MAGICKCORE_OPENMP_SUPPORT)
" OpenMP"
#endif
;
}
Commit Message:
CWE ID: CWE-189 | MagickExport const char *GetMagickFeatures(void)
{
return "DPC"
#if defined(MAGICKCORE_WINDOWS_SUPPORT) && defined(_DEBUG)
" Debug"
#endif
#if defined(MAGICKCORE_CIPHER_SUPPORT)
" Cipher"
#endif
#if defined(MAGICKCORE_HDRI_SUPPORT)
" HDRI"
#endif
#if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL)
" Modules"
#endif
#if defined(MAGICKCORE_OPENCL_SUPPORT)
" OpenCL"
#endif
#if defined(MAGICKCORE_OPENMP_SUPPORT)
" OpenMP"
#endif
#if defined(ZERO_CONFIGURATION_SUPPORT)
" Zero-configuration"
#endif
;
}
| 168,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: bool adapter_enable_disable() {
int error;
CALL_AND_WAIT(error = bt_interface->enable(), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error enabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_ON, "Adapter did not turn on.");
CALL_AND_WAIT(error = bt_interface->disable(), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error disabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_OFF, "Adapter did not turn off.");
return true;
}
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 | bool adapter_enable_disable() {
int error;
CALL_AND_WAIT(error = bt_interface->enable(false), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error enabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_ON, "Adapter did not turn on.");
CALL_AND_WAIT(error = bt_interface->disable(), adapter_state_changed);
TASSERT(error == BT_STATUS_SUCCESS, "Error disabling Bluetooth: %d", error);
TASSERT(adapter_get_state() == BT_STATE_OFF, "Adapter did not turn off.");
return true;
}
| 173,556 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection,
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection
This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree|
instead of |VisibleSelection| to reduce usage of |VisibleSelection| for
improving code health.
BUG=657237
TEST=n/a
Review-Url: https://codereview.chromium.org/2733183002
Cr-Commit-Position: refs/heads/master@{#455368}
CWE ID: | bool Editor::insertTextWithoutSendingTextEvent(const String& text,
bool selectInsertedText,
TextEvent* triggeringEvent) {
if (text.isEmpty())
return false;
const VisibleSelection& selection = selectionForCommand(triggeringEvent);
if (!selection.isContentEditable())
return false;
spellChecker().updateMarkersForWordsAffectedByEditing(
isSpaceOrNewline(text[0]));
TypingCommand::insertText(
*selection.start().document(), text, selection.asSelection(),
selectInsertedText ? TypingCommand::SelectInsertedText : 0,
triggeringEvent && triggeringEvent->isComposition()
? TypingCommand::TextCompositionConfirm
: TypingCommand::TextCompositionNone);
if (LocalFrame* editedFrame = selection.start().document()->frame()) {
if (Page* page = editedFrame->page()) {
LocalFrame* focusedOrMainFrame =
toLocalFrame(page->focusController().focusedOrMainFrame());
focusedOrMainFrame->selection().revealSelection(
ScrollAlignment::alignCenterIfNeeded);
}
}
return true;
}
| 172,030 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringCase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXLayoutObject::isSelected() const {
if (!getLayoutObject() || !getNode())
return false;
const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
if (equalIgnoringASCIICase(ariaSelected, "true"))
return true;
AXObject* focusedObject = axObjectCache().focusedObject();
if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject &&
focusedObject->activeDescendant() == this) {
return true;
}
if (isTabItem() && isTabItemSelected())
return true;
return false;
}
| 171,905 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName)
{
char nameBuf[512];
char absoluteFile[sizeof(nameBuf)];
const size_t kBufLen = sizeof(nameBuf) - 1;
const char* dataRoot;
char* cp;
/*
* Get the absolute path of the Jar or DEX file.
*/
absoluteFile[0] = '\0';
if (fileName[0] != '/') {
/*
* Generate the absolute path. This doesn't do everything it
* should, e.g. if filename is "./out/whatever" it doesn't crunch
* the leading "./" out, but it'll do.
*/
if (getcwd(absoluteFile, kBufLen) == NULL) {
ALOGE("Can't get CWD while opening jar file");
return NULL;
}
strncat(absoluteFile, "/", kBufLen);
}
strncat(absoluteFile, fileName, kBufLen);
/*
* Append the name of the Jar file entry, if any. This is not currently
* required, but will be if we start putting more than one DEX file
* in a Jar.
*/
if (subFileName != NULL) {
strncat(absoluteFile, "/", kBufLen);
strncat(absoluteFile, subFileName, kBufLen);
}
/* Turn the path into a flat filename by replacing
* any slashes after the first one with '@' characters.
*/
cp = absoluteFile + 1;
while (*cp != '\0') {
if (*cp == '/') {
*cp = '@';
}
cp++;
}
/* Build the name of the cache directory.
*/
dataRoot = getenv("ANDROID_DATA");
if (dataRoot == NULL)
dataRoot = "/data";
snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
/* Tack on the file name for the actual cache file path.
*/
strncat(nameBuf, absoluteFile, kBufLen);
ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf);
return strdup(nameBuf);
}
Commit Message: Fix potential buffer overrun.
BUG=27840771
Change-Id: I240f188b2e8f4b45d90138cfb3b14869cf506452
CWE ID: CWE-119 | char* dexOptGenerateCacheFileName(const char* fileName, const char* subFileName)
{
char nameBuf[512];
char absoluteFile[sizeof(nameBuf)];
const size_t kBufLen = sizeof(nameBuf) - 1;
const char* dataRoot;
char* cp;
/*
* Get the absolute path of the Jar or DEX file.
*/
absoluteFile[0] = '\0';
if (fileName[0] != '/') {
/*
* Generate the absolute path. This doesn't do everything it
* should, e.g. if filename is "./out/whatever" it doesn't crunch
* the leading "./" out, but it'll do.
*/
if (getcwd(absoluteFile, kBufLen) == NULL) {
ALOGE("Can't get CWD while opening jar file");
return NULL;
}
strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile));
}
strncat(absoluteFile, fileName, kBufLen - strlen(absoluteFile));
/*
* Append the name of the Jar file entry, if any. This is not currently
* required, but will be if we start putting more than one DEX file
* in a Jar.
*/
if (subFileName != NULL) {
strncat(absoluteFile, "/", kBufLen - strlen(absoluteFile));
strncat(absoluteFile, subFileName, kBufLen - strlen(absoluteFile));
}
/* Turn the path into a flat filename by replacing
* any slashes after the first one with '@' characters.
*/
cp = absoluteFile + 1;
while (*cp != '\0') {
if (*cp == '/') {
*cp = '@';
}
cp++;
}
/* Build the name of the cache directory.
*/
dataRoot = getenv("ANDROID_DATA");
if (dataRoot == NULL)
dataRoot = "/data";
snprintf(nameBuf, kBufLen, "%s/%s", dataRoot, kCacheDirectoryName);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
snprintf(nameBuf, kBufLen, "%s/%s/%s", dataRoot, kCacheDirectoryName, kInstructionSet);
if (strcmp(dataRoot, "/data") != 0) {
int result = dexOptMkdir(nameBuf, 0700);
if (result != 0 && errno != EEXIST) {
ALOGE("Failed to create dalvik-cache directory %s: %s", nameBuf, strerror(errno));
return NULL;
}
}
/* Tack on the file name for the actual cache file path.
*/
strncat(nameBuf, absoluteFile, kBufLen - strlen(nameBuf));
ALOGV("Cache file for '%s' '%s' is '%s'", fileName, subFileName, nameBuf);
return strdup(nameBuf);
}
| 173,559 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cms_copy_content(BIO *out, BIO *in, unsigned int flags)
{
unsigned char buf[4096];
int r = 0, i;
BIO *tmpout = NULL;
if (out == NULL)
tmpout = BIO_new(BIO_s_null());
else if (flags & CMS_TEXT)
{
tmpout = BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(tmpout, 0);
}
else
tmpout = out;
if(!tmpout)
{
CMSerr(CMS_F_CMS_COPY_CONTENT,ERR_R_MALLOC_FAILURE);
goto err;
}
/* Read all content through chain to process digest, decrypt etc */
for (;;)
{
i=BIO_read(in,buf,sizeof(buf));
if (i <= 0)
{
if (BIO_method_type(in) == BIO_TYPE_CIPHER)
{
if (!BIO_get_cipher_status(in))
goto err;
}
if (i < 0)
goto err;
break;
}
if (tmpout && (BIO_write(tmpout, buf, i) != i))
goto err;
}
if(flags & CMS_TEXT)
{
if(!SMIME_text(tmpout, out))
{
CMSerr(CMS_F_CMS_COPY_CONTENT,CMS_R_SMIME_TEXT_ERROR);
goto err;
}
}
r = 1;
err:
if (tmpout && (tmpout != out))
BIO_free(tmpout);
return r;
}
Commit Message: Canonicalise input in CMS_verify.
If content is detached and not binary mode translate the input to
CRLF format. Before this change the input was verified verbatim
which lead to a discrepancy between sign and verify.
CWE ID: CWE-399 | static int cms_copy_content(BIO *out, BIO *in, unsigned int flags)
static BIO *cms_get_text_bio(BIO *out, unsigned int flags)
{
BIO *rbio;
if (out == NULL)
rbio = BIO_new(BIO_s_null());
else if (flags & CMS_TEXT)
{
rbio = BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(rbio, 0);
}
else
rbio = out;
return rbio;
}
static int cms_copy_content(BIO *out, BIO *in, unsigned int flags)
{
unsigned char buf[4096];
int r = 0, i;
BIO *tmpout;
tmpout = cms_get_text_bio(out, flags);
if(!tmpout)
{
CMSerr(CMS_F_CMS_COPY_CONTENT,ERR_R_MALLOC_FAILURE);
goto err;
}
/* Read all content through chain to process digest, decrypt etc */
for (;;)
{
i=BIO_read(in,buf,sizeof(buf));
if (i <= 0)
{
if (BIO_method_type(in) == BIO_TYPE_CIPHER)
{
if (!BIO_get_cipher_status(in))
goto err;
}
if (i < 0)
goto err;
break;
}
if (tmpout && (BIO_write(tmpout, buf, i) != i))
goto err;
}
if(flags & CMS_TEXT)
{
if(!SMIME_text(tmpout, out))
{
CMSerr(CMS_F_CMS_COPY_CONTENT,CMS_R_SMIME_TEXT_ERROR);
goto err;
}
}
r = 1;
err:
if (tmpout && (tmpout != out))
BIO_free(tmpout);
return r;
}
| 166,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: const Chapters::Atom* Chapters::Edition::GetAtom(int index) const
{
if (index < 0)
return NULL;
if (index >= m_atoms_count)
return NULL;
return m_atoms + index;
}
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 Chapters::Atom* Chapters::Edition::GetAtom(int index) const
const Chapters::Display* Chapters::Atom::GetDisplay(int index) const {
if (index < 0)
return NULL;
if (index >= m_displays_count)
return NULL;
return m_displays + index;
}
| 174,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BoundingBox "viewbox"
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if ((image->columns == 0) || (image->rows == 0))
{
char
primitive[MaxTextExtent];
register char
*p;
SegmentInfo
bounds;
/*
Determine size of image canvas.
*/
while (ReadBlobString(image,primitive) != (char *) NULL)
{
for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ;
if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0)
continue;
(void) sscanf(p,"viewbox %lf %lf %lf %lf",&bounds.x1,&bounds.y1,
&bounds.x2,&bounds.y2);
image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5);
image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5);
break;
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/
DefaultResolution;
draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/
DefaultResolution;
image->columns=(size_t) (draw_info->affine.sx*image->columns);
image->rows=(size_t) (draw_info->affine.sy*image->rows);
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Render drawing.
*/
if (GetBlobStreamData(image) == (unsigned char *) NULL)
draw_info->primitive=FileToString(image->filename,~0UL,exception);
else
{
draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1);
if (draw_info->primitive != (char *) NULL)
{
CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image),
GetBlobSize(image));
draw_info->primitive[GetBlobSize(image)]='\0';
}
}
(void) DrawImage(image,draw_info);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define BoundingBox "viewbox"
DrawInfo
*draw_info;
Image
*image;
MagickBooleanType
status;
/*
Open image.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if ((image->columns == 0) || (image->rows == 0))
{
char
primitive[MaxTextExtent];
register char
*p;
SegmentInfo
bounds;
/*
Determine size of image canvas.
*/
while (ReadBlobString(image,primitive) != (char *) NULL)
{
for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ;
if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0)
continue;
(void) sscanf(p,"viewbox %lf %lf %lf %lf",&bounds.x1,&bounds.y1,
&bounds.x2,&bounds.y2);
image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5);
image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5);
break;
}
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(OptionError,"MustSpecifyImageSize");
draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/
DefaultResolution;
draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/
DefaultResolution;
image->columns=(size_t) (draw_info->affine.sx*image->columns);
image->rows=(size_t) (draw_info->affine.sy*image->rows);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Render drawing.
*/
if (GetBlobStreamData(image) == (unsigned char *) NULL)
draw_info->primitive=FileToString(image->filename,~0UL,exception);
else
{
draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1);
if (draw_info->primitive != (char *) NULL)
{
CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image),
GetBlobSize(image));
draw_info->primitive[GetBlobSize(image)]='\0';
}
}
(void) DrawImage(image,draw_info);
draw_info=DestroyDrawInfo(draw_info);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item )
{
cJSON_AddItemToObject( object, string, create_reference( item ) );
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | void cJSON_AddItemReferenceToObject( cJSON *object, const char *string, cJSON *item )
| 167,266 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BiquadDSPKernel::getFrequencyResponse(int nFrequencies,
const float* frequencyHz,
float* magResponse,
float* phaseResponse)
{
bool isGood = nFrequencies > 0 && frequencyHz && magResponse && phaseResponse;
ASSERT(isGood);
if (!isGood)
return;
Vector<float> frequency(nFrequencies);
double nyquist = this->nyquist();
for (int k = 0; k < nFrequencies; ++k)
frequency[k] = narrowPrecisionToFloat(frequencyHz[k] / nyquist);
updateCoefficientsIfNecessary(false, true);
m_biquad.getFrequencyResponse(nFrequencies, frequency.data(), magResponse, phaseResponse);
}
Commit Message: Initialize value since calculateFinalValues may fail to do so.
Fix threading issue where updateCoefficientsIfNecessary was not always
called from the audio thread. This causes the value not to be
initialized.
Thus,
o Initialize the variable to some value, just in case.
o Split updateCoefficientsIfNecessary into two functions with the code
that sets the coefficients pulled out in to the new function
updateCoefficients.
o Simplify updateCoefficientsIfNecessary since useSmoothing was always
true, and forceUpdate is not longer needed.
o Add process lock to prevent the audio thread from updating the
coefficients while they are being read in the main thread. The audio
thread will update them the next time around.
o Make getFrequencyResponse set the lock while reading the
coefficients of the biquad in preparation for computing the
frequency response.
BUG=389219
Review URL: https://codereview.chromium.org/354213002
git-svn-id: svn://svn.chromium.org/blink/trunk@177250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | void BiquadDSPKernel::getFrequencyResponse(int nFrequencies,
const float* frequencyHz,
float* magResponse,
float* phaseResponse)
{
bool isGood = nFrequencies > 0 && frequencyHz && magResponse && phaseResponse;
ASSERT(isGood);
if (!isGood)
return;
Vector<float> frequency(nFrequencies);
double nyquist = this->nyquist();
for (int k = 0; k < nFrequencies; ++k)
frequency[k] = narrowPrecisionToFloat(frequencyHz[k] / nyquist);
double cutoffFrequency;
double Q;
double gain;
double detune; // in Cents
{
// Get a copy of the current biquad filter coefficients so we can update the biquad with
// these values. We need to synchronize with process() to prevent process() from updating
// the filter coefficients while we're trying to access them. The process will update it
// next time around.
//
// The BiquadDSPKernel object here (along with it's Biquad object) is for querying the
// frequency response and is NOT the same as the one in process() which is used for
// performing the actual filtering. This one is is created in
// BiquadProcessor::getFrequencyResponse for this purpose. Both, however, point to the same
// BiquadProcessor object.
//
// FIXME: Simplify this: crbug.com/390266
MutexLocker processLocker(m_processLock);
cutoffFrequency = biquadProcessor()->parameter1()->value();
Q = biquadProcessor()->parameter2()->value();
gain = biquadProcessor()->parameter3()->value();
detune = biquadProcessor()->parameter4()->value();
}
updateCoefficients(cutoffFrequency, Q, gain, detune);
m_biquad.getFrequencyResponse(nFrequencies, frequency.data(), magResponse, phaseResponse);
}
| 171,660 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheUpdateJob::HandleMasterEntryFetchCompleted(
URLFetcher* fetcher) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
net::URLRequest* request = fetcher->request();
const GURL& url = request->original_url();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = request->status().is_success()
? request->GetResponseCode() : -1;
PendingMasters::iterator found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
AppCacheEntry master_entry(AppCacheEntry::MASTER,
fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written());
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
(*host_it)->AssociateCompleteCache(cache);
}
}
} else {
HostNotifier host_notifier;
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
AppCacheHost* host = *host_it;
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
const char* kFormatString = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->url(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(
AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/),
fetcher->result(),
GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
Commit Message: AppCache: fix a browser crashing bug that can happen during updates.
BUG=558589
Review URL: https://codereview.chromium.org/1463463003
Cr-Commit-Position: refs/heads/master@{#360967}
CWE ID: | void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(
URLFetcher* fetcher) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
net::URLRequest* request = fetcher->request();
const GURL& url = request->original_url();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = request->status().is_success()
? request->GetResponseCode() : -1;
PendingMasters::iterator found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
AppCacheEntry master_entry(AppCacheEntry::MASTER,
fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written());
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
(*host_it)->AssociateCompleteCache(cache);
}
}
} else {
HostNotifier host_notifier;
for (PendingHosts::iterator host_it = hosts.begin();
host_it != hosts.end(); ++host_it) {
AppCacheHost* host = *host_it;
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
failed_master_entries_.insert(url);
const char* kFormatString = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->url(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(
AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(AppCacheErrorDetails(message,
APPCACHE_MANIFEST_ERROR,
request->url(),
response_code,
false /*is_cross_origin*/),
fetcher->result(),
GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
| 171,732 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LauncherView::LauncherView(LauncherModel* model,
LauncherDelegate* delegate,
ShelfLayoutManager* shelf_layout_manager)
: model_(model),
delegate_(delegate),
view_model_(new views::ViewModel),
last_visible_index_(-1),
overflow_button_(NULL),
dragging_(false),
drag_view_(NULL),
drag_offset_(0),
start_drag_index_(-1),
context_menu_id_(0),
alignment_(SHELF_ALIGNMENT_BOTTOM) {
DCHECK(model_);
bounds_animator_.reset(new views::BoundsAnimator(this));
bounds_animator_->AddObserver(this);
set_context_menu_controller(this);
focus_search_.reset(new LauncherFocusSearch(view_model_.get()));
tooltip_.reset(new LauncherTooltipManager(alignment_, shelf_layout_manager));
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | LauncherView::LauncherView(LauncherModel* model,
LauncherDelegate* delegate,
ShelfLayoutManager* shelf_layout_manager)
: model_(model),
delegate_(delegate),
view_model_(new views::ViewModel),
first_visible_index_(0),
last_visible_index_(-1),
overflow_button_(NULL),
dragging_(false),
drag_view_(NULL),
drag_offset_(0),
start_drag_index_(-1),
context_menu_id_(0),
alignment_(SHELF_ALIGNMENT_BOTTOM),
leading_inset_(kDefaultLeadingInset) {
DCHECK(model_);
bounds_animator_.reset(new views::BoundsAnimator(this));
bounds_animator_->AddObserver(this);
set_context_menu_controller(this);
focus_search_.reset(new LauncherFocusSearch(view_model_.get()));
tooltip_.reset(new LauncherTooltipManager(alignment_, shelf_layout_manager));
}
| 170,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4 &&
!(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125 | static int piv_match_card_continued(sc_card_t *card)
{
int i;
int type = -1;
piv_private_data_t *priv = NULL;
int saved_type = card->type;
/* Since we send an APDU, the card's logout function may be called...
* however it may be in dirty memory */
card->ops->logout = NULL;
/* piv_match_card may be called with card->type, set by opensc.conf */
/* user provide card type must be one we know */
switch (card->type) {
case -1:
case SC_CARD_TYPE_PIV_II_GENERIC:
case SC_CARD_TYPE_PIV_II_HIST:
case SC_CARD_TYPE_PIV_II_NEO:
case SC_CARD_TYPE_PIV_II_YUBIKEY4:
case SC_CARD_TYPE_PIV_II_GI_DE:
type = card->type;
break;
default:
return 0; /* can not handle the card */
}
if (type == -1) {
/*
*try to identify card by ATR or historical data in ATR
* currently all PIV card will respond to piv_find_aid
* the same. But in future may need to know card type first,
* so do it here.
*/
if (card->reader->atr_info.hist_bytes != NULL) {
if (card->reader->atr_info.hist_bytes_len == 8 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey4", 8))) {
type = SC_CARD_TYPE_PIV_II_YUBIKEY4;
}
else if (card->reader->atr_info.hist_bytes_len >= 7 &&
!(memcmp(card->reader->atr_info.hist_bytes, "Yubikey", 7))) {
type = SC_CARD_TYPE_PIV_II_NEO;
}
/*
* https://csrc.nist.gov/csrc/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp1239.pdf
* lists 2 ATRS with historical bytes:
* 73 66 74 65 2D 63 64 30 38 30
* 73 66 74 65 20 63 64 31 34 34
* will check for 73 66 74 65
*/
else if (card->reader->atr_info.hist_bytes_len >= 4
&& !(memcmp(card->reader->atr_info.hist_bytes, "sfte", 4))) {
type = SC_CARD_TYPE_PIV_II_GI_DE;
}
else if (card->reader->atr_info.hist_bytes_len > 0
&& card->reader->atr_info.hist_bytes[0] == 0x80u) { /* compact TLV */
size_t datalen;
const u8 *data = sc_compacttlv_find_tag(card->reader->atr_info.hist_bytes + 1,
card->reader->atr_info.hist_bytes_len - 1,
0xF0, &datalen);
if (data != NULL) {
int k;
for (k = 0; piv_aids[k].len_long != 0; k++) {
if (datalen == piv_aids[k].len_long
&& !memcmp(data, piv_aids[k].value, datalen)) {
type = SC_CARD_TYPE_PIV_II_HIST;
break;
}
}
}
}
}
if (type == -1)
type = SC_CARD_TYPE_PIV_II_GENERIC;
}
/* allocate and init basic fields */
priv = calloc(1, sizeof(piv_private_data_t));
if (!priv)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
if (card->type == -1)
card->type = type;
card->drv_data = priv; /* will free if no match, or pass on to piv_init */
priv->aid_file = sc_file_new();
priv->selected_obj = -1;
priv->pin_preference = 0x80; /* 800-73-3 part 1, table 3 */
priv->logged_in = SC_PIN_STATE_UNKNOWN;
priv->tries_left = 10; /* will assume OK at start */
priv->pstate = PIV_STATE_MATCH;
/* Some objects will only be present if History object says so */
for (i=0; i < PIV_OBJ_LAST_ENUM -1; i++)
if(piv_objects[i].flags & PIV_OBJECT_NOT_PRESENT)
priv->obj_cache[i].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
sc_lock(card);
/*
* detect if active AID is PIV. NIST 800-73 says Only one PIV application per card
* and PIV must be the default application
* This can avoid doing doing a select_aid and losing the login state on some cards
* We may get interference on some cards by other drivers trying SELECT_AID before
* we get to see if PIV application is still active.
* putting PIV driver first might help.
* This may fail if the wrong AID is active
*/
i = piv_find_discovery(card);
if (i < 0) {
/* Detect by selecting applet */
sc_file_t aidfile;
i = piv_find_aid(card, &aidfile);
}
if (i >= 0) {
/*
* We now know PIV AID is active, test DISCOVERY object
* Some CAC cards with PIV don't support DISCOVERY and return
* SC_ERROR_INCORRECT_PARAMETERS. Any error other then
* SC_ERROR_FILE_NOT_FOUND means we cannot use discovery
* to test for active AID.
*/
int i7e = piv_find_discovery(card);
if (i7e != 0 && i7e != SC_ERROR_FILE_NOT_FOUND) {
priv->card_issues |= CI_DISCOVERY_USELESS;
priv->obj_cache[PIV_OBJ_DISCOVERY].flags |= PIV_OBJ_CACHE_NOT_PRESENT;
}
}
if (i < 0) {
/* don't match. Does not have a PIV applet. */
sc_unlock(card);
piv_finish(card);
card->type = saved_type;
return 0;
}
/* Matched, caller will use or free priv and sc_lock as needed */
priv->pstate=PIV_STATE_INIT;
return 1; /* match */
}
| 169,062 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MaintainContentLengthPrefsForDateChange(
base::ListValue* original_update,
base::ListValue* received_update,
int days_since_last_update) {
if (days_since_last_update == -1) {
days_since_last_update = 0;
} else if (days_since_last_update < -1) {
original_update->Clear();
received_update->Clear();
days_since_last_update = kNumDaysInHistory;
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
}
DCHECK_GE(days_since_last_update, 0);
for (int i = 0;
i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory);
++i) {
original_update->AppendString(base::Int64ToString(0));
received_update->AppendString(base::Int64ToString(0));
}
MaintainContentLengthPrefsWindow(original_update, kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update, kNumDaysInHistory);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416 | void MaintainContentLengthPrefsForDateChange(
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
class DailyContentLengthUpdate {
public:
DailyContentLengthUpdate(
const char* pref,
PrefService* pref_service)
: update_(pref_service, pref) {
}
void UpdateForDataChange(int days_since_last_update) {
// New empty lists may have been created. Maintain the invariant that
// there should be exactly |kNumDaysInHistory| days in the histories.
MaintainContentLengthPrefsWindow(update_.Get(), kNumDaysInHistory);
if (days_since_last_update) {
MaintainContentLengthPrefForDateChange(days_since_last_update);
}
}
| 171,325 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BackendIO::ExecuteBackendOperation() {
switch (operation_) {
case OP_INIT:
result_ = backend_->SyncInit();
break;
case OP_OPEN: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_CREATE: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncCreateEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_DOOM:
result_ = backend_->SyncDoomEntry(key_);
break;
case OP_DOOM_ALL:
result_ = backend_->SyncDoomAllEntries();
break;
case OP_DOOM_BETWEEN:
result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_);
break;
case OP_DOOM_SINCE:
result_ = backend_->SyncDoomEntriesSince(initial_time_);
break;
case OP_SIZE_ALL:
result_ = backend_->SyncCalculateSizeOfAllEntries();
break;
case OP_OPEN_NEXT: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenNextEntry(iterator_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_END_ENUMERATION:
backend_->SyncEndEnumeration(std::move(scoped_iterator_));
result_ = net::OK;
break;
case OP_ON_EXTERNAL_CACHE_HIT:
backend_->SyncOnExternalCacheHit(key_);
result_ = net::OK;
break;
case OP_CLOSE_ENTRY:
entry_->Release();
result_ = net::OK;
break;
case OP_DOOM_ENTRY:
entry_->DoomImpl();
result_ = net::OK;
break;
case OP_FLUSH_QUEUE:
result_ = net::OK;
break;
case OP_RUN_TASK:
task_.Run();
result_ = net::OK;
break;
default:
NOTREACHED() << "Invalid Operation";
result_ = net::ERR_UNEXPECTED;
}
DCHECK_NE(net::ERR_IO_PENDING, result_);
NotifyController();
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20 | void BackendIO::ExecuteBackendOperation() {
switch (operation_) {
case OP_INIT:
result_ = backend_->SyncInit();
break;
case OP_OPEN: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_CREATE: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncCreateEntry(key_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_DOOM:
result_ = backend_->SyncDoomEntry(key_);
break;
case OP_DOOM_ALL:
result_ = backend_->SyncDoomAllEntries();
break;
case OP_DOOM_BETWEEN:
result_ = backend_->SyncDoomEntriesBetween(initial_time_, end_time_);
break;
case OP_DOOM_SINCE:
result_ = backend_->SyncDoomEntriesSince(initial_time_);
break;
case OP_SIZE_ALL:
result_ = backend_->SyncCalculateSizeOfAllEntries();
break;
case OP_OPEN_NEXT: {
scoped_refptr<EntryImpl> entry;
result_ = backend_->SyncOpenNextEntry(iterator_, &entry);
*entry_ptr_ = LeakEntryImpl(std::move(entry));
break;
}
case OP_END_ENUMERATION:
backend_->SyncEndEnumeration(std::move(scoped_iterator_));
result_ = net::OK;
break;
case OP_ON_EXTERNAL_CACHE_HIT:
backend_->SyncOnExternalCacheHit(key_);
result_ = net::OK;
break;
case OP_CLOSE_ENTRY:
entry_->Release();
result_ = net::OK;
break;
case OP_DOOM_ENTRY:
entry_->DoomImpl();
result_ = net::OK;
break;
case OP_FLUSH_QUEUE:
result_ = net::OK;
break;
case OP_RUN_TASK:
task_.Run();
result_ = net::OK;
break;
default:
NOTREACHED() << "Invalid Operation";
result_ = net::ERR_UNEXPECTED;
}
DCHECK_NE(net::ERR_IO_PENDING, result_);
NotifyController();
backend_->OnSyncBackendOpComplete();
}
| 172,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid)
{
const char *perm = "add";
return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0;
}
Commit Message: ServiceManager: Restore basic uid check
Prevent apps from registering services without relying on selinux checks.
Bug: 29431260
Change-Id: I38c6e8bc7f7cba1cbd3568e8fed1ae7ac2054a9b
(cherry picked from commit 2b74d2c1d2a2c1bb6e9c420f7e9b339ba2a95179)
CWE ID: CWE-264 | static int svc_can_register(const uint16_t *name, size_t name_len, pid_t spid, uid_t uid)
{
const char *perm = "add";
if (uid >= AID_APP) {
return 0; /* Don't allow apps to register services */
}
return check_mac_perms_from_lookup(spid, uid, perm, str8(name, name_len)) ? 1 : 0;
}
| 174,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: static int xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr = avpkt->data;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
end = avpkt->data + avpkt->size;
while (memcmp(ptr, "/* XPM */", 9) && ptr < end - 9)
ptr++;
if (ptr >= end) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 94;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
ptr += mod_strcspn(ptr, "\"") + 1;
for (j = 0; j < avctx->width; j++) {
if (ptr + cpp > end)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues
Most of these were found through code review in response to
fixing 1466/clusterfuzz-testcase-minimized-5961584419536896
There is thus no testcase for most of this.
The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int xpm_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
XPMDecContext *x = avctx->priv_data;
AVFrame *p=data;
const uint8_t *end, *ptr;
int ncolors, cpp, ret, i, j;
int64_t size;
uint32_t *dst;
avctx->pix_fmt = AV_PIX_FMT_BGRA;
av_fast_padded_malloc(&x->buf, &x->buf_size, avpkt->size);
if (!x->buf)
return AVERROR(ENOMEM);
memcpy(x->buf, avpkt->data, avpkt->size);
x->buf[avpkt->size] = 0;
ptr = x->buf;
end = x->buf + avpkt->size;
while (end - ptr > 9 && memcmp(ptr, "/* XPM */", 9))
ptr++;
if (end - ptr <= 9) {
av_log(avctx, AV_LOG_ERROR, "missing signature\n");
return AVERROR_INVALIDDATA;
}
ptr += mod_strcspn(ptr, "\"");
if (sscanf(ptr, "\"%u %u %u %u\",",
&avctx->width, &avctx->height, &ncolors, &cpp) != 4) {
av_log(avctx, AV_LOG_ERROR, "missing image parameters\n");
return AVERROR_INVALIDDATA;
}
if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0)
return ret;
if ((ret = ff_get_buffer(avctx, p, 0)) < 0)
return ret;
if (cpp <= 0 || cpp >= 5) {
av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp);
return AVERROR_INVALIDDATA;
}
size = 1;
for (i = 0; i < cpp; i++)
size *= 95;
if (ncolors <= 0 || ncolors > size) {
av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors);
return AVERROR_INVALIDDATA;
}
size *= 4;
av_fast_padded_malloc(&x->pixels, &x->pixels_size, size);
if (!x->pixels)
return AVERROR(ENOMEM);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (i = 0; i < ncolors; i++) {
const uint8_t *index;
int len;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
index = ptr;
ptr += cpp;
ptr = strstr(ptr, "c ");
if (ptr) {
ptr += 2;
} else {
return AVERROR_INVALIDDATA;
}
len = strcspn(ptr, "\" ");
if ((ret = ascii2index(index, cpp)) < 0)
return ret;
x->pixels[ret] = color_string_to_rgba(ptr, len);
ptr += mod_strcspn(ptr, ",") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
}
for (i = 0; i < avctx->height; i++) {
dst = (uint32_t *)(p->data[0] + i * p->linesize[0]);
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
ptr += mod_strcspn(ptr, "\"") + 1;
if (end - ptr < 1)
return AVERROR_INVALIDDATA;
for (j = 0; j < avctx->width; j++) {
if (end - ptr < cpp)
return AVERROR_INVALIDDATA;
if ((ret = ascii2index(ptr, cpp)) < 0)
return ret;
*dst++ = x->pixels[ret];
ptr += cpp;
}
ptr += mod_strcspn(ptr, ",") + 1;
}
p->key_frame = 1;
p->pict_type = AV_PICTURE_TYPE_I;
*got_frame = 1;
return avpkt->size;
}
| 168,078 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
Commit Message: Include U+0517 in set of Cyrillic/Latin lookalikes.
Cyrillic letter U+0517 (ԗ) looks somewhat similar to the Latin letter p.
This CL adds this character to the set of Cyrillic characters that look
like Latin characters. Domains made up entirely of Cyrillic/Latin
lookalikes are displayed as punycode in URLs.
Bug: 863663
Change-Id: I4340c48d124c9c4cd3d3b5d0f9d3865d709e082d
Reviewed-on: https://chromium-review.googlesource.com/c/1286825
Commit-Queue: Joe DeBlasio <[email protected]>
Commit-Queue: Peter Kasting <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#600582}
CWE ID: CWE-20 | IDNSpoofChecker::IDNSpoofChecker() {
UErrorCode status = U_ZERO_ERROR;
checker_ = uspoof_open(&status);
if (U_FAILURE(status)) {
checker_ = nullptr;
return;
}
uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE);
SetAllowedUnicodeSet(&status);
int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO;
uspoof_setChecks(checker_, checks, &status);
deviation_characters_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status);
deviation_characters_.freeze();
non_ascii_latin_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status);
non_ascii_latin_letters_.freeze();
kana_letters_exceptions_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"),
status);
kana_letters_exceptions_.freeze();
combining_diacritics_exceptions_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status);
combining_diacritics_exceptions_.freeze();
cyrillic_letters_latin_alike_ = icu::UnicodeSet(
icu::UnicodeString::fromUTF8("[асԁеһіјӏорԗԛѕԝхуъЬҽпгѵѡ]"), status);
cyrillic_letters_latin_alike_.freeze();
cyrillic_letters_ =
icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status);
cyrillic_letters_.freeze();
DCHECK(U_SUCCESS(status));
lgc_letters_n_ascii_ = icu::UnicodeSet(
UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_"
"\\u002d][\\u0300-\\u0339]]"),
status);
lgc_letters_n_ascii_.freeze();
UParseError parse_error;
diacritic_remover_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("DropAcc"),
icu::UnicodeString::fromUTF8("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;"
" ł > l; ø > o; đ > d;"),
UTRANS_FORWARD, parse_error, status));
extra_confusable_mapper_.reset(icu::Transliterator::createFromRules(
UNICODE_STRING_SIMPLE("ExtraConf"),
icu::UnicodeString::fromUTF8(
"[æӕ] > ae; [þϼҏ] > p; [ħнћңҥӈӊԋԧԩ] > h;"
"[ĸκкқҝҟҡӄԟ] > k; [ŋпԥก] > n; œ > ce;"
"[ŧтҭԏ] > t; [ƅьҍв] > b; [ωшщพฟພຟ] > w;"
"[мӎ] > m; [єҽҿၔ] > e; ґ > r; [ғӻ] > f;"
"[ҫင] > c; ұ > y; [χҳӽӿ] > x;"
"ԃ > d; [ԍဌ] > g; [ടรຣຮ] > s; ၂ > j;"
"[зҙӡउওဒვპ] > 3; [บບ] > u"),
UTRANS_FORWARD, parse_error, status));
DCHECK(U_SUCCESS(status))
<< "Spoofchecker initalization failed due to an error: "
<< u_errorName(status);
}
| 173,116 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TextAutosizer::processSubtree(RenderObject* layoutRoot)
{
if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page())
return false;
Frame* mainFrame = m_document->page()->mainFrame();
TextAutosizingWindowInfo windowInfo;
windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride();
if (windowInfo.windowSize.isEmpty()) {
bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame);
windowInfo.windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size(); // FIXME: Check that this is always in logical (density-independent) pixels (see wkbug.com/87440).
}
windowInfo.minLayoutSize = mainFrame->view()->layoutSize();
for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent()) {
if (!frame->view()->isInChildFrameWithFrameFlattening())
windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize());
}
RenderBlock* container = layoutRoot->isRenderBlock() ? toRenderBlock(layoutRoot) : layoutRoot->containingBlock();
while (container && !isAutosizingContainer(container))
container = container->containingBlock();
RenderBlock* cluster = container;
while (cluster && (!isAutosizingContainer(cluster) || !isAutosizingCluster(cluster)))
cluster = cluster->containingBlock();
processCluster(cluster, container, layoutRoot, windowInfo);
return true;
}
Commit Message: Text Autosizing: Counteract funky window sizing on Android.
https://bugs.webkit.org/show_bug.cgi?id=98809
Reviewed by Adam Barth.
In Chrome for Android, the window sizes provided to WebCore are
currently in physical screen pixels instead of
device-scale-adjusted units. For example window width on a
Galaxy Nexus is 720 instead of 360. Text autosizing expects
device-independent pixels. When Chrome for Android cuts over to
the new coordinate space, it will be tied to the setting
applyPageScaleFactorInCompositor.
No new tests.
* rendering/TextAutosizer.cpp:
(WebCore::TextAutosizer::processSubtree):
git-svn-id: svn://svn.chromium.org/blink/trunk@130866 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
{
if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page())
return false;
Frame* mainFrame = m_document->page()->mainFrame();
TextAutosizingWindowInfo windowInfo;
windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride();
if (windowInfo.windowSize.isEmpty()) {
bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame);
windowInfo.windowSize = mainFrame->view()->visibleContentRect(includeScrollbars).size();
if (!m_document->settings()->applyPageScaleFactorInCompositor())
windowInfo.windowSize.scale(1 / m_document->page()->deviceScaleFactor());
}
windowInfo.minLayoutSize = mainFrame->view()->layoutSize();
for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent()) {
if (!frame->view()->isInChildFrameWithFrameFlattening())
windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize());
}
RenderBlock* container = layoutRoot->isRenderBlock() ? toRenderBlock(layoutRoot) : layoutRoot->containingBlock();
while (container && !isAutosizingContainer(container))
container = container->containingBlock();
RenderBlock* cluster = container;
while (cluster && (!isAutosizingContainer(cluster) || !isAutosizingCluster(cluster)))
cluster = cluster->containingBlock();
processCluster(cluster, container, layoutRoot, windowInfo);
return true;
}
| 170,248 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,
__be32 saddr, __be32 daddr, struct ip_options *opt)
{
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = skb_rtable(skb);
struct iphdr *iph;
/* Build the IP header. */
skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 5;
iph->tos = inet->tos;
if (ip_dont_fragment(sk, &rt->dst))
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->ttl = ip_select_ttl(inet, &rt->dst);
iph->daddr = rt->rt_dst;
iph->saddr = rt->rt_src;
iph->protocol = sk->sk_protocol;
ip_select_ident(iph, &rt->dst, sk);
if (opt && opt->optlen) {
iph->ihl += opt->optlen>>2;
ip_options_build(skb, opt, daddr, rt, 0);
}
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
/* Send it out. */
return ip_local_out(skb);
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,
__be32 saddr, __be32 daddr, struct ip_options_rcu *opt)
{
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = skb_rtable(skb);
struct iphdr *iph;
/* Build the IP header. */
skb_push(skb, sizeof(struct iphdr) + (opt ? opt->opt.optlen : 0));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 5;
iph->tos = inet->tos;
if (ip_dont_fragment(sk, &rt->dst))
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->ttl = ip_select_ttl(inet, &rt->dst);
iph->daddr = rt->rt_dst;
iph->saddr = rt->rt_src;
iph->protocol = sk->sk_protocol;
ip_select_ident(iph, &rt->dst, sk);
if (opt && opt->opt.optlen) {
iph->ihl += opt->opt.optlen>>2;
ip_options_build(skb, &opt->opt, daddr, rt, 0);
}
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
/* Send it out. */
return ip_local_out(skb);
}
| 165,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: parse_wcc_attr(netdissect_options *ndo,
const uint32_t *dp)
{
ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0])));
ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u",
EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5])));
return (dp + 6);
}
Commit Message: CVE-2017-12898/NFS: Fix bounds checking.
Fix the bounds checking for the NFSv3 WRITE procedure to check whether the
length of the opaque data being written is present in the captured data,
not just whether the byte count is present in the captured data.
furthest forward in the packet, not the item before it. (This also lets
us eliminate the check for the "stable" argument being present in the
captured data; rewrite the code to print that to make it a bit clearer.)
Check that the entire ar_stat field is present in the capture.
Note that parse_wcc_attr() is called after we've already checked whether
the wcc_data is present.
Check before fetching the "access" part of the NFSv3 ACCESS results.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Include a test for the "check before fetching the "access" part..." fix,
using the capture supplied by the reporter(s).
CWE ID: CWE-125 | parse_wcc_attr(netdissect_options *ndo,
const uint32_t *dp)
{
/* Our caller has already checked this */
ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0])));
ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u",
EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]),
EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5])));
return (dp + 6);
}
| 167,940 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ns_nprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp)
{
register u_int i, l;
register const u_char *rp = NULL;
register int compress = 0;
int chars_processed;
int elt;
int data_size = ndo->ndo_snapend - bp;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
chars_processed = 1;
if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) {
compress = 0;
rp = cp + l;
}
if (i != 0)
while (i && cp < ndo->ndo_snapend) {
if ((i & INDIR_MASK) == INDIR_MASK) {
if (!compress) {
rp = cp + 1;
compress = 1;
}
if (!ND_TTEST2(*cp, 1))
return(NULL);
cp = bp + (((i << 8) | *cp) & 0x3fff);
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
/*
* If we've looked at every character in
* the message, this pointer will make
* us look at some character again,
* which means we're looping.
*/
if (chars_processed >= data_size) {
ND_PRINT((ndo, "<LOOP>"));
return (NULL);
}
continue;
}
if ((i & INDIR_MASK) == EDNS0_MASK) {
elt = (i & ~INDIR_MASK);
switch(elt) {
case EDNS0_ELT_BITLABEL:
if (blabel_print(ndo, cp) == NULL)
return (NULL);
break;
default:
/* unknown ELT */
ND_PRINT((ndo, "<ELT %d>", elt));
return(NULL);
}
} else {
if (fn_printn(ndo, cp, l, ndo->ndo_snapend))
return(NULL);
}
cp += l;
chars_processed += l;
ND_PRINT((ndo, "."));
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
chars_processed++;
if (!compress)
rp += l + 1;
}
else
ND_PRINT((ndo, "."));
return (rp);
}
Commit Message: CVE-2017-12995/Check for DNS compression pointers that don't point backwards.
This is what BIND 9.11.0-P2 does; it not only detects pointers that
loop, as "point backwards" means "point before anything we've processed
so far, including what we're processing right now", so the pointer can't
point to itself (as that's what we're processing right now).
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
Also, add some infinite-pointer-loop captures.
More checks should be done. We might, for example, want to make sure
the upper 2 bits of the label length/pointer byte are 00 or 11, and that
if we encounter a pointer and jump backwards to what we think is a label
the label ends before the beginning of the last label we processed, to
make sure the pointer doesn't point backwards into the *middle* of a
label, and also make sure the entire name is <= 255 bytes long.
CWE ID: CWE-835 | ns_nprint(netdissect_options *ndo,
register const u_char *cp, register const u_char *bp)
{
register u_int i, l;
register const u_char *rp = NULL;
register int compress = 0;
int elt;
u_int offset, max_offset;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
max_offset = (u_int)(cp - bp);
if (((i = *cp++) & INDIR_MASK) != INDIR_MASK) {
compress = 0;
rp = cp + l;
}
if (i != 0)
while (i && cp < ndo->ndo_snapend) {
if ((i & INDIR_MASK) == INDIR_MASK) {
if (!compress) {
rp = cp + 1;
compress = 1;
}
if (!ND_TTEST2(*cp, 1))
return(NULL);
offset = (((i << 8) | *cp) & 0x3fff);
/*
* This must move backwards in the packet.
* No RFC explicitly says that, but BIND's
* name decompression code requires it,
* as a way of preventing infinite loops
* and other bad behavior, and it's probably
* what was intended (compress by pointing
* to domain name suffixes already seen in
* the packet).
*/
if (offset >= max_offset) {
ND_PRINT((ndo, "<BAD PTR>"));
return(NULL);
}
max_offset = offset;
cp = bp + offset;
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
continue;
}
if ((i & INDIR_MASK) == EDNS0_MASK) {
elt = (i & ~INDIR_MASK);
switch(elt) {
case EDNS0_ELT_BITLABEL:
if (blabel_print(ndo, cp) == NULL)
return (NULL);
break;
default:
/* unknown ELT */
ND_PRINT((ndo, "<ELT %d>", elt));
return(NULL);
}
} else {
if (fn_printn(ndo, cp, l, ndo->ndo_snapend))
return(NULL);
}
cp += l;
ND_PRINT((ndo, "."));
if ((l = labellen(ndo, cp)) == (u_int)-1)
return(NULL);
if (!ND_TTEST2(*cp, 1))
return(NULL);
i = *cp++;
if (!compress)
rp += l + 1;
}
else
ND_PRINT((ndo, "."));
return (rp);
}
| 167,912 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
DCHECK(thread_checker_.CalledOnValidThread());
return true;
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | bool DataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
| 172,641 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 gboolean nbd_negotiate_continue(QIOChannel *ioc,
GIOCondition condition,
void *opaque)
{
qemu_coroutine_enter(opaque);
return TRUE;
}
Commit Message:
CWE ID: CWE-20 | static gboolean nbd_negotiate_continue(QIOChannel *ioc,
| 165,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: void PeopleHandler::HandleSignout(const base::ListValue* args) {
bool delete_profile = false;
args->GetBoolean(0, &delete_profile);
if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) {
DCHECK(delete_profile);
} else {
SigninManager* signin_manager =
SigninManagerFactory::GetForProfile(profile_);
if (signin_manager->IsAuthenticated()) {
if (GetSyncService())
ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS);
signin_metrics::SignoutDelete delete_metric =
delete_profile ? signin_metrics::SignoutDelete::DELETED
: signin_metrics::SignoutDelete::KEEPING;
signin_manager->SignOutAndRemoveAllAccounts(
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
} else {
DCHECK(!delete_profile)
<< "Deleting the profile should only be offered the user is syncing.";
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
->RevokeAllCredentials();
}
}
if (delete_profile) {
webui::DeleteProfileAtPath(profile_->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void PeopleHandler::HandleSignout(const base::ListValue* args) {
bool delete_profile = false;
args->GetBoolean(0, &delete_profile);
if (!signin_util::IsUserSignoutAllowedForProfile(profile_)) {
DCHECK(delete_profile);
} else {
SigninManager* signin_manager =
SigninManagerFactory::GetForProfile(profile_);
if (signin_manager->IsAuthenticated()) {
if (GetSyncService())
ProfileSyncService::SyncEvent(ProfileSyncService::STOP_FROM_OPTIONS);
signin_metrics::SignoutDelete delete_metric =
delete_profile ? signin_metrics::SignoutDelete::DELETED
: signin_metrics::SignoutDelete::KEEPING;
signin_manager->SignOutAndRemoveAllAccounts(
signin_metrics::USER_CLICKED_SIGNOUT_SETTINGS, delete_metric);
} else {
DCHECK(!delete_profile)
<< "Deleting the profile should only be offered the user is syncing.";
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
->RevokeAllCredentials(
signin_metrics::SourceForRefreshTokenOperation::
kSettings_Signout);
}
}
if (delete_profile) {
webui::DeleteProfileAtPath(profile_->GetPath(),
ProfileMetrics::DELETE_PROFILE_SETTINGS);
}
}
| 172,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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* Chapters::Atom::GetStringUID() const
{
return m_string_uid;
}
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* Chapters::Atom::GetStringUID() const
| 174,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DOMWindow::focus(LocalDOMWindow* incumbent_window) {
if (!GetFrame())
return;
Page* page = GetFrame()->GetPage();
if (!page)
return;
DCHECK(incumbent_window);
ExecutionContext* incumbent_execution_context =
incumbent_window->GetExecutionContext();
bool allow_focus = incumbent_execution_context->IsWindowInteractionAllowed();
if (allow_focus) {
incumbent_execution_context->ConsumeWindowInteraction();
} else {
DCHECK(IsMainThread());
allow_focus =
opener() && (opener() != this) &&
(ToDocument(incumbent_execution_context)->domWindow() == opener());
}
if (GetFrame()->IsMainFrame() && allow_focus)
page->GetChromeClient().Focus();
page->GetFocusController().FocusDocumentView(GetFrame(),
true /* notifyEmbedder */);
}
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 DOMWindow::focus(LocalDOMWindow* incumbent_window) {
if (!GetFrame())
return;
Page* page = GetFrame()->GetPage();
if (!page)
return;
DCHECK(incumbent_window);
ExecutionContext* incumbent_execution_context =
incumbent_window->GetExecutionContext();
bool allow_focus = incumbent_execution_context->IsWindowInteractionAllowed();
if (allow_focus) {
incumbent_execution_context->ConsumeWindowInteraction();
} else {
DCHECK(IsMainThread());
allow_focus =
opener() && (opener() != this) &&
(ToDocument(incumbent_execution_context)->domWindow() == opener());
}
if (GetFrame()->IsMainFrame() && allow_focus)
page->GetChromeClient().Focus(incumbent_window->GetFrame());
page->GetFocusController().FocusDocumentView(GetFrame(),
true /* notifyEmbedder */);
}
| 172,722 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((p > (datum+length-count)) || (count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
Commit Message: Fixed SEGV reported in https://github.com/ImageMagick/ImageMagick/issues/130
CWE ID: CWE-20 | static void WriteTo8BimProfile(Image *image,const char *name,
const StringInfo *profile)
{
const unsigned char
*datum,
*q;
register const unsigned char
*p;
size_t
length;
StringInfo
*profile_8bim;
ssize_t
count;
unsigned char
length_byte;
unsigned int
value;
unsigned short
id,
profile_id;
if (LocaleCompare(name,"icc") == 0)
profile_id=0x040f;
else
if (LocaleCompare(name,"iptc") == 0)
profile_id=0x0404;
else
if (LocaleCompare(name,"xmp") == 0)
profile_id=0x0424;
else
return;
profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *)
image->profiles,"8bim");
if (profile_8bim == (StringInfo *) NULL)
return;
datum=GetStringInfoDatum(profile_8bim);
length=GetStringInfoLength(profile_8bim);
for (p=datum; p < (datum+length-16); )
{
q=p;
if (LocaleNCompare((char *) p,"8BIM",4) != 0)
break;
p+=4;
p=ReadResourceShort(p,&id);
p=ReadResourceByte(p,&length_byte);
p+=length_byte;
if (((length_byte+1) & 0x01) != 0)
p++;
if (p > (datum+length-4))
break;
p=ReadResourceLong(p,&value);
count=(ssize_t) value;
if ((count & 0x01) != 0)
count++;
if ((count < 0) || (p > (datum+length-count)) ||
(count > (ssize_t) length))
break;
if (id != profile_id)
p+=count;
else
{
size_t
extent,
offset;
ssize_t
extract_extent;
StringInfo
*extract_profile;
extract_extent=0;
extent=(datum+length)-(p+count);
if (profile == (StringInfo *) NULL)
{
offset=(q-datum);
extract_profile=AcquireStringInfo(offset+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset);
}
else
{
offset=(p-datum);
extract_extent=profile->length;
if ((extract_extent & 0x01) != 0)
extract_extent++;
extract_profile=AcquireStringInfo(offset+extract_extent+extent);
(void) CopyMagickMemory(extract_profile->datum,datum,offset-4);
(void) WriteResourceLong(extract_profile->datum+offset-4,
(unsigned int) profile->length);
(void) CopyMagickMemory(extract_profile->datum+offset,
profile->datum,profile->length);
}
(void) CopyMagickMemory(extract_profile->datum+offset+extract_extent,
p+count,extent);
(void) AddValueToSplayTree((SplayTreeInfo *) image->profiles,
ConstantString("8bim"),CloneStringInfo(extract_profile));
extract_profile=DestroyStringInfo(extract_profile);
break;
}
}
}
| 168,792 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int headroom;
unsigned int len;
__be16 proto;
bool csum;
int sg = !!(features & NETIF_F_SG);
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
proto = skb_network_protocol(head_skb);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
csum = !!can_checksum_protocol(features, proto);
__skb_push(head_skb, doffset);
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
len = head_skb->len - offset;
if (len > mss)
len = mss;
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
nskb->mac_len = head_skb->mac_len;
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
nskb->ip_summed = CHECKSUM_NONE;
nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
nskb->csum = skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
nskb->ip_summed = CHECKSUM_NONE;
}
} while ((offset += len) < head_skb->len);
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
Commit Message: skbuff: skb_segment: orphan frags before copying
skb_segment copies frags around, so we need
to copy them carefully to avoid accessing
user memory after reporting completion to userspace
through a callback.
skb_segment doesn't normally happen on datapath:
TSO needs to be disabled - so disabling zero copy
in this case does not look like a big deal.
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | struct sk_buff *skb_segment(struct sk_buff *head_skb,
netdev_features_t features)
{
struct sk_buff *segs = NULL;
struct sk_buff *tail = NULL;
struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
skb_frag_t *frag = skb_shinfo(head_skb)->frags;
unsigned int mss = skb_shinfo(head_skb)->gso_size;
unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
struct sk_buff *frag_skb = head_skb;
unsigned int offset = doffset;
unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
unsigned int headroom;
unsigned int len;
__be16 proto;
bool csum;
int sg = !!(features & NETIF_F_SG);
int nfrags = skb_shinfo(head_skb)->nr_frags;
int err = -ENOMEM;
int i = 0;
int pos;
proto = skb_network_protocol(head_skb);
if (unlikely(!proto))
return ERR_PTR(-EINVAL);
csum = !!can_checksum_protocol(features, proto);
__skb_push(head_skb, doffset);
headroom = skb_headroom(head_skb);
pos = skb_headlen(head_skb);
do {
struct sk_buff *nskb;
skb_frag_t *nskb_frag;
int hsize;
int size;
len = head_skb->len - offset;
if (len > mss)
len = mss;
hsize = skb_headlen(head_skb) - offset;
if (hsize < 0)
hsize = 0;
if (hsize > len || !sg)
hsize = len;
if (!hsize && i >= nfrags && skb_headlen(list_skb) &&
(skb_headlen(list_skb) == len || sg)) {
BUG_ON(skb_headlen(list_skb) > len);
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
pos += skb_headlen(list_skb);
while (pos < offset + len) {
BUG_ON(i >= nfrags);
size = skb_frag_size(frag);
if (pos + size > offset + len)
break;
i++;
pos += size;
frag++;
}
nskb = skb_clone(list_skb, GFP_ATOMIC);
list_skb = list_skb->next;
if (unlikely(!nskb))
goto err;
if (unlikely(pskb_trim(nskb, len))) {
kfree_skb(nskb);
goto err;
}
hsize = skb_end_offset(nskb);
if (skb_cow_head(nskb, doffset + headroom)) {
kfree_skb(nskb);
goto err;
}
nskb->truesize += skb_end_offset(nskb) - hsize;
skb_release_head_state(nskb);
__skb_push(nskb, doffset);
} else {
nskb = __alloc_skb(hsize + doffset + headroom,
GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
NUMA_NO_NODE);
if (unlikely(!nskb))
goto err;
skb_reserve(nskb, headroom);
__skb_put(nskb, doffset);
}
if (segs)
tail->next = nskb;
else
segs = nskb;
tail = nskb;
__copy_skb_header(nskb, head_skb);
nskb->mac_len = head_skb->mac_len;
skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
nskb->data - tnl_hlen,
doffset + tnl_hlen);
if (nskb->len == len + doffset)
goto perform_csum_check;
if (!sg) {
nskb->ip_summed = CHECKSUM_NONE;
nskb->csum = skb_copy_and_csum_bits(head_skb, offset,
skb_put(nskb, len),
len, 0);
continue;
}
nskb_frag = skb_shinfo(nskb)->frags;
skb_copy_from_linear_data_offset(head_skb, offset,
skb_put(nskb, hsize), hsize);
skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags &
SKBTX_SHARED_FRAG;
while (pos < offset + len) {
if (i >= nfrags) {
BUG_ON(skb_headlen(list_skb));
i = 0;
nfrags = skb_shinfo(list_skb)->nr_frags;
frag = skb_shinfo(list_skb)->frags;
frag_skb = list_skb;
BUG_ON(!nfrags);
list_skb = list_skb->next;
}
if (unlikely(skb_shinfo(nskb)->nr_frags >=
MAX_SKB_FRAGS)) {
net_warn_ratelimited(
"skb_segment: too many frags: %u %u\n",
pos, mss);
goto err;
}
if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC)))
goto err;
*nskb_frag = *frag;
__skb_frag_ref(nskb_frag);
size = skb_frag_size(nskb_frag);
if (pos < offset) {
nskb_frag->page_offset += offset - pos;
skb_frag_size_sub(nskb_frag, offset - pos);
}
skb_shinfo(nskb)->nr_frags++;
if (pos + size <= offset + len) {
i++;
frag++;
pos += size;
} else {
skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
goto skip_fraglist;
}
nskb_frag++;
}
skip_fraglist:
nskb->data_len = len - hsize;
nskb->len += nskb->data_len;
nskb->truesize += nskb->data_len;
perform_csum_check:
if (!csum) {
nskb->csum = skb_checksum(nskb, doffset,
nskb->len - doffset, 0);
nskb->ip_summed = CHECKSUM_NONE;
}
} while ((offset += len) < head_skb->len);
return segs;
err:
kfree_skb_list(segs);
return ERR_PTR(err);
}
| 166,458 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GetNetworkList(NetworkInterfaceList* networks, int policy) {
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s <= 0) {
PLOG(ERROR) << "socket";
return false;
}
uint32_t num_ifs = 0;
if (ioctl_netc_get_num_ifs(s, &num_ifs) < 0) {
PLOG(ERROR) << "ioctl_netc_get_num_ifs";
PCHECK(close(s) == 0);
return false;
}
for (uint32_t i = 0; i < num_ifs; ++i) {
netc_if_info_t interface;
if (ioctl_netc_get_if_info_at(s, &i, &interface) < 0) {
PLOG(WARNING) << "ioctl_netc_get_if_info_at";
continue;
}
if (internal::IsLoopbackOrUnspecifiedAddress(
reinterpret_cast<sockaddr*>(&(interface.addr)))) {
continue;
}
IPEndPoint address;
if (!address.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.addr)),
sizeof(interface.addr))) {
DLOG(WARNING) << "ioctl_netc_get_if_info returned invalid address.";
continue;
}
int prefix_length = 0;
IPEndPoint netmask;
if (netmask.FromSockAddr(reinterpret_cast<sockaddr*>(&(interface.netmask)),
sizeof(interface.netmask))) {
prefix_length = MaskPrefixLength(netmask.address());
}
int attributes = 0;
networks->push_back(
NetworkInterface(interface.name, interface.name, interface.index,
NetworkChangeNotifier::CONNECTION_UNKNOWN,
address.address(), prefix_length, attributes));
}
PCHECK(close(s) == 0);
return true;
}
Commit Message: Reland "[Fuchsia] Use Netstack FIDL interface to get network interfaces."
This is a reland of b29fc269716e556be6b4e999bb4b24332cc43c6e
Original change's description:
> [Fuchsia] Use Netstack FIDL interface to get network interfaces.
>
> 1. Updated FILD GN template to generate and compile tables file, FIDL
> generated code was failing to link without them.
> 2. Updated GetNetworkList() for Fuchsia to FIDL API instead of ioctl().
>
> Bug: 831384
> Change-Id: Ib90303a5110a465ea5f2bad787a7b63a2bf13f61
> Reviewed-on: https://chromium-review.googlesource.com/1023124
> Commit-Queue: Sergey Ulanov <[email protected]>
> Reviewed-by: James Robinson <[email protected]>
> Reviewed-by: Matt Menke <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554868}
[email protected]
Bug: 831384
Change-Id: Iabb29661680b835b947b2780d169e204fd5e2559
Reviewed-on: https://chromium-review.googlesource.com/1036484
Commit-Queue: Sergey Ulanov <[email protected]>
Reviewed-by: Kevin Marshall <[email protected]>
Cr-Commit-Position: refs/heads/master@{#554946}
CWE ID: CWE-119 | bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
IPAddress NetAddressToIPAddress(const netstack::NetAddress& addr) {
if (addr.ipv4) {
return IPAddress(addr.ipv4->addr.data(), addr.ipv4->addr.count());
}
if (addr.ipv6) {
return IPAddress(addr.ipv6->addr.data(), addr.ipv6->addr.count());
}
return IPAddress();
}
bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
netstack::NetstackSyncPtr netstack =
base::fuchsia::ComponentContext::GetDefault()
->ConnectToServiceSync<netstack::Netstack>();
fidl::VectorPtr<netstack::NetInterface> interfaces;
if (!netstack->GetInterfaces(&interfaces))
return false;
for (auto& interface : interfaces.get()) {
// Check if the interface is up.
if (!(interface.flags & netstack::NetInterfaceFlagUp))
continue;
// Skip loopback.
if (interface.features & netstack::interfaceFeatureLoopback)
continue;
NetworkChangeNotifier::ConnectionType connection_type =
(interface.features & netstack::interfaceFeatureWlan)
? NetworkChangeNotifier::CONNECTION_WIFI
: NetworkChangeNotifier::CONNECTION_UNKNOWN;
// addresses. Currently Netstack doesn't provide this information.
int attributes = 0;
networks->push_back(NetworkInterface(
*interface.name, *interface.name, interface.id, connection_type,
NetAddressToIPAddress(interface.addr),
MaskPrefixLength(NetAddressToIPAddress(interface.netmask)),
attributes));
}
return true;
}
| 171,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: fbCompositeGeneral (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
RegionRec region;
int n;
BoxPtr pbox;
Bool srcRepeat = FALSE;
Bool maskRepeat = FALSE;
int w, h;
CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH*3];
CARD32 *scanline_buffer = _scanline_buffer;
FbComposeData compose_data;
if (pSrc->pDrawable)
srcRepeat = pSrc->repeatType == RepeatNormal && !pSrc->transform
&& (pSrc->pDrawable->width != 1 || pSrc->pDrawable->height != 1);
if (pMask && pMask->pDrawable)
maskRepeat = pMask->repeatType == RepeatNormal && !pMask->transform
&& (pMask->pDrawable->width != 1 || pMask->pDrawable->height != 1);
if (op == PictOpOver && !pMask && !pSrc->transform && !PICT_FORMAT_A(pSrc->format) && !pSrc->alphaMap)
op = PictOpSrc;
if (!miComputeCompositeRegion (®ion,
pSrc,
pMask,
pDst,
xSrc,
ySrc,
xMask,
yMask,
xDst,
yDst,
width,
height))
return;
compose_data.op = op;
compose_data.src = pSrc;
compose_data.mask = pMask;
compose_data.dest = pDst;
if (width > SCANLINE_BUFFER_LENGTH)
scanline_buffer = (CARD32 *) malloc(width * 3 * sizeof(CARD32));
n = REGION_NUM_RECTS (®ion);
pbox = REGION_RECTS (®ion);
while (n--)
{
h = pbox->y2 - pbox->y1;
compose_data.ySrc = pbox->y1 - yDst + ySrc;
compose_data.yMask = pbox->y1 - yDst + yMask;
compose_data.yDest = pbox->y1;
while (h)
{
compose_data.height = h;
w = pbox->x2 - pbox->x1;
compose_data.xSrc = pbox->x1 - xDst + xSrc;
compose_data.xMask = pbox->x1 - xDst + xMask;
compose_data.xDest = pbox->x1;
if (maskRepeat)
{
compose_data.yMask = mod (compose_data.yMask, pMask->pDrawable->height);
if (compose_data.height > pMask->pDrawable->height - compose_data.yMask)
compose_data.height = pMask->pDrawable->height - compose_data.yMask;
}
if (srcRepeat)
{
compose_data.ySrc = mod (compose_data.ySrc, pSrc->pDrawable->height);
if (compose_data.height > pSrc->pDrawable->height - compose_data.ySrc)
compose_data.height = pSrc->pDrawable->height - compose_data.ySrc;
}
while (w)
{
compose_data.width = w;
if (maskRepeat)
{
compose_data.xMask = mod (compose_data.xMask, pMask->pDrawable->width);
if (compose_data.width > pMask->pDrawable->width - compose_data.xMask)
compose_data.width = pMask->pDrawable->width - compose_data.xMask;
}
if (srcRepeat)
{
compose_data.xSrc = mod (compose_data.xSrc, pSrc->pDrawable->width);
if (compose_data.width > pSrc->pDrawable->width - compose_data.xSrc)
compose_data.width = pSrc->pDrawable->width - compose_data.xSrc;
}
fbCompositeRect(&compose_data, scanline_buffer);
w -= compose_data.width;
compose_data.xSrc += compose_data.width;
compose_data.xMask += compose_data.width;
compose_data.xDest += compose_data.width;
}
h -= compose_data.height;
compose_data.ySrc += compose_data.height;
compose_data.yMask += compose_data.height;
compose_data.yDest += compose_data.height;
}
pbox++;
}
REGION_UNINIT (pDst->pDrawable->pScreen, ®ion);
if (scanline_buffer != _scanline_buffer)
free(scanline_buffer);
}
Commit Message:
CWE ID: CWE-189 | fbCompositeGeneral (CARD8 op,
PicturePtr pSrc,
PicturePtr pMask,
PicturePtr pDst,
INT16 xSrc,
INT16 ySrc,
INT16 xMask,
INT16 yMask,
INT16 xDst,
INT16 yDst,
CARD16 width,
CARD16 height)
{
return fbComposite (op, pSrc, pMask, pDst,
xSrc, ySrc, xMask, yMask, xDst, yDst,
width, height);
}
| 165,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: write_png(const char **name, FILE *fp, int color_type, int bit_depth,
volatile png_fixed_point gamma, chunk_insert * volatile insert,
unsigned int filters, unsigned int *colors)
{
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
name, makepng_error, makepng_warning);
volatile png_infop info_ptr = NULL;
volatile png_bytep row = NULL;
if (png_ptr == NULL)
{
fprintf(stderr, "makepng: OOM allocating write structure\n");
return 1;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
png_structp nv_ptr = png_ptr;
png_infop nv_info = info_ptr;
png_ptr = NULL;
info_ptr = NULL;
png_destroy_write_struct(&nv_ptr, &nv_info);
if (row != NULL) free(row);
return 1;
}
/* Allow benign errors so that we can write PNGs with errors */
png_set_benign_errors(png_ptr, 1/*allowed*/);
png_init_io(png_ptr, fp);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
{
unsigned int size = image_size_of_type(color_type, bit_depth, colors);
png_fixed_point real_gamma = 45455; /* For sRGB */
png_byte gamma_table[256];
double conv;
/* This function uses the libpng values used on read to carry extra
* information about the gamma:
*/
if (gamma == PNG_GAMMA_MAC_18)
gamma = 65909;
else if (gamma > 0 && gamma < 1000)
gamma = PNG_FP_1;
if (gamma > 0)
real_gamma = gamma;
{
unsigned int i;
if (real_gamma == 45455) for (i=0; i<256; ++i)
{
gamma_table[i] = (png_byte)i;
conv = 1.;
}
else
{
/* Convert 'i' from sRGB (45455) to real_gamma, this makes
* the images look the same regardless of the gAMA chunk.
*/
conv = real_gamma;
conv /= 45455;
gamma_table[0] = 0;
for (i=1; i<255; ++i)
gamma_table[i] = (png_byte)floor(pow(i/255.,conv) * 255 + .5);
gamma_table[255] = 255;
}
}
png_set_IHDR(png_ptr, info_ptr, size, size, bit_depth, color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if (color_type & PNG_COLOR_MASK_PALETTE)
{
int npalette;
png_color palette[256];
png_byte trans[256];
npalette = generate_palette(palette, trans, bit_depth, gamma_table,
colors);
png_set_PLTE(png_ptr, info_ptr, palette, npalette);
png_set_tRNS(png_ptr, info_ptr, trans, npalette-1,
NULL/*transparent color*/);
/* Reset gamma_table to prevent the image rows being changed */
for (npalette=0; npalette<256; ++npalette)
gamma_table[npalette] = (png_byte)npalette;
}
if (gamma == PNG_DEFAULT_sRGB)
png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE);
else if (gamma > 0) /* Else don't set color space information */
{
png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma);
/* Just use the sRGB values here. */
png_set_cHRM_fixed(png_ptr, info_ptr,
/* color x y */
/* white */ 31270, 32900,
/* red */ 64000, 33000,
/* green */ 30000, 60000,
/* blue */ 15000, 6000
);
}
/* Insert extra information. */
while (insert != NULL)
{
insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters);
insert = insert->next;
}
/* Write the file header. */
png_write_info(png_ptr, info_ptr);
/* Restrict the filters */
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
{
int passes = png_set_interlace_handling(png_ptr);
int pass;
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = malloc(rowbytes);
if (row == NULL)
png_error(png_ptr, "OOM allocating row buffer");
for (pass = 0; pass < passes; ++pass)
{
unsigned int y;
for (y=0; y<size; ++y)
{
generate_row(row, rowbytes, y, color_type, bit_depth,
gamma_table, conv, colors);
png_write_row(png_ptr, row);
}
}
}
}
/* Finish writing the file. */
png_write_end(png_ptr, info_ptr);
{
png_structp nv_ptr = png_ptr;
png_infop nv_info = info_ptr;
png_ptr = NULL;
info_ptr = NULL;
png_destroy_write_struct(&nv_ptr, &nv_info);
}
free(row);
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | write_png(const char **name, FILE *fp, int color_type, int bit_depth,
volatile png_fixed_point gamma, chunk_insert * volatile insert,
unsigned int filters, unsigned int *colors, int small, int tRNS)
{
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
name, makepng_error, makepng_warning);
volatile png_infop info_ptr = NULL;
volatile png_bytep row = NULL;
if (png_ptr == NULL)
{
fprintf(stderr, "makepng: OOM allocating write structure\n");
return 1;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
png_structp nv_ptr = png_ptr;
png_infop nv_info = info_ptr;
png_ptr = NULL;
info_ptr = NULL;
png_destroy_write_struct(&nv_ptr, &nv_info);
if (row != NULL) free(row);
return 1;
}
/* Allow benign errors so that we can write PNGs with errors */
png_set_benign_errors(png_ptr, 1/*allowed*/);
/* Max out the text compression level in an attempt to make the license
* small. If --small then do the same for the IDAT.
*/
if (small)
png_set_compression_level(png_ptr, Z_BEST_COMPRESSION);
png_set_text_compression_level(png_ptr, Z_BEST_COMPRESSION);
png_init_io(png_ptr, fp);
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
png_error(png_ptr, "OOM allocating info structure");
{
const unsigned int size =
image_size_of_type(color_type, bit_depth, colors, small);
unsigned int ysize;
png_fixed_point real_gamma = 45455; /* For sRGB */
png_byte gamma_table[256];
double conv;
/* Normally images are square, but with 'small' we want to simply generate
* all the pixel values, or all that we reasonably can:
*/
if (small)
{
const unsigned int pixel_depth =
pixel_depth_of_type(color_type, bit_depth);
if (pixel_depth <= 8U)
{
assert(size == (1U<<pixel_depth));
ysize = 1U;
}
else
{
assert(size == 256U);
ysize = 256U;
}
}
else
ysize = size;
/* This function uses the libpng values used on read to carry extra
* information about the gamma:
*/
if (gamma == PNG_GAMMA_MAC_18)
gamma = 65909;
else if (gamma > 0 && gamma < 1000)
gamma = PNG_FP_1;
if (gamma > 0)
real_gamma = gamma;
{
unsigned int i;
if (real_gamma == 45455) for (i=0; i<256; ++i)
{
gamma_table[i] = (png_byte)i;
conv = 1.;
}
else
{
/* Convert 'i' from sRGB (45455) to real_gamma, this makes
* the images look the same regardless of the gAMA chunk.
*/
conv = real_gamma;
conv /= 45455;
gamma_table[0] = 0;
for (i=1; i<255; ++i)
gamma_table[i] = floorb(pow(i/255.,conv) * 255 + .5);
gamma_table[255] = 255;
}
}
png_set_IHDR(png_ptr, info_ptr, size, ysize, bit_depth, color_type,
PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
if (color_type & PNG_COLOR_MASK_PALETTE)
{
int npalette;
png_color palette[256];
png_byte trans[256];
npalette = generate_palette(palette, trans, bit_depth, gamma_table,
colors);
png_set_PLTE(png_ptr, info_ptr, palette, npalette);
if (tRNS)
png_set_tRNS(png_ptr, info_ptr, trans, npalette-1,
NULL/*transparent color*/);
/* Reset gamma_table to prevent the image rows being changed */
for (npalette=0; npalette<256; ++npalette)
gamma_table[npalette] = (png_byte)npalette;
}
else if (tRNS)
{
png_color_16 col;
col.red = col.green = col.blue = col.gray =
0x0101U & ((1U<<bit_depth)-1U);
col.index = 0U;
png_set_tRNS(png_ptr, info_ptr, NULL/*trans*/, 1U, &col);
}
if (gamma == PNG_DEFAULT_sRGB)
png_set_sRGB(png_ptr, info_ptr, PNG_sRGB_INTENT_ABSOLUTE);
else if (gamma > 0) /* Else don't set color space information */
{
png_set_gAMA_fixed(png_ptr, info_ptr, real_gamma);
/* Just use the sRGB values here. */
png_set_cHRM_fixed(png_ptr, info_ptr,
/* color x y */
/* white */ 31270, 32900,
/* red */ 64000, 33000,
/* green */ 30000, 60000,
/* blue */ 15000, 6000
);
}
/* Insert extra information. */
while (insert != NULL)
{
insert->insert(png_ptr, info_ptr, insert->nparams, insert->parameters);
insert = insert->next;
}
/* Write the file header. */
png_write_info(png_ptr, info_ptr);
/* Restrict the filters */
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, filters);
{
# ifdef PNG_WRITE_INTERLACING_SUPPORTED
int passes = png_set_interlace_handling(png_ptr);
# else /* !WRITE_INTERLACING */
int passes = 1;
# endif /* !WRITE_INTERLACING */
int pass;
png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr);
row = malloc(rowbytes);
if (row == NULL)
png_error(png_ptr, "OOM allocating row buffer");
for (pass = 0; pass < passes; ++pass)
{
unsigned int y;
for (y=0; y<ysize; ++y)
{
unsigned int row_filters =
generate_row(row, rowbytes, y, color_type, bit_depth,
gamma_table, conv, colors, small);
if (row_filters != 0 && filters == PNG_ALL_FILTERS)
png_set_filter(png_ptr, PNG_FILTER_TYPE_BASE, row_filters);
png_write_row(png_ptr, row);
}
}
}
}
/* Finish writing the file. */
png_write_end(png_ptr, info_ptr);
{
png_structp nv_ptr = png_ptr;
png_infop nv_info = info_ptr;
png_ptr = NULL;
info_ptr = NULL;
png_destroy_write_struct(&nv_ptr, &nv_info);
}
free(row);
return 0;
}
| 173,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: size_t compile_tree(struct filter_op **fop)
{
int i = 1;
struct filter_op *array = NULL;
struct unfold_elm *ue;
BUG_IF(tree_root == NULL);
fprintf(stdout, " Unfolding the meta-tree ");
fflush(stdout);
/* start the recursion on the tree */
unfold_blk(&tree_root);
fprintf(stdout, " done.\n\n");
/* substitute the virtual labels with real offsets */
labels_to_offsets();
/* convert the tailq into an array */
TAILQ_FOREACH(ue, &unfolded_tree, next) {
/* label == 0 means a real instruction */
if (ue->label == 0) {
SAFE_REALLOC(array, i * sizeof(struct filter_op));
memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op));
i++;
}
}
/* always append the exit function to a script */
SAFE_REALLOC(array, i * sizeof(struct filter_op));
array[i - 1].opcode = FOP_EXIT;
/* return the pointer to the array */
*fop = array;
return (i);
}
Commit Message: Exit gracefully in case of corrupted filters (Closes issue #782)
CWE ID: CWE-125 | size_t compile_tree(struct filter_op **fop)
{
int i = 1;
struct filter_op *array = NULL;
struct unfold_elm *ue;
// invalid file
if (tree_root == NULL)
return 0;
fprintf(stdout, " Unfolding the meta-tree ");
fflush(stdout);
/* start the recursion on the tree */
unfold_blk(&tree_root);
fprintf(stdout, " done.\n\n");
/* substitute the virtual labels with real offsets */
labels_to_offsets();
/* convert the tailq into an array */
TAILQ_FOREACH(ue, &unfolded_tree, next) {
/* label == 0 means a real instruction */
if (ue->label == 0) {
SAFE_REALLOC(array, i * sizeof(struct filter_op));
memcpy(&array[i - 1], &ue->fop, sizeof(struct filter_op));
i++;
}
}
/* always append the exit function to a script */
SAFE_REALLOC(array, i * sizeof(struct filter_op));
array[i - 1].opcode = FOP_EXIT;
/* return the pointer to the array */
*fop = array;
return (i);
}
| 168,336 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements; j++, i++) {
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
Commit Message: CVE-2014-0207: Prevent 0 element vectors and vectors longer than the number
of properties from accessing random memory.
CWE ID: CWE-119 | cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
| 166,442 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pipe_read(struct kiocb *iocb, const struct iovec *_iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
struct pipe_inode_info *pipe = filp->private_data;
int do_wakeup;
ssize_t ret;
struct iovec *iov = (struct iovec *)_iov;
size_t total_len;
total_len = iov_length(iov, nr_segs);
/* Null read succeeds. */
if (unlikely(total_len == 0))
return 0;
do_wakeup = 0;
ret = 0;
__pipe_lock(pipe);
for (;;) {
int bufs = pipe->nrbufs;
if (bufs) {
int curbuf = pipe->curbuf;
struct pipe_buffer *buf = pipe->bufs + curbuf;
const struct pipe_buf_operations *ops = buf->ops;
void *addr;
size_t chars = buf->len;
int error, atomic;
if (chars > total_len)
chars = total_len;
error = ops->confirm(pipe, buf);
if (error) {
if (!ret)
ret = error;
break;
}
atomic = !iov_fault_in_pages_write(iov, chars);
redo:
if (atomic)
addr = kmap_atomic(buf->page);
else
addr = kmap(buf->page);
error = pipe_iov_copy_to_user(iov, addr + buf->offset, chars, atomic);
if (atomic)
kunmap_atomic(addr);
else
kunmap(buf->page);
if (unlikely(error)) {
/*
* Just retry with the slow path if we failed.
*/
if (atomic) {
atomic = 0;
goto redo;
}
if (!ret)
ret = error;
break;
}
ret += chars;
buf->offset += chars;
buf->len -= chars;
/* Was it a packet buffer? Clean up and exit */
if (buf->flags & PIPE_BUF_FLAG_PACKET) {
total_len = chars;
buf->len = 0;
}
if (!buf->len) {
buf->ops = NULL;
ops->release(pipe, buf);
curbuf = (curbuf + 1) & (pipe->buffers - 1);
pipe->curbuf = curbuf;
pipe->nrbufs = --bufs;
do_wakeup = 1;
}
total_len -= chars;
if (!total_len)
break; /* common path: read succeeded */
}
if (bufs) /* More to do? */
continue;
if (!pipe->writers)
break;
if (!pipe->waiting_writers) {
/* syscall merging: Usually we must not sleep
* if O_NONBLOCK is set, or if we got some data.
* But if a writer sleeps in kernel space, then
* we can wait for that data without violating POSIX.
*/
if (ret)
break;
if (filp->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
}
if (signal_pending(current)) {
if (!ret)
ret = -ERESTARTSYS;
break;
}
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
pipe_wait(pipe);
}
__pipe_unlock(pipe);
/* Signal writers asynchronously that there is more room. */
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
if (ret > 0)
file_accessed(filp);
return ret;
}
Commit Message: switch pipe_read() to copy_page_to_iter()
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | pipe_read(struct kiocb *iocb, const struct iovec *_iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
struct pipe_inode_info *pipe = filp->private_data;
int do_wakeup;
ssize_t ret;
struct iovec *iov = (struct iovec *)_iov;
size_t total_len;
struct iov_iter iter;
total_len = iov_length(iov, nr_segs);
/* Null read succeeds. */
if (unlikely(total_len == 0))
return 0;
iov_iter_init(&iter, iov, nr_segs, total_len, 0);
do_wakeup = 0;
ret = 0;
__pipe_lock(pipe);
for (;;) {
int bufs = pipe->nrbufs;
if (bufs) {
int curbuf = pipe->curbuf;
struct pipe_buffer *buf = pipe->bufs + curbuf;
const struct pipe_buf_operations *ops = buf->ops;
size_t chars = buf->len;
size_t written;
int error;
if (chars > total_len)
chars = total_len;
error = ops->confirm(pipe, buf);
if (error) {
if (!ret)
ret = error;
break;
}
written = copy_page_to_iter(buf->page, buf->offset, chars, &iter);
if (unlikely(written < chars)) {
if (!ret)
ret = -EFAULT;
break;
}
ret += chars;
buf->offset += chars;
buf->len -= chars;
/* Was it a packet buffer? Clean up and exit */
if (buf->flags & PIPE_BUF_FLAG_PACKET) {
total_len = chars;
buf->len = 0;
}
if (!buf->len) {
buf->ops = NULL;
ops->release(pipe, buf);
curbuf = (curbuf + 1) & (pipe->buffers - 1);
pipe->curbuf = curbuf;
pipe->nrbufs = --bufs;
do_wakeup = 1;
}
total_len -= chars;
if (!total_len)
break; /* common path: read succeeded */
}
if (bufs) /* More to do? */
continue;
if (!pipe->writers)
break;
if (!pipe->waiting_writers) {
/* syscall merging: Usually we must not sleep
* if O_NONBLOCK is set, or if we got some data.
* But if a writer sleeps in kernel space, then
* we can wait for that data without violating POSIX.
*/
if (ret)
break;
if (filp->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
break;
}
}
if (signal_pending(current)) {
if (!ret)
ret = -ERESTARTSYS;
break;
}
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
pipe_wait(pipe);
}
__pipe_unlock(pipe);
/* Signal writers asynchronously that there is more room. */
if (do_wakeup) {
wake_up_interruptible_sync_poll(&pipe->wait, POLLOUT | POLLWRNORM);
kill_fasync(&pipe->fasync_writers, SIGIO, POLL_OUT);
}
if (ret > 0)
file_accessed(filp);
return ret;
}
| 169,929 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)
{
int res, bytes, i, indexes, index_bytes, ids;
long long *index, start, end;
struct squashfs_xattr_table id_table;
TRACE("read_xattrs_from_disk\n");
if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)
return SQUASHFS_INVALID_BLK;
/*
* Read xattr id table, containing start of xattr metadata and the
* number of xattrs in the file system
*/
res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),
&id_table);
if(res == 0)
return 0;
SQUASHFS_INSWAP_XATTR_TABLE(&id_table);
if(flag) {
/*
* id_table.xattr_table_start stores the start of the compressed xattr
* * metadata blocks. This by definition is also the end of the previous
* filesystem table - the id lookup table.
*/
*table_start = id_table.xattr_table_start;
return id_table.xattr_ids;
}
/*
* Allocate and read the index to the xattr id table metadata
* blocks
*/
ids = id_table.xattr_ids;
xattr_table_start = id_table.xattr_table_start;
index_bytes = SQUASHFS_XATTR_BLOCK_BYTES(ids);
indexes = SQUASHFS_XATTR_BLOCKS(ids);
index = malloc(index_bytes);
if(index == NULL)
MEM_ERROR();
res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),
index_bytes, index);
if(res ==0)
goto failed1;
SQUASHFS_INSWAP_LONG_LONGS(index, indexes);
/*
* Allocate enough space for the uncompressed xattr id table, and
* read and decompress it
*/
bytes = SQUASHFS_XATTR_BYTES(ids);
xattr_ids = malloc(bytes);
if(xattr_ids == NULL)
MEM_ERROR();
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
int length = read_block(fd, index[i], NULL, expected,
((unsigned char *) xattr_ids) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr id table block %d, from 0x%llx, length "
"%d\n", i, index[i], length);
if(length == 0) {
ERROR("Failed to read xattr id table block %d, "
"from 0x%llx, length %d\n", i, index[i],
length);
goto failed2;
}
}
/*
* Read and decompress the xattr metadata
*
* Note the first xattr id table metadata block is immediately after
* the last xattr metadata block, so we can use index[0] to work out
* the end of the xattr metadata
*/
start = xattr_table_start;
end = index[0];
for(i = 0; start < end; i++) {
int length;
xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);
if(xattrs == NULL)
MEM_ERROR();
/* store mapping from location of compressed block in fs ->
* location of uncompressed block in memory */
save_xattr_block(start, i * SQUASHFS_METADATA_SIZE);
length = read_block(fd, start, &start, 0,
((unsigned char *) xattrs) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr block %d, length %d\n", i, length);
if(length == 0) {
ERROR("Failed to read xattr block %d\n", i);
goto failed3;
}
/*
* If this is not the last metadata block in the xattr metadata
* then it should be SQUASHFS_METADATA_SIZE in size.
* Note, we can't use expected in read_block() above for this
* because we don't know if this is the last block until
* after reading.
*/
if(start != end && length != SQUASHFS_METADATA_SIZE) {
ERROR("Xattr block %d should be %d bytes in length, "
"it is %d bytes\n", i, SQUASHFS_METADATA_SIZE,
length);
goto failed3;
}
}
/* swap if necessary the xattr id entries */
for(i = 0; i < ids; i++)
SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);
free(index);
return ids;
failed3:
free(xattrs);
failed2:
free(xattr_ids);
failed1:
free(index);
return 0;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190 | int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)
{
/*
* Note on overflow limits:
* Size of ids (id_table.xattr_ids) is 2^32 (unsigned int)
* Max size of bytes is 2^32*16 or 2^36
* Max indexes is (2^32*16)/8K or 2^23
* Max index_bytes is ((2^32*16)/8K)*8 or 2^26 or 64M
*/
int res, i, indexes, index_bytes;
unsigned int ids;
long long bytes;
long long *index, start, end;
struct squashfs_xattr_table id_table;
TRACE("read_xattrs_from_disk\n");
if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)
return SQUASHFS_INVALID_BLK;
/*
* Read xattr id table, containing start of xattr metadata and the
* number of xattrs in the file system
*/
res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),
&id_table);
if(res == 0)
return 0;
SQUASHFS_INSWAP_XATTR_TABLE(&id_table);
/*
* Compute index table values
*/
ids = id_table.xattr_ids;
xattr_table_start = id_table.xattr_table_start;
index_bytes = SQUASHFS_XATTR_BLOCK_BYTES((long long) ids);
indexes = SQUASHFS_XATTR_BLOCKS((long long) ids);
/*
* The size of the index table (index_bytes) should match the
* table start and end points
*/
if(index_bytes != (sBlk->bytes_used - (sBlk->xattr_id_table_start + sizeof(id_table)))) {
ERROR("read_xattrs_from_disk: Bad xattr_ids count in super block\n");
return 0;
}
/*
* id_table.xattr_table_start stores the start of the compressed xattr
* metadata blocks. This by definition is also the end of the previous
* filesystem table - the id lookup table.
*/
if(table_start != NULL)
*table_start = id_table.xattr_table_start;
/*
* If flag is set then return once we've read the above
* table_start. That value is necessary for sanity checking,
* but we don't actually want to extract the xattrs, and so
* stop here.
*/
if(flag)
return id_table.xattr_ids;
/*
* Allocate and read the index to the xattr id table metadata
* blocks
*/
index = malloc(index_bytes);
if(index == NULL)
MEM_ERROR();
res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),
index_bytes, index);
if(res ==0)
goto failed1;
SQUASHFS_INSWAP_LONG_LONGS(index, indexes);
/*
* Allocate enough space for the uncompressed xattr id table, and
* read and decompress it
*/
bytes = SQUASHFS_XATTR_BYTES((long long) ids);
xattr_ids = malloc(bytes);
if(xattr_ids == NULL)
MEM_ERROR();
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
int length = read_block(fd, index[i], NULL, expected,
((unsigned char *) xattr_ids) +
((long long) i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr id table block %d, from 0x%llx, length "
"%d\n", i, index[i], length);
if(length == 0) {
ERROR("Failed to read xattr id table block %d, "
"from 0x%llx, length %d\n", i, index[i],
length);
goto failed2;
}
}
/*
* Read and decompress the xattr metadata
*
* Note the first xattr id table metadata block is immediately after
* the last xattr metadata block, so we can use index[0] to work out
* the end of the xattr metadata
*/
start = xattr_table_start;
end = index[0];
for(i = 0; start < end; i++) {
int length;
xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);
if(xattrs == NULL)
MEM_ERROR();
/* store mapping from location of compressed block in fs ->
* location of uncompressed block in memory */
save_xattr_block(start, i * SQUASHFS_METADATA_SIZE);
length = read_block(fd, start, &start, 0,
((unsigned char *) xattrs) +
(i * SQUASHFS_METADATA_SIZE));
TRACE("Read xattr block %d, length %d\n", i, length);
if(length == 0) {
ERROR("Failed to read xattr block %d\n", i);
goto failed3;
}
/*
* If this is not the last metadata block in the xattr metadata
* then it should be SQUASHFS_METADATA_SIZE in size.
* Note, we can't use expected in read_block() above for this
* because we don't know if this is the last block until
* after reading.
*/
if(start != end && length != SQUASHFS_METADATA_SIZE) {
ERROR("Xattr block %d should be %d bytes in length, "
"it is %d bytes\n", i, SQUASHFS_METADATA_SIZE,
length);
goto failed3;
}
}
/* swap if necessary the xattr id entries */
for(i = 0; i < ids; i++)
SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);
free(index);
return ids;
failed3:
free(xattrs);
failed2:
free(xattr_ids);
failed1:
free(index);
return 0;
}
| 168,878 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PageCaptureSaveAsMHTMLFunction::RunAsync() {
params_ = SaveAsMHTML::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
AddRef(); // Balanced in ReturnFailure/ReturnSuccess()
#if defined(OS_CHROMEOS)
if (profiles::ArePublicSessionRestrictionsEnabled()) {
WebContents* web_contents = GetWebContents();
if (!web_contents) {
ReturnFailure(kTabClosedError);
return true;
}
auto callback =
base::Bind(&PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest,
base::Unretained(this));
permission_helper::HandlePermissionRequest(
*extension(), {APIPermission::kPageCapture}, web_contents, callback,
permission_helper::PromptFactory());
return true;
}
#endif
base::PostTaskWithTraits(
FROM_HERE, kCreateTemporaryFileTaskTraits,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile,
this));
return true;
}
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 PageCaptureSaveAsMHTMLFunction::RunAsync() {
params_ = SaveAsMHTML::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
AddRef(); // Balanced in ReturnFailure/ReturnSuccess()
#if defined(OS_CHROMEOS)
if (profiles::ArePublicSessionRestrictionsEnabled()) {
WebContents* web_contents = GetWebContents();
if (!web_contents) {
ReturnFailure(kTabClosedError);
return true;
}
auto callback =
base::Bind(&PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest,
base::Unretained(this));
permission_helper::HandlePermissionRequest(
*extension(), {APIPermission::kPageCapture}, web_contents, callback,
permission_helper::PromptFactory());
return true;
}
#endif
if (!CanCaptureCurrentPage()) {
return false;
}
base::PostTaskWithTraits(
FROM_HERE, kCreateTemporaryFileTaskTraits,
base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile,
this));
return true;
}
| 173,004 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_ && !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
Commit Message: exo: Reduce side-effects of dynamic activation code.
This code exists for clients that need to managed their own system
modal dialogs. Since the addition of the remote surface API we
can limit the impact of this to surfaces created for system modal
container.
BUG=29528396
Review-Url: https://codereview.chromium.org/2084023003
Cr-Commit-Position: refs/heads/master@{#401115}
CWE ID: CWE-416 | void ShellSurface::CreateShellSurfaceWidget(ui::WindowShowState show_state) {
DCHECK(enabled());
DCHECK(!widget_);
views::Widget::InitParams params;
params.type = views::Widget::InitParams::TYPE_WINDOW;
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.delegate = this;
params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params.show_state = show_state;
params.parent =
ash::Shell::GetContainer(ash::Shell::GetPrimaryRootWindow(), container_);
params.bounds = initial_bounds_;
bool activatable = activatable_;
// ShellSurfaces in system modal container are only activatable if input
// region is non-empty. See OnCommitSurface() for more details.
if (container_ == ash::kShellWindowId_SystemModalContainer)
activatable &= !surface_->GetHitTestBounds().IsEmpty();
params.activatable = activatable ? views::Widget::InitParams::ACTIVATABLE_YES
: views::Widget::InitParams::ACTIVATABLE_NO;
widget_ = new ShellSurfaceWidget(this);
widget_->Init(params);
widget_->set_movement_disabled(!initial_bounds_.IsEmpty());
aura::Window* window = widget_->GetNativeWindow();
window->SetName("ExoShellSurface");
window->AddChild(surface_->window());
window->SetEventTargeter(base::WrapUnique(new CustomWindowTargeter));
SetApplicationId(window, &application_id_);
SetMainSurface(window, surface_);
window->AddObserver(this);
ash::wm::GetWindowState(window)->AddObserver(this);
if (parent_)
wm::AddTransientChild(parent_, window);
ash::wm::GetWindowState(window)->set_window_position_managed(
ash::wm::ToWindowShowState(ash::wm::WINDOW_STATE_TYPE_AUTO_POSITIONED) ==
show_state &&
initial_bounds_.IsEmpty());
views::FocusManager* focus_manager = widget_->GetFocusManager();
for (const auto& entry : kCloseWindowAccelerators) {
focus_manager->RegisterAccelerator(
ui::Accelerator(entry.keycode, entry.modifiers),
ui::AcceleratorManager::kNormalPriority, this);
}
pending_show_widget_ = true;
}
| 171,638 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock)
{
struct net_device *dev;
struct bnep_session *s, *ss;
u8 dst[ETH_ALEN], src[ETH_ALEN];
int err;
BT_DBG("");
baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst);
baswap((void *) src, &l2cap_pi(sock->sk)->chan->src);
/* session struct allocated as private part of net_device */
dev = alloc_netdev(sizeof(struct bnep_session),
(*req->device) ? req->device : "bnep%d",
NET_NAME_UNKNOWN,
bnep_net_setup);
if (!dev)
return -ENOMEM;
down_write(&bnep_session_sem);
ss = __bnep_get_session(dst);
if (ss && ss->state == BT_CONNECTED) {
err = -EEXIST;
goto failed;
}
s = netdev_priv(dev);
/* This is rx header therefore addresses are swapped.
* ie. eh.h_dest is our local address. */
memcpy(s->eh.h_dest, &src, ETH_ALEN);
memcpy(s->eh.h_source, &dst, ETH_ALEN);
memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN);
s->dev = dev;
s->sock = sock;
s->role = req->role;
s->state = BT_CONNECTED;
s->msg.msg_flags = MSG_NOSIGNAL;
#ifdef CONFIG_BT_BNEP_MC_FILTER
/* Set default mc filter */
set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter);
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
/* Set default protocol filter */
bnep_set_default_proto_filter(s);
#endif
SET_NETDEV_DEV(dev, bnep_get_device(s));
SET_NETDEV_DEVTYPE(dev, &bnep_type);
err = register_netdev(dev);
if (err)
goto failed;
__bnep_link_session(s);
__module_get(THIS_MODULE);
s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name);
if (IS_ERR(s->task)) {
/* Session thread start failed, gotta cleanup. */
module_put(THIS_MODULE);
unregister_netdev(dev);
__bnep_unlink_session(s);
err = PTR_ERR(s->task);
goto failed;
}
up_write(&bnep_session_sem);
strcpy(req->device, dev->name);
return 0;
failed:
up_write(&bnep_session_sem);
free_netdev(dev);
return err;
}
Commit Message: Bluetooth: bnep: bnep_add_connection() should verify that it's dealing with l2cap socket
same story as cmtp
Signed-off-by: Al Viro <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-20 | int bnep_add_connection(struct bnep_connadd_req *req, struct socket *sock)
{
struct net_device *dev;
struct bnep_session *s, *ss;
u8 dst[ETH_ALEN], src[ETH_ALEN];
int err;
BT_DBG("");
if (!l2cap_is_socket(sock))
return -EBADFD;
baswap((void *) dst, &l2cap_pi(sock->sk)->chan->dst);
baswap((void *) src, &l2cap_pi(sock->sk)->chan->src);
/* session struct allocated as private part of net_device */
dev = alloc_netdev(sizeof(struct bnep_session),
(*req->device) ? req->device : "bnep%d",
NET_NAME_UNKNOWN,
bnep_net_setup);
if (!dev)
return -ENOMEM;
down_write(&bnep_session_sem);
ss = __bnep_get_session(dst);
if (ss && ss->state == BT_CONNECTED) {
err = -EEXIST;
goto failed;
}
s = netdev_priv(dev);
/* This is rx header therefore addresses are swapped.
* ie. eh.h_dest is our local address. */
memcpy(s->eh.h_dest, &src, ETH_ALEN);
memcpy(s->eh.h_source, &dst, ETH_ALEN);
memcpy(dev->dev_addr, s->eh.h_dest, ETH_ALEN);
s->dev = dev;
s->sock = sock;
s->role = req->role;
s->state = BT_CONNECTED;
s->msg.msg_flags = MSG_NOSIGNAL;
#ifdef CONFIG_BT_BNEP_MC_FILTER
/* Set default mc filter */
set_bit(bnep_mc_hash(dev->broadcast), (ulong *) &s->mc_filter);
#endif
#ifdef CONFIG_BT_BNEP_PROTO_FILTER
/* Set default protocol filter */
bnep_set_default_proto_filter(s);
#endif
SET_NETDEV_DEV(dev, bnep_get_device(s));
SET_NETDEV_DEVTYPE(dev, &bnep_type);
err = register_netdev(dev);
if (err)
goto failed;
__bnep_link_session(s);
__module_get(THIS_MODULE);
s->task = kthread_run(bnep_session, s, "kbnepd %s", dev->name);
if (IS_ERR(s->task)) {
/* Session thread start failed, gotta cleanup. */
module_put(THIS_MODULE);
unregister_netdev(dev);
__bnep_unlink_session(s);
err = PTR_ERR(s->task);
goto failed;
}
up_write(&bnep_session_sem);
strcpy(req->device, dev->name);
return 0;
failed:
up_write(&bnep_session_sem);
free_netdev(dev);
return err;
}
| 167,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: lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
Commit Message: Fail with negative lha->compsize in lha_read_file_header_1()
Fixes a heap buffer overflow reported in Secunia SA74169
CWE ID: CWE-125 | lha_read_file_header_1(struct archive_read *a, struct lha *lha)
{
const unsigned char *p;
size_t extdsize;
int i, err, err2;
int namelen, padding;
unsigned char headersum, sum_calculated;
err = ARCHIVE_OK;
if ((p = __archive_read_ahead(a, H1_FIXED_SIZE, NULL)) == NULL)
return (truncated_error(a));
lha->header_size = p[H1_HEADER_SIZE_OFFSET] + 2;
headersum = p[H1_HEADER_SUM_OFFSET];
/* Note: An extended header size is included in a compsize. */
lha->compsize = archive_le32dec(p + H1_COMP_SIZE_OFFSET);
lha->origsize = archive_le32dec(p + H1_ORIG_SIZE_OFFSET);
lha->mtime = lha_dos_time(p + H1_DOS_TIME_OFFSET);
namelen = p[H1_NAME_LEN_OFFSET];
/* Calculate a padding size. The result will be normally 0 only(?) */
padding = ((int)lha->header_size) - H1_FIXED_SIZE - namelen;
if (namelen > 230 || padding < 0)
goto invalid;
if ((p = __archive_read_ahead(a, lha->header_size, NULL)) == NULL)
return (truncated_error(a));
for (i = 0; i < namelen; i++) {
if (p[i + H1_FILE_NAME_OFFSET] == 0xff)
goto invalid;/* Invalid filename. */
}
archive_strncpy(&lha->filename, p + H1_FILE_NAME_OFFSET, namelen);
lha->crc = archive_le16dec(p + H1_FILE_NAME_OFFSET + namelen);
lha->setflag |= CRC_IS_SET;
sum_calculated = lha_calcsum(0, p, 2, lha->header_size - 2);
/* Consume used bytes but not include `next header size' data
* since it will be consumed in lha_read_file_extended_header(). */
__archive_read_consume(a, lha->header_size - 2);
/* Read extended headers */
err2 = lha_read_file_extended_header(a, lha, NULL, 2,
(size_t)(lha->compsize + 2), &extdsize);
if (err2 < ARCHIVE_WARN)
return (err2);
if (err2 < err)
err = err2;
/* Get a real compressed file size. */
lha->compsize -= extdsize - 2;
if (lha->compsize < 0)
goto invalid; /* Invalid compressed file size */
if (sum_calculated != headersum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"LHa header sum error");
return (ARCHIVE_FATAL);
}
return (err);
invalid:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid LHa header");
return (ARCHIVE_FATAL);
}
| 168,381 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LogLuvSetupEncode(TIFF* tif)
{
static const char module[] = "LogLuvSetupEncode";
LogLuvState* sp = EncoderState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (td->td_photometric) {
case PHOTOMETRIC_LOGLUV:
if (!LogLuvInitState(tif))
break;
if (td->td_compression == COMPRESSION_SGILOG24) {
tif->tif_encoderow = LogLuvEncode24;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv24fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv24fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
} else {
tif->tif_encoderow = LogLuvEncode32;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv32fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv32fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
}
break;
case PHOTOMETRIC_LOGL:
if (!LogL16InitState(tif))
break;
tif->tif_encoderow = LogL16Encode;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = L16fromY;
break;
case SGILOGDATAFMT_16BIT:
break;
default:
goto notsupported;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Inappropriate photometric interpretation %d for SGILog compression; %s",
td->td_photometric, "must be either LogLUV or LogL");
break;
}
return (1);
notsupported:
TIFFErrorExt(tif->tif_clientdata, module,
"SGILog compression supported only for %s, or raw data",
td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
return (0);
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125 | LogLuvSetupEncode(TIFF* tif)
{
static const char module[] = "LogLuvSetupEncode";
LogLuvState* sp = EncoderState(tif);
TIFFDirectory* td = &tif->tif_dir;
switch (td->td_photometric) {
case PHOTOMETRIC_LOGLUV:
if (!LogLuvInitState(tif))
break;
if (td->td_compression == COMPRESSION_SGILOG24) {
tif->tif_encoderow = LogLuvEncode24;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv24fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv24fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
} else {
tif->tif_encoderow = LogLuvEncode32;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = Luv32fromXYZ;
break;
case SGILOGDATAFMT_16BIT:
sp->tfunc = Luv32fromLuv48;
break;
case SGILOGDATAFMT_RAW:
break;
default:
goto notsupported;
}
}
break;
case PHOTOMETRIC_LOGL:
if (!LogL16InitState(tif))
break;
tif->tif_encoderow = LogL16Encode;
switch (sp->user_datafmt) {
case SGILOGDATAFMT_FLOAT:
sp->tfunc = L16fromY;
break;
case SGILOGDATAFMT_16BIT:
break;
default:
goto notsupported;
}
break;
default:
TIFFErrorExt(tif->tif_clientdata, module,
"Inappropriate photometric interpretation %d for SGILog compression; %s",
td->td_photometric, "must be either LogLUV or LogL");
break;
}
sp->encoder_state = 1;
return (1);
notsupported:
TIFFErrorExt(tif->tif_clientdata, module,
"SGILog compression supported only for %s, or raw data",
td->td_photometric == PHOTOMETRIC_LOGL ? "Y, L" : "XYZ, Luv");
return (0);
}
| 168,465 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436 | side_in_cb (GSocket *socket, GIOCondition condition, gpointer user_data)
{
ProxySide *side = user_data;
FlatpakProxyClient *client = side->client;
GError *error = NULL;
Buffer *buffer;
gboolean retval = G_SOURCE_CONTINUE;
g_object_ref (client);
while (!side->closed)
{
if (!side->got_first_byte)
buffer = buffer_new (1, NULL);
else if (!client->authenticated)
buffer = buffer_new (64, NULL);
else
buffer = side->current_read_buffer;
if (!buffer_read (side, buffer, socket))
{
if (buffer != side->current_read_buffer)
buffer_unref (buffer);
break;
}
if (!client->authenticated)
{
if (buffer->pos > 0)
{
gboolean found_auth_end = FALSE;
gsize extra_data;
buffer->size = buffer->pos;
if (!side->got_first_byte)
{
buffer->send_credentials = TRUE;
side->got_first_byte = TRUE;
}
/* Look for end of authentication mechanism */
else if (side == &client->client_side)
{
gssize auth_end = find_auth_end (client, buffer);
if (auth_end >= 0)
{
found_auth_end = TRUE;
buffer->size = auth_end;
extra_data = buffer->pos - buffer->size;
/* We may have gotten some extra data which is not part of
the auth handshake, keep it for the next iteration. */
if (extra_data > 0)
side->extra_input_data = g_bytes_new (buffer->data + buffer->size, extra_data);
}
else if (auth_end == FIND_AUTH_END_ABORT)
{
buffer_unref (buffer);
if (client->proxy->log_messages)
g_print ("Invalid AUTH line, aborting\n");
side_closed (side);
break;
}
}
got_buffer_from_side (side, buffer);
if (found_auth_end)
client->authenticated = TRUE;
}
else
{
buffer_unref (buffer);
}
}
else if (buffer->pos == buffer->size)
{
if (buffer == &side->header_buffer)
{
gssize required;
required = g_dbus_message_bytes_needed (buffer->data, buffer->size, &error);
if (required < 0)
{
g_warning ("Invalid message header read");
side_closed (side);
}
else
{
side->current_read_buffer = buffer_new (required, buffer);
}
}
else
{
got_buffer_from_side (side, buffer);
side->header_buffer.pos = 0;
side->current_read_buffer = &side->header_buffer;
}
}
}
if (side->closed)
{
side->in_source = NULL;
retval = G_SOURCE_REMOVE;
}
g_object_unref (client);
return retval;
}
| 169,343 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
Commit Message: PPB_Flash.Navigate(): Disallow certain HTTP request headers.
With this CL, PPB_Flash.Navigate() fails the operation with
PP_ERROR_NOACCESS if the request headers contain non-simple headers.
BUG=332023
TEST=None
Review URL: https://codereview.chromium.org/136393004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249114 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | int32_t PepperFlashRendererHost::OnNavigate(
ppapi::host::HostMessageContext* host_context,
const ppapi::URLRequestInfoData& data,
const std::string& target,
bool from_user_action) {
content::PepperPluginInstance* plugin_instance =
host_->GetPluginInstance(pp_instance());
if (!plugin_instance)
return PP_ERROR_FAILED;
std::map<std::string, FlashNavigateUsage>& rejected_headers =
g_rejected_headers.Get();
if (rejected_headers.empty()) {
for (size_t i = 0; i < arraysize(kRejectedHttpRequestHeaders); ++i)
rejected_headers[kRejectedHttpRequestHeaders[i]] =
static_cast<FlashNavigateUsage>(i);
}
net::HttpUtil::HeadersIterator header_iter(data.headers.begin(),
data.headers.end(),
"\n\r");
bool rejected = false;
while (header_iter.GetNext()) {
std::string lower_case_header_name = StringToLowerASCII(header_iter.name());
if (!IsSimpleHeader(lower_case_header_name, header_iter.values())) {
rejected = true;
std::map<std::string, FlashNavigateUsage>::const_iterator iter =
rejected_headers.find(lower_case_header_name);
FlashNavigateUsage usage = iter != rejected_headers.end() ?
iter->second : REJECT_OTHER_HEADERS;
RecordFlashNavigateUsage(usage);
}
}
RecordFlashNavigateUsage(TOTAL_NAVIGATE_REQUESTS);
if (rejected) {
RecordFlashNavigateUsage(TOTAL_REJECTED_NAVIGATE_REQUESTS);
return PP_ERROR_NOACCESS;
}
ppapi::proxy::HostDispatcher* host_dispatcher =
ppapi::proxy::HostDispatcher::GetForInstance(pp_instance());
host_dispatcher->set_allow_plugin_reentrancy();
base::WeakPtr<PepperFlashRendererHost> weak_ptr = weak_factory_.GetWeakPtr();
navigate_replies_.push_back(host_context->MakeReplyMessageContext());
plugin_instance->Navigate(data, target.c_str(), from_user_action);
if (weak_ptr.get()) {
SendReply(navigate_replies_.back(), IPC::Message());
navigate_replies_.pop_back();
}
return PP_OK_COMPLETIONPENDING;
}
| 171,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.