prompt
stringlengths 1.19k
236k
| output
int64 0
1
|
---|---|
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum)
{
#define AlignedExtent(size,alignment) \
(((size)+((alignment)-1)) & ~((alignment)-1))
size_t
alignment,
extent,
size;
void
*memory;
if (CheckMemoryOverflow(count,quantum) != MagickFalse)
return((void *) NULL);
memory=NULL;
alignment=CACHE_LINE_SIZE;
size=count*quantum;
extent=AlignedExtent(size,alignment);
if ((size == 0) || (alignment < sizeof(void *)) || (extent < size))
return((void *) NULL);
#if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN)
if (posix_memalign(&memory,alignment,extent) != 0)
memory=NULL;
#elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC)
memory=_aligned_malloc(extent,alignment);
#else
{
void
*p;
extent=(size+alignment-1)+sizeof(void *);
if (extent > size)
{
p=malloc(extent);
if (p != NULL)
{
memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment);
*((void **) memory-1)=p;
}
}
}
#endif
return(memory);
}
Commit Message: Suspend exception processing if there are too many exceptions
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void voidMethodEventTargetArgMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod");
TestObjectPythonV8Internal::voidMethodEventTargetArgMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution");
}
Commit Message: document.location bindings fix
BUG=352374
[email protected]
Review URL: https://codereview.chromium.org/196343011
git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void _free_result(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
pgsql_result_handle *pg_result = (pgsql_result_handle *)rsrc->ptr;
PQclear(pg_result->result);
efree(pg_result);
}
Commit Message:
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CrosLibrary::TestApi::SetBurnLibrary(
BurnLibrary* library, bool own) {
library_->burn_lib_.SetImpl(library, own);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int aes_xts_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)
{
EVP_AES_XTS_CTX *xctx = EVP_C_DATA(EVP_AES_XTS_CTX,c);
if (type == EVP_CTRL_COPY) {
EVP_CIPHER_CTX *out = ptr;
EVP_AES_XTS_CTX *xctx_out = EVP_C_DATA(EVP_AES_XTS_CTX,out);
if (xctx->xts.key1) {
if (xctx->xts.key1 != &xctx->ks1)
return 0;
xctx_out->xts.key1 = &xctx_out->ks1;
}
if (xctx->xts.key2) {
if (xctx->xts.key2 != &xctx->ks2)
return 0;
xctx_out->xts.key2 = &xctx_out->ks2;
}
return 1;
} else if (type != EVP_CTRL_INIT)
return -1;
/* key1 and key2 are used as an indicator both key and IV are set */
xctx->xts.key1 = NULL;
xctx->xts.key2 = NULL;
return 1;
}
Commit Message: crypto/evp: harden AEAD ciphers.
Originally a crash in 32-bit build was reported CHACHA20-POLY1305
cipher. The crash is triggered by truncated packet and is result
of excessive hashing to the edge of accessible memory. Since hash
operation is read-only it is not considered to be exploitable
beyond a DoS condition. Other ciphers were hardened.
Thanks to Robert Święcki for report.
CVE-2017-3731
Reviewed-by: Rich Salz <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void QuotaTask::DeleteSoon() {
MessageLoop::current()->DeleteSoon(FROM_HERE, this);
}
Commit Message: Quota double-delete fix
BUG=142310
Review URL: https://chromiumcodereview.appspot.com/10832407
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@152532 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
Packet *p, Flow * const pflow)
{
PACKET_PROFILING_DETECT_START(p, PROF_DETECT_CLEANUP);
/* cleanup pkt specific part of the patternmatcher */
PacketPatternCleanup(det_ctx);
if (pflow != NULL) {
/* update inspected tracker for raw reassembly */
if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL) {
StreamReassembleRawUpdateProgress(pflow->protoctx, p,
det_ctx->raw_stream_progress);
DetectEngineCleanHCBDBuffers(det_ctx);
}
}
PACKET_PROFILING_DETECT_END(p, PROF_DETECT_CLEANUP);
SCReturn;
}
Commit Message: stream: fix false negative on bad RST
If a bad RST was received the stream inspection would not happen
for that packet, but it would still move the 'raw progress' tracker
forward. Following good packets would then fail to detect anything
before the 'raw progress' position.
Bug #2770
Reported-by: Alexey Vishnyakov
CWE ID: CWE-347
Target: 1
Example 2:
Code: bool ikev1_decode_peer_id(struct msg_digest *md, bool initiator, bool aggrmode)
{
struct state *const st = md->st;
struct payload_digest *const id_pld = md->chain[ISAKMP_NEXT_ID];
const pb_stream *const id_pbs = &id_pld->pbs;
struct isakmp_id *const id = &id_pld->payload.id;
struct id peer;
/* I think that RFC2407 (IPSEC DOI) 4.6.2 is confused.
* It talks about the protocol ID and Port fields of the ID
* Payload, but they don't exist as such in Phase 1.
* We use more appropriate names.
* isaid_doi_specific_a is in place of Protocol ID.
* isaid_doi_specific_b is in place of Port.
* Besides, there is no good reason for allowing these to be
* other than 0 in Phase 1.
*/
if (st->hidden_variables.st_nat_traversal != LEMPTY &&
id->isaid_doi_specific_a == IPPROTO_UDP &&
(id->isaid_doi_specific_b == 0 ||
id->isaid_doi_specific_b == pluto_nat_port)) {
DBG_log("protocol/port in Phase 1 ID Payload is %d/%d. "
"accepted with port_floating NAT-T",
id->isaid_doi_specific_a, id->isaid_doi_specific_b);
} else if (!(id->isaid_doi_specific_a == 0 &&
id->isaid_doi_specific_b == 0) &&
!(id->isaid_doi_specific_a == IPPROTO_UDP &&
id->isaid_doi_specific_b == pluto_port))
{
loglog(RC_LOG_SERIOUS, "protocol/port in Phase 1 ID Payload MUST be 0/0 or %d/%d"
" but are %d/%d (attempting to continue)",
IPPROTO_UDP, pluto_port,
id->isaid_doi_specific_a,
id->isaid_doi_specific_b);
/* we have turned this into a warning because of bugs in other vendors
* products. Specifically CISCO VPN3000.
*/
/* return FALSE; */
}
zero(&peer); /* ??? pointer fields might not be NULLed */
peer.kind = id->isaid_idtype;
if (!extract_peer_id(&peer, id_pbs))
return FALSE;
/*
* For interop with SoftRemote/aggressive mode we need to remember some
* things for checking the hash
*/
st->st_peeridentity_protocol = id->isaid_doi_specific_a;
st->st_peeridentity_port = ntohs(id->isaid_doi_specific_b);
{
char buf[IDTOA_BUF];
idtoa(&peer, buf, sizeof(buf));
libreswan_log("%s mode peer ID is %s: '%s'",
aggrmode ? "Aggressive" : "Main",
enum_show(&ike_idtype_names, id->isaid_idtype), buf);
}
/* check for certificates */
if (!ikev1_decode_cert(md))
return FALSE;
/* Now that we've decoded the ID payload, let's see if we
* need to switch connections.
* We must not switch horses if we initiated:
* - if the initiation was explicit, we'd be ignoring user's intent
* - if opportunistic, we'll lose our HOLD info
*/
if (initiator) {
if (!same_id(&st->st_connection->spd.that.id, &peer) &&
id_kind(&st->st_connection->spd.that.id) != ID_FROMCERT) {
char expect[IDTOA_BUF],
found[IDTOA_BUF];
idtoa(&st->st_connection->spd.that.id, expect,
sizeof(expect));
idtoa(&peer, found, sizeof(found));
loglog(RC_LOG_SERIOUS,
"we require IKEv1 peer to have ID '%s', but peer declares '%s'",
expect, found);
return FALSE;
} else if (id_kind(&st->st_connection->spd.that.id) == ID_FROMCERT) {
if (id_kind(&peer) != ID_DER_ASN1_DN) {
loglog(RC_LOG_SERIOUS,
"peer ID is not a certificate type");
return FALSE;
}
duplicate_id(&st->st_connection->spd.that.id, &peer);
}
} else {
struct connection *c = st->st_connection;
struct connection *r = NULL;
bool fromcert;
uint16_t auth = xauth_calcbaseauth(st->st_oakley.auth);
lset_t auth_policy = LEMPTY;
switch (auth) {
case OAKLEY_PRESHARED_KEY:
auth_policy = POLICY_PSK;
break;
case OAKLEY_RSA_SIG:
auth_policy = POLICY_RSASIG;
break;
/* Not implemented */
case OAKLEY_DSS_SIG:
case OAKLEY_RSA_ENC:
case OAKLEY_RSA_REVISED_MODE:
case OAKLEY_ECDSA_P256:
case OAKLEY_ECDSA_P384:
case OAKLEY_ECDSA_P521:
default:
DBG(DBG_CONTROL, DBG_log("ikev1 ikev1_decode_peer_id bad_case due to not supported policy"));
}
if (aggrmode)
auth_policy |= POLICY_AGGRESSIVE;
/* check for certificate requests */
ikev1_decode_cr(md);
if ((auth_policy & ~POLICY_AGGRESSIVE) != LEMPTY) {
r = refine_host_connection(st, &peer, initiator, auth_policy, &fromcert);
pexpect(r != NULL);
}
if (r == NULL) {
char buf[IDTOA_BUF];
idtoa(&peer, buf, sizeof(buf));
loglog(RC_LOG_SERIOUS,
"no suitable connection for peer '%s'",
buf);
return FALSE;
}
DBG(DBG_CONTROL, {
char buf[IDTOA_BUF];
dntoa_or_null(buf, IDTOA_BUF, r->spd.this.ca,
"%none");
DBG_log("offered CA: '%s'", buf);
});
if (r != c) {
char b1[CONN_INST_BUF];
char b2[CONN_INST_BUF];
/* apparently, r is an improvement on c -- replace */
libreswan_log("switched from \"%s\"%s to \"%s\"%s",
c->name,
fmt_conn_instance(c, b1),
r->name,
fmt_conn_instance(r, b2));
if (r->kind == CK_TEMPLATE || r->kind == CK_GROUP) {
/* instantiate it, filling in peer's ID */
r = rw_instantiate(r, &c->spd.that.host_addr,
NULL,
&peer);
}
update_state_connection(st, r);
} else if (c->spd.that.has_id_wildcards) {
free_id_content(&c->spd.that.id);
c->spd.that.id = peer;
c->spd.that.has_id_wildcards = FALSE;
unshare_id_content(&c->spd.that.id);
} else if (fromcert) {
DBG(DBG_CONTROL, DBG_log("copying ID for fromcert"));
duplicate_id(&r->spd.that.id, &peer);
}
}
return TRUE;
}
Commit Message: IKEv1: packet retransmit fixes for Main/Aggr/Xauth modes
- Do not schedule retransmits for inI1outR1 packets (prevent DDOS)
- Do schedule retransmits for XAUTH packets
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool InitializeTemporaryOriginsInfoOnDBThread(const std::set<GURL>* origins,
QuotaDatabase* database) {
DCHECK(database);
if (database->IsOriginDatabaseBootstrapped())
return true;
if (database->RegisterInitialOriginInfo(*origins, kStorageTypeTemporary)) {
database->SetOriginDatabaseBootstrapped(true);
return true;
}
return false;
}
Commit Message: Wipe out QuotaThreadTask.
This is a one of a series of refactoring patches for QuotaManager.
http://codereview.chromium.org/10872054/
http://codereview.chromium.org/10917060/
BUG=139270
Review URL: https://chromiumcodereview.appspot.com/10919070
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static const char *parse_scheme(struct parse_state *state)
{
size_t mb;
const char *tmp = state->ptr;
do {
switch (*state->ptr) {
case ':':
/* scheme delimiter */
state->url.scheme = &state->buffer[0];
state->buffer[state->offset++] = 0;
return ++state->ptr;
case '0': case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9':
case '+': case '-': case '.':
if (state->ptr == tmp) {
return tmp;
}
/* no break */
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
case 'V': case 'W': case 'X': case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
case 'v': case 'w': case 'x': case 'y': case 'z':
/* scheme part */
state->buffer[state->offset++] = *state->ptr;
break;
default:
if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) {
/* soft fail; parse path next */
return tmp;
}
state->ptr += mb - 1;
}
} while (++state->ptr != state->end);
return state->ptr = tmp;
}
Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions)
The parser's offset was not reset when we softfail in scheme
parsing and continue to parse a path.
Thanks to hlt99 at blinkenshell dot org for the report.
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int prepend_name(char **buffer, int *buflen, const struct qstr *name)
{
const char *dname = ACCESS_ONCE(name->name);
u32 dlen = ACCESS_ONCE(name->len);
char *p;
smp_read_barrier_depends();
*buflen -= dlen + 1;
if (*buflen < 0)
return -ENAMETOOLONG;
p = *buffer -= dlen + 1;
*p++ = '/';
while (dlen--) {
char c = *dname++;
if (!c)
break;
*p++ = c;
}
return 0;
}
Commit Message: dentry name snapshots
take_dentry_name_snapshot() takes a safe snapshot of dentry name;
if the name is a short one, it gets copied into caller-supplied
structure, otherwise an extra reference to external name is grabbed
(those are never modified). In either case the pointer to stable
string is stored into the same structure.
dentry must be held by the caller of take_dentry_name_snapshot(),
but may be freely dropped afterwards - the snapshot will stay
until destroyed by release_dentry_name_snapshot().
Intended use:
struct name_snapshot s;
take_dentry_name_snapshot(&s, dentry);
...
access s.name
...
release_dentry_name_snapshot(&s);
Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name
to pass down with event.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __net_random_once_deferred(struct work_struct *w)
{
struct __net_random_once_work *work =
container_of(w, struct __net_random_once_work, work);
if (!static_key_enabled(work->key))
static_key_slow_inc(work->key);
kfree(work);
}
Commit Message: net: avoid dependency of net_get_random_once on nop patching
net_get_random_once depends on the static keys infrastructure to patch up
the branch to the slow path during boot. This was realized by abusing the
static keys api and defining a new initializer to not enable the call
site while still indicating that the branch point should get patched
up. This was needed to have the fast path considered likely by gcc.
The static key initialization during boot up normally walks through all
the registered keys and either patches in ideal nops or enables the jump
site but omitted that step on x86 if ideal nops where already placed at
static_key branch points. Thus net_get_random_once branches not always
became active.
This patch switches net_get_random_once to the ordinary static_key
api and thus places the kernel fast path in the - by gcc considered -
unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that
the unlikely path actually beats the likely path in terms of cycle cost
and that different nop patterns did not make much difference, thus this
switch should not be noticeable.
Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once")
Reported-by: Tuomas Räsänen <[email protected]>
Cc: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: MagickExport MagickBooleanType AnnotateImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
char
*p,
primitive[MagickPathExtent],
*text,
**textlist;
DrawInfo
*annotate,
*annotate_info;
GeometryInfo
geometry_info;
MagickBooleanType
status;
PointInfo
offset;
RectangleInfo
geometry;
register ssize_t
i;
TypeMetric
metrics;
size_t
height,
number_lines;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->text == (char *) NULL)
return(MagickFalse);
if (*draw_info->text == '\0')
return(MagickTrue);
annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info);
text=annotate->text;
annotate->text=(char *) NULL;
annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
number_lines=1;
for (p=text; *p != '\0'; p++)
if (*p == '\n')
number_lines++;
textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist));
if (textlist == (char **) NULL)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
return(MagickFalse);
}
p=text;
for (i=0; i < number_lines; i++)
{
char
*q;
textlist[i]=p;
for (q=p; *q != '\0'; q++)
if ((*q == '\r') || (*q == '\n'))
break;
if (*q == '\r')
{
*q='\0';
q++;
}
*q='\0';
p=q+1;
}
textlist[i]=(char *) NULL;
SetGeometry(image,&geometry);
SetGeometryInfo(&geometry_info);
if (annotate_info->geometry != (char *) NULL)
{
(void) ParsePageGeometry(image,annotate_info->geometry,&geometry,
exception);
(void) ParseGeometry(annotate_info->geometry,&geometry_info);
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(MagickFalse);
}
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
status=MagickTrue;
(void) memset(&metrics,0,sizeof(metrics));
for (i=0; textlist[i] != (char *) NULL; i++)
{
if (*textlist[i] == '\0')
continue;
/*
Position text relative to image.
*/
annotate_info->affine.tx=geometry_info.xi-image->page.x;
annotate_info->affine.ty=geometry_info.psi-image->page.y;
(void) CloneString(&annotate->text,textlist[i]);
if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity))
(void) GetTypeMetrics(image,annotate,&metrics,exception);
height=(ssize_t) (metrics.ascent-metrics.descent+
draw_info->interline_spacing+0.5);
switch (annotate->gravity)
{
case UndefinedGravity:
default:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case NorthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent;
break;
}
case NorthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent);
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width/2.0;
break;
}
case NorthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+annotate_info->affine.ry*
(metrics.ascent+metrics.descent)-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i*
annotate_info->affine.sy*height+annotate_info->affine.sy*
metrics.ascent-annotate_info->affine.rx*metrics.width;
break;
}
case WestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case CenterGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy*
(metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0;
break;
}
case EastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width+
annotate_info->affine.ry*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0-1.0;
offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+
geometry.height/2.0+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width+
annotate_info->affine.sy*(metrics.ascent+metrics.descent-
(number_lines-1.0)*height)/2.0;
break;
}
case SouthWestGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i*
annotate_info->affine.ry*height-annotate_info->affine.ry*
(number_lines-1.0)*height;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthGravity:
{
offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+
geometry.width/2.0+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0-
annotate_info->affine.ry*(number_lines-1.0)*height/2.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
case SouthEastGravity:
{
offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+
geometry.width+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width-
annotate_info->affine.ry*(number_lines-1.0)*height-1.0;
offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+
geometry.height+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width-
annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent;
break;
}
}
switch (annotate->align)
{
case LeftAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height;
break;
}
case CenterAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width/2.0;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width/2.0;
break;
}
case RightAlign:
{
offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height-
annotate_info->affine.sx*metrics.width;
offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height-
annotate_info->affine.rx*metrics.width;
break;
}
default:
break;
}
if (draw_info->undercolor.alpha != TransparentAlpha)
{
DrawInfo
*undercolor_info;
/*
Text box.
*/
undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL);
undercolor_info->fill=draw_info->undercolor;
undercolor_info->affine=draw_info->affine;
undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent;
undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent;
(void) FormatLocaleString(primitive,MagickPathExtent,
"rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height);
(void) CloneString(&undercolor_info->primitive,primitive);
(void) DrawImage(image,undercolor_info,exception);
(void) DestroyDrawInfo(undercolor_info);
}
annotate_info->affine.tx=offset.x;
annotate_info->affine.ty=offset.y;
(void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g "
"line 0,0 %g,0",metrics.underline_thickness,metrics.width);
if (annotate->decorate == OverlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+
metrics.descent-metrics.underline_position));
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
else
if (annotate->decorate == UnderlineDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*
metrics.underline_position);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
/*
Annotate image with text.
*/
status=RenderType(image,annotate,&offset,&metrics,exception);
if (status == MagickFalse)
break;
if (annotate->decorate == LineThroughDecoration)
{
annotate_info->affine.ty-=(draw_info->affine.sy*(height+
metrics.underline_position+metrics.descent)/2.0);
(void) CloneString(&annotate_info->primitive,primitive);
(void) DrawImage(image,annotate_info,exception);
}
}
/*
Relinquish resources.
*/
annotate_info=DestroyDrawInfo(annotate_info);
annotate=DestroyDrawInfo(annotate);
textlist=(char **) RelinquishMagickMemory(textlist);
return(status);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1588
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void arm_timer(struct k_itimer *timer, union cpu_time_count now)
{
struct task_struct *p = timer->it.cpu.task;
struct list_head *head, *listpos;
struct cpu_timer_list *const nt = &timer->it.cpu;
struct cpu_timer_list *next;
unsigned long i;
head = (CPUCLOCK_PERTHREAD(timer->it_clock) ?
p->cpu_timers : p->signal->cpu_timers);
head += CPUCLOCK_WHICH(timer->it_clock);
BUG_ON(!irqs_disabled());
spin_lock(&p->sighand->siglock);
listpos = head;
if (CPUCLOCK_WHICH(timer->it_clock) == CPUCLOCK_SCHED) {
list_for_each_entry(next, head, entry) {
if (next->expires.sched > nt->expires.sched)
break;
listpos = &next->entry;
}
} else {
list_for_each_entry(next, head, entry) {
if (cputime_gt(next->expires.cpu, nt->expires.cpu))
break;
listpos = &next->entry;
}
}
list_add(&nt->entry, listpos);
if (listpos == head) {
/*
* We are the new earliest-expiring timer.
* If we are a thread timer, there can always
* be a process timer telling us to stop earlier.
*/
if (CPUCLOCK_PERTHREAD(timer->it_clock)) {
switch (CPUCLOCK_WHICH(timer->it_clock)) {
default:
BUG();
case CPUCLOCK_PROF:
if (cputime_eq(p->it_prof_expires,
cputime_zero) ||
cputime_gt(p->it_prof_expires,
nt->expires.cpu))
p->it_prof_expires = nt->expires.cpu;
break;
case CPUCLOCK_VIRT:
if (cputime_eq(p->it_virt_expires,
cputime_zero) ||
cputime_gt(p->it_virt_expires,
nt->expires.cpu))
p->it_virt_expires = nt->expires.cpu;
break;
case CPUCLOCK_SCHED:
if (p->it_sched_expires == 0 ||
p->it_sched_expires > nt->expires.sched)
p->it_sched_expires = nt->expires.sched;
break;
}
} else {
/*
* For a process timer, we must balance
* all the live threads' expirations.
*/
switch (CPUCLOCK_WHICH(timer->it_clock)) {
default:
BUG();
case CPUCLOCK_VIRT:
if (!cputime_eq(p->signal->it_virt_expires,
cputime_zero) &&
cputime_lt(p->signal->it_virt_expires,
timer->it.cpu.expires.cpu))
break;
goto rebalance;
case CPUCLOCK_PROF:
if (!cputime_eq(p->signal->it_prof_expires,
cputime_zero) &&
cputime_lt(p->signal->it_prof_expires,
timer->it.cpu.expires.cpu))
break;
i = p->signal->rlim[RLIMIT_CPU].rlim_cur;
if (i != RLIM_INFINITY &&
i <= cputime_to_secs(timer->it.cpu.expires.cpu))
break;
goto rebalance;
case CPUCLOCK_SCHED:
rebalance:
process_timer_rebalance(
timer->it.cpu.task,
CPUCLOCK_WHICH(timer->it_clock),
timer->it.cpu.expires, now);
break;
}
}
}
spin_unlock(&p->sighand->siglock);
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void f2fs_destroy_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et = F2FS_I(inode)->extent_tree;
unsigned int node_cnt = 0;
if (!et)
return;
if (inode->i_nlink && !is_bad_inode(inode) &&
atomic_read(&et->node_cnt)) {
mutex_lock(&sbi->extent_tree_lock);
list_add_tail(&et->list, &sbi->zombie_list);
atomic_inc(&sbi->total_zombie_tree);
mutex_unlock(&sbi->extent_tree_lock);
return;
}
/* free all extent info belong to this extent tree */
node_cnt = f2fs_destroy_extent_node(inode);
/* delete extent tree entry in radix tree */
mutex_lock(&sbi->extent_tree_lock);
f2fs_bug_on(sbi, atomic_read(&et->node_cnt));
radix_tree_delete(&sbi->extent_tree_root, inode->i_ino);
kmem_cache_free(extent_tree_slab, et);
atomic_dec(&sbi->total_ext_tree);
mutex_unlock(&sbi->extent_tree_lock);
F2FS_I(inode)->extent_tree = NULL;
trace_f2fs_destroy_extent_tree(inode, node_cnt);
}
Commit Message: f2fs: fix a bug caused by NULL extent tree
Thread A: Thread B:
-f2fs_remount
-sbi->mount_opt.opt = 0;
<--- -f2fs_iget
-do_read_inode
-f2fs_init_extent_tree
-F2FS_I(inode)->extent_tree is NULL
-default_options && parse_options
-remount return
<--- -f2fs_map_blocks
-f2fs_lookup_extent_tree
-f2fs_bug_on(sbi, !et);
The same problem with f2fs_new_inode.
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int err;
int peeked, skip;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
msg->msg_namelen = 0;
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(sock_rcvtimeo(sk, noblock));
goto out;
}
skip = sk_peek_offset(sk, flags);
skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err);
if (!skb) {
unix_state_lock(sk);
/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
(sk->sk_shutdown & RCV_SHUTDOWN))
err = 0;
unix_state_unlock(sk);
goto out_unlock;
}
wake_up_interruptible_sync_poll(&u->peer_wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
if (msg->msg_name)
unix_copy_addr(msg, skb->sk);
if (size > skb->len - skip)
size = skb->len - skip;
else if (size < skb->len - skip)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size);
if (err)
goto out_free;
if (sock_flag(sk, SOCK_RCVTSTAMP))
__sock_recv_timestamp(msg, sk, skb);
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
unix_set_secdata(siocb->scm, skb);
if (!(flags & MSG_PEEK)) {
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
sk_peek_offset_bwd(sk, skb->len);
} else {
/* It is questionable: on PEEK we could:
- do not return fds - good, but too simple 8)
- return fds, and do not return them on read (old strategy,
apparently wrong)
- clone fds (I chose it for now, it is the most universal
solution)
POSIX 1003.1g does not actually define this clearly
at all. POSIX 1003.1g doesn't define a lot of things
clearly however!
*/
sk_peek_offset_fwd(sk, size);
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
}
err = (flags & MSG_TRUNC) ? skb->len - skip : size;
scm_recv(sock, msg, siocb->scm, flags);
out_free:
skb_free_datagram(sk, skb);
out_unlock:
mutex_unlock(&u->readlock);
out:
return err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static const struct hid_device_id *hid_match_device(struct hid_device *hdev,
struct hid_driver *hdrv)
{
struct hid_dynid *dynid;
spin_lock(&hdrv->dyn_lock);
list_for_each_entry(dynid, &hdrv->dyn_list, list) {
if (hid_match_one_id(hdev, &dynid->id)) {
spin_unlock(&hdrv->dyn_lock);
return &dynid->id;
}
}
spin_unlock(&hdrv->dyn_lock);
return hid_match_id(hdev, hdrv->id_table);
}
Commit Message: HID: core: prevent out-of-bound readings
Plugging a Logitech DJ receiver with KASAN activated raises a bunch of
out-of-bound readings.
The fields are allocated up to MAX_USAGE, meaning that potentially, we do
not have enough fields to fit the incoming values.
Add checks and silence KASAN.
Signed-off-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int parse_size_uint(const char *size, guint *bytes)
{
const char *desc;
guint number, multiplier, limit;
int len;
*bytes = 0;
/* max. return value is about 1.6 years */
number = 0;
while (*size != '\0') {
if (i_isdigit(*size)) {
char *endptr;
if (!parse_uint(size, &endptr, 10, &number)) {
return FALSE;
}
size = endptr;
continue;
}
/* skip punctuation */
while (*size != '\0' && i_ispunct(*size))
size++;
/* get description */
for (len = 0, desc = size; i_isalpha(*size); size++)
len++;
if (len == 0) {
if (number == 0) {
/* "0" - allow it */
return TRUE;
}
*bytes += number*1024; /* assume kilobytes */
return FALSE;
}
multiplier = 0;
limit = 0;
if (g_ascii_strncasecmp(desc, "gbytes", len) == 0) {
multiplier = 1U << 30;
limit = 2U << 0;
}
if (g_ascii_strncasecmp(desc, "mbytes", len) == 0) {
multiplier = 1U << 20;
limit = 2U << 10;
}
if (g_ascii_strncasecmp(desc, "kbytes", len) == 0) {
multiplier = 1U << 10;
limit = 2U << 20;
}
if (g_ascii_strncasecmp(desc, "bytes", len) == 0) {
multiplier = 1;
limit = 2U << 30;
}
if (limit && number > limit) {
return FALSE;
}
*bytes += number * multiplier;
/* skip punctuation */
while (*size != '\0' && i_ispunct(*size))
size++;
}
return TRUE;
}
Commit Message: Merge branch 'security' into 'master'
Security
Closes #10
See merge request !17
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: SYSCALL_DEFINE5(perf_event_open,
struct perf_event_attr __user *, attr_uptr,
pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
{
struct perf_event *group_leader = NULL, *output_event = NULL;
struct perf_event *event, *sibling;
struct perf_event_attr attr;
struct perf_event_context *ctx;
struct file *event_file = NULL;
struct fd group = {NULL, 0};
struct task_struct *task = NULL;
struct pmu *pmu;
int event_fd;
int move_group = 0;
int err;
int f_flags = O_RDWR;
/* for future expandability... */
if (flags & ~PERF_FLAG_ALL)
return -EINVAL;
err = perf_copy_attr(attr_uptr, &attr);
if (err)
return err;
if (!attr.exclude_kernel) {
if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
return -EACCES;
}
if (attr.freq) {
if (attr.sample_freq > sysctl_perf_event_sample_rate)
return -EINVAL;
} else {
if (attr.sample_period & (1ULL << 63))
return -EINVAL;
}
/*
* In cgroup mode, the pid argument is used to pass the fd
* opened to the cgroup directory in cgroupfs. The cpu argument
* designates the cpu on which to monitor threads from that
* cgroup.
*/
if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
return -EINVAL;
if (flags & PERF_FLAG_FD_CLOEXEC)
f_flags |= O_CLOEXEC;
event_fd = get_unused_fd_flags(f_flags);
if (event_fd < 0)
return event_fd;
if (group_fd != -1) {
err = perf_fget_light(group_fd, &group);
if (err)
goto err_fd;
group_leader = group.file->private_data;
if (flags & PERF_FLAG_FD_OUTPUT)
output_event = group_leader;
if (flags & PERF_FLAG_FD_NO_GROUP)
group_leader = NULL;
}
if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
task = find_lively_task_by_vpid(pid);
if (IS_ERR(task)) {
err = PTR_ERR(task);
goto err_group_fd;
}
}
if (task && group_leader &&
group_leader->attr.inherit != attr.inherit) {
err = -EINVAL;
goto err_task;
}
get_online_cpus();
event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
NULL, NULL);
if (IS_ERR(event)) {
err = PTR_ERR(event);
goto err_cpus;
}
if (flags & PERF_FLAG_PID_CGROUP) {
err = perf_cgroup_connect(pid, event, &attr, group_leader);
if (err) {
__free_event(event);
goto err_cpus;
}
}
if (is_sampling_event(event)) {
if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
err = -ENOTSUPP;
goto err_alloc;
}
}
account_event(event);
/*
* Special case software events and allow them to be part of
* any hardware group.
*/
pmu = event->pmu;
if (group_leader &&
(is_software_event(event) != is_software_event(group_leader))) {
if (is_software_event(event)) {
/*
* If event and group_leader are not both a software
* event, and event is, then group leader is not.
*
* Allow the addition of software events to !software
* groups, this is safe because software events never
* fail to schedule.
*/
pmu = group_leader->pmu;
} else if (is_software_event(group_leader) &&
(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
/*
* In case the group is a pure software group, and we
* try to add a hardware event, move the whole group to
* the hardware context.
*/
move_group = 1;
}
}
/*
* Get the target context (task or percpu):
*/
ctx = find_get_context(pmu, task, event->cpu);
if (IS_ERR(ctx)) {
err = PTR_ERR(ctx);
goto err_alloc;
}
if (task) {
put_task_struct(task);
task = NULL;
}
/*
* Look up the group leader (we will attach this event to it):
*/
if (group_leader) {
err = -EINVAL;
/*
* Do not allow a recursive hierarchy (this new sibling
* becoming part of another group-sibling):
*/
if (group_leader->group_leader != group_leader)
goto err_context;
/*
* Do not allow to attach to a group in a different
* task or CPU context:
*/
if (move_group) {
/*
* Make sure we're both on the same task, or both
* per-cpu events.
*/
if (group_leader->ctx->task != ctx->task)
goto err_context;
/*
* Make sure we're both events for the same CPU;
* grouping events for different CPUs is broken; since
* you can never concurrently schedule them anyhow.
*/
if (group_leader->cpu != event->cpu)
goto err_context;
} else {
if (group_leader->ctx != ctx)
goto err_context;
}
/*
* Only a group leader can be exclusive or pinned
*/
if (attr.exclusive || attr.pinned)
goto err_context;
}
if (output_event) {
err = perf_event_set_output(event, output_event);
if (err)
goto err_context;
}
event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
f_flags);
if (IS_ERR(event_file)) {
err = PTR_ERR(event_file);
goto err_context;
}
if (move_group) {
struct perf_event_context *gctx = group_leader->ctx;
mutex_lock(&gctx->mutex);
perf_remove_from_context(group_leader, false);
/*
* Removing from the context ends up with disabled
* event. What we want here is event in the initial
* startup state, ready to be add into new context.
*/
perf_event__state_init(group_leader);
list_for_each_entry(sibling, &group_leader->sibling_list,
group_entry) {
perf_remove_from_context(sibling, false);
perf_event__state_init(sibling);
put_ctx(gctx);
}
mutex_unlock(&gctx->mutex);
put_ctx(gctx);
}
WARN_ON_ONCE(ctx->parent_ctx);
mutex_lock(&ctx->mutex);
if (move_group) {
synchronize_rcu();
perf_install_in_context(ctx, group_leader, group_leader->cpu);
get_ctx(ctx);
list_for_each_entry(sibling, &group_leader->sibling_list,
group_entry) {
perf_install_in_context(ctx, sibling, sibling->cpu);
get_ctx(ctx);
}
}
perf_install_in_context(ctx, event, event->cpu);
perf_unpin_context(ctx);
mutex_unlock(&ctx->mutex);
put_online_cpus();
event->owner = current;
mutex_lock(¤t->perf_event_mutex);
list_add_tail(&event->owner_entry, ¤t->perf_event_list);
mutex_unlock(¤t->perf_event_mutex);
/*
* Precalculate sample_data sizes
*/
perf_event__header_size(event);
perf_event__id_header_size(event);
/*
* Drop the reference on the group_event after placing the
* new event on the sibling_list. This ensures destruction
* of the group leader will find the pointer to itself in
* perf_group_detach().
*/
fdput(group);
fd_install(event_fd, event_file);
return event_fd;
err_context:
perf_unpin_context(ctx);
put_ctx(ctx);
err_alloc:
free_event(event);
err_cpus:
put_online_cpus();
err_task:
if (task)
put_task_struct(task);
err_group_fd:
fdput(group);
err_fd:
put_unused_fd(event_fd);
return err;
}
Commit Message: perf: Fix event->ctx locking
There have been a few reported issues wrt. the lack of locking around
changing event->ctx. This patch tries to address those.
It avoids the whole rwsem thing; and while it appears to work, please
give it some thought in review.
What I did fail at is sensible runtime checks on the use of
event->ctx, the RCU use makes it very hard.
Signed-off-by: Peter Zijlstra (Intel) <[email protected]>
Cc: Paul E. McKenney <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Arnaldo Carvalho de Melo <[email protected]>
Cc: Linus Torvalds <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: static void CL_OldGame(void)
{
if(cl_oldGameSet)
{
cl_oldGameSet = qfalse;
Cvar_Set2("fs_game", cl_oldGame, qtrue);
FS_ConditionalRestart(clc.checksumFeed, qfalse);
}
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: RenderFrameObserverNatives::RenderFrameObserverNatives(ScriptContext* context)
: ObjectBackedNativeHandler(context), weak_ptr_factory_(this) {
RouteFunction(
"OnDocumentElementCreated",
base::Bind(&RenderFrameObserverNatives::OnDocumentElementCreated,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
Commit Message: CVE-2017-13002/AODV: Add some missing bounds checks.
In aodv_extension() do a bounds check on the extension header before we
look at it.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add a test using the capture file supplied by the reporter(s).
While we're at it, add the RFC number, and check the validity of the
length for the Hello extension.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void SetHeaderFromIPL(Image *image, IPLInfo *ipl){
image->columns = ipl->width;
image->rows = ipl->height;
image->depth = ipl->depth;
image->x_resolution = 1;
image->y_resolution = 1;
}
Commit Message: ...
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip,
impeg2d_video_decode_op_t *ps_op)
{
UWORD32 u4_bits_read;
dec_state_t *ps_dec;
UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
ps_dec = (dec_state_t *)pv_dec;
ps_op->s_ivd_video_decode_op_t.u4_error_code = 0;
if (u4_size > MAX_BITSTREAM_BUFFER_SIZE)
{
u4_size = MAX_BITSTREAM_BUFFER_SIZE;
}
memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size);
impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer,
u4_size);
{
{
IMPEG2D_ERROR_CODES_T e_error;
e_error = impeg2d_process_video_header(ps_dec);
if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0)
ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error;
if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0;
ps_dec->u2_header_done = 0;
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width;
}
impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE);
return;
}
}
ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size;
ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size;
ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME;
ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS;
u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream);
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3;
if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes)
{
ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes;
}
ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0;
/* MOD */
ps_dec->u2_header_done = 1;
}
}
Commit Message: Adding check for min_width and min_height
Add check for min_wd and min_ht. Stride is updated if header
decode is done.
Bug: 74078669
Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd
(cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da)
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
RequestGlobalDumpCallback callback) {
const auto& coordinator = GetCoordinatorBindingForCurrentThread();
coordinator->GetVmRegionsForHeapProfiler(callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269
Target: 1
Example 2:
Code: int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
#if defined(OS_WIN) && !defined(USE_AURA)
switch (app_command_id) {
case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
case APPCOMMAND_NEW: return IDC_NEW_TAB;
case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
case APPCOMMAND_PRINT: return IDC_PRINT;
case APPCOMMAND_COPY: return IDC_COPY;
case APPCOMMAND_CUT: return IDC_CUT;
case APPCOMMAND_PASTE: return IDC_PASTE;
case APPCOMMAND_UNDO:
case APPCOMMAND_REDO:
case APPCOMMAND_SPELL_CHECK:
default: return -1;
}
#else
return -1;
#endif
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGLRenderingContextBase::BufferDataImpl(GLenum target,
int64_t size,
const void* data,
GLenum usage) {
WebGLBuffer* buffer = ValidateBufferDataTarget("bufferData", target);
if (!buffer)
return;
if (!ValidateBufferDataUsage("bufferData", usage))
return;
if (!ValidateValueFitNonNegInt32("bufferData", "size", size))
return;
buffer->SetSize(size);
ContextGL()->BufferData(target, static_cast<GLsizeiptr>(size), data, usage);
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: read_header(struct archive_read *a, struct archive_entry *entry,
char head_type)
{
const void *h;
const char *p, *endp;
struct rar *rar;
struct rar_header rar_header;
struct rar_file_header file_header;
int64_t header_size;
unsigned filename_size, end;
char *filename;
char *strp;
char packed_size[8];
char unp_size[8];
int ttime;
struct archive_string_conv *sconv, *fn_sconv;
unsigned long crc32_val;
int ret = (ARCHIVE_OK), ret2;
rar = (struct rar *)(a->format->data);
/* Setup a string conversion object for non-rar-unicode filenames. */
sconv = rar->opt_sconv;
if (sconv == NULL) {
if (!rar->init_default_conversion) {
rar->sconv_default =
archive_string_default_conversion_for_read(
&(a->archive));
rar->init_default_conversion = 1;
}
sconv = rar->sconv_default;
}
if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
p = h;
memcpy(&rar_header, p, sizeof(rar_header));
rar->file_flags = archive_le16dec(rar_header.flags);
header_size = archive_le16dec(rar_header.size);
if (header_size < (int64_t)sizeof(file_header) + 7) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2);
__archive_read_consume(a, 7);
if (!(rar->file_flags & FHD_SOLID))
{
rar->compression_method = 0;
rar->packed_size = 0;
rar->unp_size = 0;
rar->mtime = 0;
rar->ctime = 0;
rar->atime = 0;
rar->arctime = 0;
rar->mode = 0;
memset(&rar->salt, 0, sizeof(rar->salt));
rar->atime = 0;
rar->ansec = 0;
rar->ctime = 0;
rar->cnsec = 0;
rar->mtime = 0;
rar->mnsec = 0;
rar->arctime = 0;
rar->arcnsec = 0;
}
else
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"RAR solid archive support unavailable.");
return (ARCHIVE_FATAL);
}
if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
/* File Header CRC check. */
crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7));
if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Header CRC error");
return (ARCHIVE_FATAL);
}
/* If no CRC error, Go on parsing File Header. */
p = h;
endp = p + header_size - 7;
memcpy(&file_header, p, sizeof(file_header));
p += sizeof(file_header);
rar->compression_method = file_header.method;
ttime = archive_le32dec(file_header.file_time);
rar->mtime = get_time(ttime);
rar->file_crc = archive_le32dec(file_header.file_crc);
if (rar->file_flags & FHD_PASSWORD)
{
archive_entry_set_is_data_encrypted(entry, 1);
rar->has_encrypted_entries = 1;
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"RAR encryption support unavailable.");
/* Since it is only the data part itself that is encrypted we can at least
extract information about the currently processed entry and don't need
to return ARCHIVE_FATAL here. */
/*return (ARCHIVE_FATAL);*/
}
if (rar->file_flags & FHD_LARGE)
{
memcpy(packed_size, file_header.pack_size, 4);
memcpy(packed_size + 4, p, 4); /* High pack size */
p += 4;
memcpy(unp_size, file_header.unp_size, 4);
memcpy(unp_size + 4, p, 4); /* High unpack size */
p += 4;
rar->packed_size = archive_le64dec(&packed_size);
rar->unp_size = archive_le64dec(&unp_size);
}
else
{
rar->packed_size = archive_le32dec(file_header.pack_size);
rar->unp_size = archive_le32dec(file_header.unp_size);
}
if (rar->packed_size < 0 || rar->unp_size < 0)
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid sizes specified.");
return (ARCHIVE_FATAL);
}
rar->bytes_remaining = rar->packed_size;
/* TODO: RARv3 subblocks contain comments. For now the complete block is
* consumed at the end.
*/
if (head_type == NEWSUB_HEAD) {
size_t distance = p - (const char *)h;
header_size += rar->packed_size;
/* Make sure we have the extended data. */
if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
return (ARCHIVE_FATAL);
p = h;
endp = p + header_size - 7;
p += distance;
}
filename_size = archive_le16dec(file_header.name_size);
if (p + filename_size > endp) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid filename size");
return (ARCHIVE_FATAL);
}
if (rar->filename_allocated < filename_size * 2 + 2) {
char *newptr;
size_t newsize = filename_size * 2 + 2;
newptr = realloc(rar->filename, newsize);
if (newptr == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->filename = newptr;
rar->filename_allocated = newsize;
}
filename = rar->filename;
memcpy(filename, p, filename_size);
filename[filename_size] = '\0';
if (rar->file_flags & FHD_UNICODE)
{
if (filename_size != strlen(filename))
{
unsigned char highbyte, flagbits, flagbyte;
unsigned fn_end, offset;
end = filename_size;
fn_end = filename_size * 2;
filename_size = 0;
offset = (unsigned)strlen(filename) + 1;
highbyte = *(p + offset++);
flagbits = 0;
flagbyte = 0;
while (offset < end && filename_size < fn_end)
{
if (!flagbits)
{
flagbyte = *(p + offset++);
flagbits = 8;
}
flagbits -= 2;
switch((flagbyte >> flagbits) & 3)
{
case 0:
filename[filename_size++] = '\0';
filename[filename_size++] = *(p + offset++);
break;
case 1:
filename[filename_size++] = highbyte;
filename[filename_size++] = *(p + offset++);
break;
case 2:
filename[filename_size++] = *(p + offset + 1);
filename[filename_size++] = *(p + offset);
offset += 2;
break;
case 3:
{
char extra, high;
uint8_t length = *(p + offset++);
if (length & 0x80) {
extra = *(p + offset++);
high = (char)highbyte;
} else
extra = high = 0;
length = (length & 0x7f) + 2;
while (length && filename_size < fn_end) {
unsigned cp = filename_size >> 1;
filename[filename_size++] = high;
filename[filename_size++] = p[cp] + extra;
length--;
}
}
break;
}
}
if (filename_size > fn_end) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid filename");
return (ARCHIVE_FATAL);
}
filename[filename_size++] = '\0';
filename[filename_size++] = '\0';
/* Decoded unicode form is UTF-16BE, so we have to update a string
* conversion object for it. */
if (rar->sconv_utf16be == NULL) {
rar->sconv_utf16be = archive_string_conversion_from_charset(
&a->archive, "UTF-16BE", 1);
if (rar->sconv_utf16be == NULL)
return (ARCHIVE_FATAL);
}
fn_sconv = rar->sconv_utf16be;
strp = filename;
while (memcmp(strp, "\x00\x00", 2))
{
if (!memcmp(strp, "\x00\\", 2))
*(strp + 1) = '/';
strp += 2;
}
p += offset;
} else {
/*
* If FHD_UNICODE is set but no unicode data, this file name form
* is UTF-8, so we have to update a string conversion object for
* it accordingly.
*/
if (rar->sconv_utf8 == NULL) {
rar->sconv_utf8 = archive_string_conversion_from_charset(
&a->archive, "UTF-8", 1);
if (rar->sconv_utf8 == NULL)
return (ARCHIVE_FATAL);
}
fn_sconv = rar->sconv_utf8;
while ((strp = strchr(filename, '\\')) != NULL)
*strp = '/';
p += filename_size;
}
}
else
{
fn_sconv = sconv;
while ((strp = strchr(filename, '\\')) != NULL)
*strp = '/';
p += filename_size;
}
/* Split file in multivolume RAR. No more need to process header. */
if (rar->filename_save &&
filename_size == rar->filename_save_size &&
!memcmp(rar->filename, rar->filename_save, filename_size + 1))
{
__archive_read_consume(a, header_size - 7);
rar->cursor++;
if (rar->cursor >= rar->nodes)
{
rar->nodes++;
if ((rar->dbo =
realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL)
{
archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->dbo[rar->cursor].header_size = header_size;
rar->dbo[rar->cursor].start_offset = -1;
rar->dbo[rar->cursor].end_offset = -1;
}
if (rar->dbo[rar->cursor].start_offset < 0)
{
rar->dbo[rar->cursor].start_offset = a->filter->position;
rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
rar->packed_size;
}
return ret;
}
rar->filename_save = (char*)realloc(rar->filename_save,
filename_size + 1);
memcpy(rar->filename_save, rar->filename, filename_size + 1);
rar->filename_save_size = filename_size;
/* Set info for seeking */
free(rar->dbo);
if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
{
archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
return (ARCHIVE_FATAL);
}
rar->dbo[0].header_size = header_size;
rar->dbo[0].start_offset = -1;
rar->dbo[0].end_offset = -1;
rar->cursor = 0;
rar->nodes = 1;
if (rar->file_flags & FHD_SALT)
{
if (p + 8 > endp) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
memcpy(rar->salt, p, 8);
p += 8;
}
if (rar->file_flags & FHD_EXTTIME) {
if (read_exttime(p, rar, endp) < 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid header size");
return (ARCHIVE_FATAL);
}
}
__archive_read_consume(a, header_size - 7);
rar->dbo[0].start_offset = a->filter->position;
rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
switch(file_header.host_os)
{
case OS_MSDOS:
case OS_OS2:
case OS_WIN32:
rar->mode = archive_le32dec(file_header.file_attr);
if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
else
rar->mode = AE_IFREG;
rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
break;
case OS_UNIX:
case OS_MAC_OS:
case OS_BEOS:
rar->mode = archive_le32dec(file_header.file_attr);
break;
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown file attributes from RAR file's host OS");
return (ARCHIVE_FATAL);
}
rar->bytes_uncopied = rar->bytes_unconsumed = 0;
rar->lzss.position = rar->offset = 0;
rar->offset_seek = 0;
rar->dictionary_size = 0;
rar->offset_outgoing = 0;
rar->br.cache_avail = 0;
rar->br.avail_in = 0;
rar->crc_calculated = 0;
rar->entry_eof = 0;
rar->valid = 1;
rar->is_ppmd_block = 0;
rar->start_new_table = 1;
free(rar->unp_buffer);
rar->unp_buffer = NULL;
rar->unp_offset = 0;
rar->unp_buffer_size = UNP_BUFFER_SIZE;
memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
__archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
rar->ppmd_valid = rar->ppmd_eod = 0;
/* Don't set any archive entries for non-file header types */
if (head_type == NEWSUB_HEAD)
return ret;
archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
archive_entry_set_atime(entry, rar->atime, rar->ansec);
archive_entry_set_size(entry, rar->unp_size);
archive_entry_set_mode(entry, rar->mode);
if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
{
if (errno == ENOMEM)
{
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname cannot be converted from %s to current locale.",
archive_string_conversion_charset_name(fn_sconv));
ret = (ARCHIVE_WARN);
}
if (((rar->mode) & AE_IFMT) == AE_IFLNK)
{
/* Make sure a symbolic-link file does not have its body. */
rar->bytes_remaining = 0;
archive_entry_set_size(entry, 0);
/* Read a symbolic-link name. */
if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
return ret2;
if (ret > ret2)
ret = ret2;
}
if (rar->bytes_remaining == 0)
rar->entry_eof = 1;
return ret;
}
Commit Message: Avoid a read off-by-one error for UTF16 names in RAR archives.
Reported-By: OSS-Fuzz issue 573
CWE ID: CWE-125
Target: 1
Example 2:
Code: static bool HasParameterMapArg(FixedArray* parameter_map, uint32_t index) {
uint32_t length = parameter_map->length() - 2;
if (index >= length) return false;
return !parameter_map->get(index + 2)->IsTheHole(
parameter_map->GetIsolate());
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
const unsigned char **keystr)
{
int j;
j = makekey(pkt->body + pkt->savedpos,
pkt->length - pkt->savedpos,
key, keystr, 0);
if (j < 0)
return FALSE;
pkt->savedpos += j;
assert(pkt->savedpos < pkt->length);
return TRUE;
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: pimv2_addr_print(netdissect_options *ndo,
const u_char *bp, enum pimv2_addrtype at, int silent)
{
int af;
int len, hdrlen;
ND_TCHECK(bp[0]);
if (pimv2_addr_len == 0) {
ND_TCHECK(bp[1]);
switch (bp[0]) {
case 1:
af = AF_INET;
len = sizeof(struct in_addr);
break;
case 2:
af = AF_INET6;
len = sizeof(struct in6_addr);
break;
default:
return -1;
}
if (bp[1] != 0)
return -1;
hdrlen = 2;
} else {
switch (pimv2_addr_len) {
case sizeof(struct in_addr):
af = AF_INET;
break;
case sizeof(struct in6_addr):
af = AF_INET6;
break;
default:
return -1;
break;
}
len = pimv2_addr_len;
hdrlen = 0;
}
bp += hdrlen;
switch (at) {
case pimv2_unicast:
ND_TCHECK2(bp[0], len);
if (af == AF_INET) {
if (!silent)
ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp)));
}
else if (af == AF_INET6) {
if (!silent)
ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp)));
}
return hdrlen + len;
case pimv2_group:
case pimv2_source:
ND_TCHECK2(bp[0], len + 2);
if (af == AF_INET) {
if (!silent) {
ND_PRINT((ndo, "%s", ipaddr_string(ndo, bp + 2)));
if (bp[1] != 32)
ND_PRINT((ndo, "/%u", bp[1]));
}
}
else if (af == AF_INET6) {
if (!silent) {
ND_PRINT((ndo, "%s", ip6addr_string(ndo, bp + 2)));
if (bp[1] != 128)
ND_PRINT((ndo, "/%u", bp[1]));
}
}
if (bp[0] && !silent) {
if (at == pimv2_group) {
ND_PRINT((ndo, "(0x%02x)", bp[0]));
} else {
ND_PRINT((ndo, "(%s%s%s",
bp[0] & 0x04 ? "S" : "",
bp[0] & 0x02 ? "W" : "",
bp[0] & 0x01 ? "R" : ""));
if (bp[0] & 0xf8) {
ND_PRINT((ndo, "+0x%02x", bp[0] & 0xf8));
}
ND_PRINT((ndo, ")"));
}
}
return hdrlen + 2 + len;
default:
return -1;
}
trunc:
return -1;
}
Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks.
Use ND_TCHECK macros to do bounds checking, and add length checks before
the bounds checks.
Add a bounds check that the review process found was missing.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update one test output file to reflect the changes.
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void *php_libxml_streams_IO_open_write_wrapper(const char *filename)
{
return php_libxml_streams_IO_open_wrapper(filename, "wb", 0);
}
Commit Message:
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RunMemCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
const int count_test_block = 1000;
DECLARE_ALIGNED_ARRAY(16, int16_t, input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, input_extreme_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_ref_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, output_block, kNumCoeffs);
for (int i = 0; i < count_test_block; ++i) {
for (int j = 0; j < kNumCoeffs; ++j) {
input_block[j] = rnd.Rand8() - rnd.Rand8();
input_extreme_block[j] = rnd.Rand8() % 2 ? 255 : -255;
}
if (i == 0)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = 255;
if (i == 1)
for (int j = 0; j < kNumCoeffs; ++j)
input_extreme_block[j] = -255;
fwd_txfm_ref(input_extreme_block, output_ref_block, pitch_, tx_type_);
REGISTER_STATE_CHECK(RunFwdTxfm(input_extreme_block,
output_block, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
EXPECT_EQ(output_block[j], output_ref_block[j]);
EXPECT_GE(4 * DCT_MAX_VALUE, abs(output_block[j]))
<< "Error: 16x16 FDCT has coefficient larger than 4*DCT_MAX_VALUE";
}
}
}
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
Target: 1
Example 2:
Code: void Document::clearFocusedElementSoon()
{
if (!m_clearFocusedElementTimer.isActive())
m_clearFocusedElementTimer.startOneShot(0, BLINK_FROM_HERE);
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool AddPolicyForGPU(CommandLine* cmd_line, sandbox::TargetPolicy* policy) {
#if !defined(NACL_WIN64) // We don't need this code on win nacl64.
if (base::win::GetVersion() > base::win::VERSION_SERVER_2003) {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationDesktopName) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetDelayedIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
} else {
if (cmd_line->GetSwitchValueASCII(switches::kUseGL) ==
gfx::kGLImplementationSwiftShaderName ||
cmd_line->HasSwitch(switches::kReduceGpuSandbox)) {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_LIMITED);
policy->SetJobLevel(sandbox::JOB_LIMITED_USER,
JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS |
JOB_OBJECT_UILIMIT_DESKTOP |
JOB_OBJECT_UILIMIT_EXITWINDOWS |
JOB_OBJECT_UILIMIT_DISPLAYSETTINGS);
} else {
policy->SetTokenLevel(sandbox::USER_RESTRICTED_SAME_ACCESS,
sandbox::USER_RESTRICTED);
policy->SetJobLevel(sandbox::JOB_LOCKDOWN,
JOB_OBJECT_UILIMIT_HANDLES);
}
policy->SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW);
}
} else {
policy->SetJobLevel(sandbox::JOB_UNPROTECTED, 0);
policy->SetTokenLevel(sandbox::USER_UNPROTECTED,
sandbox::USER_LIMITED);
}
sandbox::ResultCode result = policy->AddRule(
sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
L"\\\\.\\pipe\\chrome.gpu.*");
if (result != sandbox::SBOX_ALL_OK)
return false;
AddGenericDllEvictionPolicy(policy);
#endif
return true;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: spnego_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle,
gss_qop_t qop_req, gss_iov_buffer_desc *iov,
int iov_count)
{
return gss_get_mic_iov(minor_status, context_handle, qop_req, iov,
iov_count);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18
Target: 1
Example 2:
Code: static void intel_pmu_drain_pebs_core(struct pt_regs *iregs)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct debug_store *ds = cpuc->ds;
struct perf_event *event = cpuc->events[0]; /* PMC0 only */
struct pebs_record_core *at, *top;
int n;
if (!x86_pmu.pebs_active)
return;
at = (struct pebs_record_core *)(unsigned long)ds->pebs_buffer_base;
top = (struct pebs_record_core *)(unsigned long)ds->pebs_index;
/*
* Whatever else happens, drain the thing
*/
ds->pebs_index = ds->pebs_buffer_base;
if (!test_bit(0, cpuc->active_mask))
return;
WARN_ON_ONCE(!event);
if (!event->attr.precise_ip)
return;
n = top - at;
if (n <= 0)
return;
/*
* Should not happen, we program the threshold at 1 and do not
* set a reset value.
*/
WARN_ON_ONCE(n > 1);
at += n - 1;
__intel_pmu_pebs_event(event, iregs, at);
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ProcPutImage(ClientPtr client)
{
GC *pGC;
DrawablePtr pDraw;
long length; /* length of scanline server padded */
long lengthProto; /* length of scanline protocol padded */
char *tmpImage;
REQUEST(xPutImageReq);
REQUEST_AT_LEAST_SIZE(xPutImageReq);
VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess);
if (stuff->format == XYBitmap) {
if ((stuff->depth != 1) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
}
else if (stuff->format == XYPixmap) {
if ((pDraw->depth != stuff->depth) ||
(stuff->leftPad >= (unsigned int) screenInfo.bitmapScanlinePad))
return BadMatch;
length = BitmapBytePad(stuff->width + stuff->leftPad);
length *= stuff->depth;
}
else if (stuff->format == ZPixmap) {
if ((pDraw->depth != stuff->depth) || (stuff->leftPad != 0))
return BadMatch;
length = PixmapBytePad(stuff->width, stuff->depth);
}
else {
client->errorValue = stuff->format;
return BadValue;
}
tmpImage = (char *) &stuff[1];
lengthProto = length;
if (lengthProto >= (INT32_MAX / stuff->height))
return BadLength;
if ((bytes_to_int32(lengthProto * stuff->height) +
bytes_to_int32(sizeof(xPutImageReq))) != client->req_len)
return BadLength;
ReformatImage(tmpImage, lengthProto * stuff->height,
stuff->format == ZPixmap ? BitsPerPixel(stuff->depth) : 1,
ClientOrder(client));
(*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, stuff->dstX, stuff->dstY,
stuff->width, stuff->height,
stuff->leftPad, stuff->format, tmpImage);
return Success;
}
Commit Message:
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke.alpha=(Quantum) TransparentAlpha;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
stroke_polygon=TraceStrokePolygon(draw_info,p);
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
if (status == 0)
break;
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
q=p+p->coordinates-1;
closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
MagickTrue : MagickFalse;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
DrawRoundLinecap(image,draw_info,p,exception);
DrawRoundLinecap(image,draw_info,q,exception);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
Commit Message: Prevent buffer overflow in magick/draw.c
CWE ID: CWE-119
Target: 1
Example 2:
Code: virtual ~Private() {}
Commit Message:
CWE ID: CWE-290
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WORD32 ihevcd_parse_transform_tree(codec_t *ps_codec,
WORD32 x0, WORD32 y0,
WORD32 cu_x_base, WORD32 cu_y_base,
WORD32 log2_trafo_size,
WORD32 trafo_depth,
WORD32 blk_idx,
WORD32 intra_pred_mode)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
sps_t *ps_sps;
pps_t *ps_pps;
WORD32 value;
WORD32 x1, y1;
WORD32 max_trafo_depth;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 intra_split_flag;
WORD32 split_transform_flag;
WORD32 ctxt_idx;
cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac;
max_trafo_depth = ps_codec->s_parse.s_cu.i4_max_trafo_depth;
ps_sps = ps_codec->s_parse.ps_sps;
ps_pps = ps_codec->s_parse.ps_pps;
intra_split_flag = ps_codec->s_parse.s_cu.i4_intra_split_flag;
{
split_transform_flag = 0;
if((log2_trafo_size <= ps_sps->i1_log2_max_transform_block_size) &&
(log2_trafo_size > ps_sps->i1_log2_min_transform_block_size) &&
(trafo_depth < max_trafo_depth) &&
!(intra_split_flag && (trafo_depth == 0)))
{
/* encode the split transform flag, context derived as per Table9-37 */
ctxt_idx = IHEVC_CAB_SPLIT_TFM + (5 - log2_trafo_size);
TRACE_CABAC_CTXT("split_transform_flag", ps_cabac->u4_range, ctxt_idx);
split_transform_flag = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx);
AEV_TRACE("split_transform_flag", split_transform_flag,
ps_cabac->u4_range);
}
else
{
WORD32 inter_split_flag = 0;
if((0 == ps_sps->i1_max_transform_hierarchy_depth_inter) &&
(PRED_MODE_INTER == ps_codec->s_parse.s_cu.i4_pred_mode) &&
(PART_2Nx2N != ps_codec->s_parse.s_cu.i4_part_mode) &&
(0 == trafo_depth))
{
inter_split_flag = 1;
}
if((log2_trafo_size > ps_sps->i1_log2_max_transform_block_size) ||
((1 == intra_split_flag) && (0 == trafo_depth)) ||
(1 == inter_split_flag))
{
split_transform_flag = 1;
}
}
if(0 == trafo_depth)
{
ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = 0;
ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = 0;
}
else
{
ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1];
ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1];
}
if(trafo_depth == 0 || log2_trafo_size > 2)
{
ctxt_idx = IHEVC_CAB_CBCR_IDX + trafo_depth;
/* CBF for Cb/Cr is sent only if the parent CBF for Cb/Cr is non-zero */
if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth - 1])
{
TRACE_CABAC_CTXT("cbf_cb", ps_cabac->u4_range, ctxt_idx);
value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx);
AEV_TRACE("cbf_cb", value, ps_cabac->u4_range);
ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] = value;
}
if((trafo_depth == 0) || ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth - 1])
{
TRACE_CABAC_CTXT("cbf_cr", ps_cabac->u4_range, ctxt_idx);
value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx);
AEV_TRACE("cbf_cr", value, ps_cabac->u4_range);
ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth] = value;
}
}
if(split_transform_flag)
{
WORD32 intra_pred_mode_tmp;
x1 = x0 + ((1 << log2_trafo_size) >> 1);
y1 = y0 + ((1 << log2_trafo_size) >> 1);
/* For transform depth of zero, intra pred mode as decoded at CU */
/* level is sent to the transform tree nodes */
/* When depth is non-zero intra pred mode of parent node is sent */
/* This takes care of passing correct mode to all the child nodes */
intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0];
ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 0, intra_pred_mode_tmp);
intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[1];
ihevcd_parse_transform_tree(ps_codec, x1, y0, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 1, intra_pred_mode_tmp);
intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[2];
ihevcd_parse_transform_tree(ps_codec, x0, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 2, intra_pred_mode_tmp);
intra_pred_mode_tmp = trafo_depth ? intra_pred_mode : ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[3];
ihevcd_parse_transform_tree(ps_codec, x1, y1, x0, y0, log2_trafo_size - 1, trafo_depth + 1, 3, intra_pred_mode_tmp);
}
else
{
WORD32 ctb_x_base;
WORD32 ctb_y_base;
WORD32 cu_qp_delta_abs;
tu_t *ps_tu = ps_codec->s_parse.ps_tu;
cu_qp_delta_abs = 0;
ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size;
ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size;
if((ps_codec->s_parse.s_cu.i4_pred_mode == PRED_MODE_INTRA) ||
(trafo_depth != 0) ||
(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth]) ||
(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth]))
{
ctxt_idx = IHEVC_CAB_CBF_LUMA_IDX;
ctxt_idx += (trafo_depth == 0) ? 1 : 0;
TRACE_CABAC_CTXT("cbf_luma", ps_cabac->u4_range, ctxt_idx);
value = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, ctxt_idx);
AEV_TRACE("cbf_luma", value, ps_cabac->u4_range);
ps_codec->s_parse.s_cu.i1_cbf_luma = value;
}
else
{
ps_codec->s_parse.s_cu.i1_cbf_luma = 1;
}
/* Initialize ps_tu to default values */
/* If required change this to WORD32 packed write */
ps_tu->b1_cb_cbf = 0;
ps_tu->b1_cr_cbf = 0;
ps_tu->b1_y_cbf = 0;
ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2);
ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2);
ps_tu->b1_transquant_bypass = ps_codec->s_parse.s_cu.i4_cu_transquant_bypass;
ps_tu->b3_size = (log2_trafo_size - 2);
ps_tu->b7_qp = ps_codec->s_parse.u4_qp;
ps_tu->b6_luma_intra_mode = intra_pred_mode;
ps_tu->b3_chroma_intra_mode_idx = ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx;
/* Section:7.3.12 Transform unit syntax inlined here */
if(ps_codec->s_parse.s_cu.i1_cbf_luma ||
ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth] ||
ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])
{
WORD32 intra_pred_mode_chroma;
if(ps_pps->i1_cu_qp_delta_enabled_flag && !ps_codec->s_parse.i4_is_cu_qp_delta_coded)
{
WORD32 c_max = TU_MAX_QP_DELTA_ABS;
WORD32 ctxt_inc = IHEVC_CAB_QP_DELTA_ABS;
WORD32 ctxt_inc_max = CTXT_MAX_QP_DELTA_ABS;
TRACE_CABAC_CTXT("cu_qp_delta_abs", ps_cabac->u4_range, ctxt_inc);
/* qp_delta_abs is coded as combination of tunary and eg0 code */
/* See Table 9-32 and Table 9-37 for details on cu_qp_delta_abs */
cu_qp_delta_abs = ihevcd_cabac_decode_bins_tunary(ps_cabac,
ps_bitstrm,
c_max,
ctxt_inc,
0,
ctxt_inc_max);
if(cu_qp_delta_abs >= c_max)
{
value = ihevcd_cabac_decode_bypass_bins_egk(ps_cabac, ps_bitstrm, 0);
cu_qp_delta_abs += value;
}
AEV_TRACE("cu_qp_delta_abs", cu_qp_delta_abs, ps_cabac->u4_range);
ps_codec->s_parse.i4_is_cu_qp_delta_coded = 1;
if(cu_qp_delta_abs)
{
value = ihevcd_cabac_decode_bypass_bin(ps_cabac, ps_bitstrm);
AEV_TRACE("cu_qp_delta_sign", value, ps_cabac->u4_range);
if(value)
cu_qp_delta_abs = -cu_qp_delta_abs;
}
ps_codec->s_parse.s_cu.i4_cu_qp_delta = cu_qp_delta_abs;
}
if(ps_codec->s_parse.s_cu.i1_cbf_luma)
{
ps_tu->b1_y_cbf = 1;
ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size, 0, intra_pred_mode);
}
if(4 == ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx)
intra_pred_mode_chroma = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0];
else
{
intra_pred_mode_chroma = gau1_intra_pred_chroma_modes[ps_codec->s_parse.s_cu.i4_intra_chroma_pred_mode_idx];
if(intra_pred_mode_chroma ==
ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0])
{
intra_pred_mode_chroma = INTRA_ANGULAR(34);
}
}
if(log2_trafo_size > 2)
{
if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth])
{
ps_tu->b1_cb_cbf = 1;
ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 1, intra_pred_mode_chroma);
}
if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])
{
ps_tu->b1_cr_cbf = 1;
ihevcd_parse_residual_coding(ps_codec, x0, y0, log2_trafo_size - 1, 2, intra_pred_mode_chroma);
}
}
else if(blk_idx == 3)
{
if(ps_codec->s_parse.s_cu.ai1_cbf_cb[trafo_depth])
{
ps_tu->b1_cb_cbf = 1;
ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 1, intra_pred_mode_chroma);
}
if(ps_codec->s_parse.s_cu.ai1_cbf_cr[trafo_depth])
{
ps_tu->b1_cr_cbf = 1;
ihevcd_parse_residual_coding(ps_codec, cu_x_base, cu_y_base, log2_trafo_size, 2, intra_pred_mode_chroma);
}
}
else
{
ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE;
}
}
else
{
if((3 != blk_idx) && (2 == log2_trafo_size))
{
ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE;
}
}
/* Set the first TU in CU flag */
{
if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) &&
(ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2))
{
ps_tu->b1_first_tu_in_cu = 1;
}
else
{
ps_tu->b1_first_tu_in_cu = 0;
}
}
ps_codec->s_parse.ps_tu++;
ps_codec->s_parse.s_cu.i4_tu_cnt++;
ps_codec->s_parse.i4_pic_tu_idx++;
}
}
return ret;
}
Commit Message: Fix in handling wrong cu_qp_delta
cu_qp_delta is now checked for the range as specified in the spec
Bug: 33966031
Change-Id: I00420bf68081af92e9f2be9af7ce58d0683094ca
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: svcauth_gss_accept_sec_context(struct svc_req *rqst,
struct rpc_gss_init_res *gr)
{
struct svc_rpc_gss_data *gd;
struct rpc_gss_cred *gc;
gss_buffer_desc recv_tok, seqbuf;
gss_OID mech;
OM_uint32 maj_stat = 0, min_stat = 0, ret_flags, seq;
log_debug("in svcauth_gss_accept_context()");
gd = SVCAUTH_PRIVATE(rqst->rq_xprt->xp_auth);
gc = (struct rpc_gss_cred *)rqst->rq_clntcred;
memset(gr, 0, sizeof(*gr));
/* Deserialize arguments. */
memset(&recv_tok, 0, sizeof(recv_tok));
if (!svc_getargs(rqst->rq_xprt, xdr_rpc_gss_init_args,
(caddr_t)&recv_tok))
return (FALSE);
gr->gr_major = gss_accept_sec_context(&gr->gr_minor,
&gd->ctx,
svcauth_gss_creds,
&recv_tok,
GSS_C_NO_CHANNEL_BINDINGS,
&gd->client_name,
&mech,
&gr->gr_token,
&ret_flags,
NULL,
NULL);
svc_freeargs(rqst->rq_xprt, xdr_rpc_gss_init_args, (caddr_t)&recv_tok);
log_status("accept_sec_context", gr->gr_major, gr->gr_minor);
if (gr->gr_major != GSS_S_COMPLETE &&
gr->gr_major != GSS_S_CONTINUE_NEEDED) {
badauth(gr->gr_major, gr->gr_minor, rqst->rq_xprt);
gd->ctx = GSS_C_NO_CONTEXT;
goto errout;
}
/*
* ANDROS: krb5 mechglue returns ctx of size 8 - two pointers,
* one to the mechanism oid, one to the internal_ctx_id
*/
if ((gr->gr_ctx.value = mem_alloc(sizeof(gss_union_ctx_id_desc))) == NULL) {
fprintf(stderr, "svcauth_gss_accept_context: out of memory\n");
goto errout;
}
memcpy(gr->gr_ctx.value, gd->ctx, sizeof(gss_union_ctx_id_desc));
gr->gr_ctx.length = sizeof(gss_union_ctx_id_desc);
/* gr->gr_win = 0x00000005; ANDROS: for debugging linux kernel version... */
gr->gr_win = sizeof(gd->seqmask) * 8;
/* Save client info. */
gd->sec.mech = mech;
gd->sec.qop = GSS_C_QOP_DEFAULT;
gd->sec.svc = gc->gc_svc;
gd->seq = gc->gc_seq;
gd->win = gr->gr_win;
if (gr->gr_major == GSS_S_COMPLETE) {
#ifdef SPKM
/* spkm3: no src_name (anonymous) */
if(!g_OID_equal(gss_mech_spkm3, mech)) {
#endif
maj_stat = gss_display_name(&min_stat, gd->client_name,
&gd->cname, &gd->sec.mech);
#ifdef SPKM
}
#endif
if (maj_stat != GSS_S_COMPLETE) {
log_status("display_name", maj_stat, min_stat);
goto errout;
}
#ifdef DEBUG
#ifdef HAVE_HEIMDAL
log_debug("accepted context for %.*s with "
"<mech {}, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
gd->sec.qop, gd->sec.svc);
#else
{
gss_buffer_desc mechname;
gss_oid_to_str(&min_stat, mech, &mechname);
log_debug("accepted context for %.*s with "
"<mech %.*s, qop %d, svc %d>",
gd->cname.length, (char *)gd->cname.value,
mechname.length, (char *)mechname.value,
gd->sec.qop, gd->sec.svc);
gss_release_buffer(&min_stat, &mechname);
}
#endif
#endif /* DEBUG */
seq = htonl(gr->gr_win);
seqbuf.value = &seq;
seqbuf.length = sizeof(seq);
gss_release_buffer(&min_stat, &gd->checksum);
maj_stat = gss_sign(&min_stat, gd->ctx, GSS_C_QOP_DEFAULT,
&seqbuf, &gd->checksum);
if (maj_stat != GSS_S_COMPLETE) {
goto errout;
}
rqst->rq_xprt->xp_verf.oa_flavor = RPCSEC_GSS;
rqst->rq_xprt->xp_verf.oa_base = gd->checksum.value;
rqst->rq_xprt->xp_verf.oa_length = gd->checksum.length;
}
return (TRUE);
errout:
gss_release_buffer(&min_stat, &gr->gr_token);
return (FALSE);
}
Commit Message: Fix gssrpc data leakage [CVE-2014-9423]
[MITKRB5-SA-2015-001] In svcauth_gss_accept_sec_context(), do not copy
bytes from the union context into the handle field we send to the
client. We do not use this handle field, so just supply a fixed
string of "xxxx".
In gss_union_ctx_id_struct, remove the unused "interposer" field which
was causing part of the union context to remain uninitialized.
ticket: 8058 (new)
target_version: 1.13.1
tags: pullup
CWE ID: CWE-200
Target: 1
Example 2:
Code: void ResetScreenHandler::RegisterMessages() {
AddCallback("cancelOnReset", &ResetScreenHandler::HandleOnCancel);
AddCallback("restartOnReset", &ResetScreenHandler::HandleOnRestart);
AddCallback("powerwashOnReset", &ResetScreenHandler::HandleOnPowerwash);
AddCallback("resetOnLearnMore", &ResetScreenHandler::HandleOnLearnMore);
}
Commit Message: Rollback option put behind the flag.
BUG=368860
Review URL: https://codereview.chromium.org/267393011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void get_v2rx_desc_bnum(u32 bnum_flag, int *out_bnum)
{
*out_bnum = hnae_get_field(bnum_flag,
HNS_RXD_BUFNUM_M, HNS_RXD_BUFNUM_S) + 1;
}
Commit Message: net: hns: Fix a skb used after free bug
skb maybe freed in hns_nic_net_xmit_hw() and return NETDEV_TX_OK,
which cause hns_nic_net_xmit to use a freed skb.
BUG: KASAN: use-after-free in hns_nic_net_xmit_hw+0x62c/0x940...
[17659.112635] alloc_debug_processing+0x18c/0x1a0
[17659.117208] __slab_alloc+0x52c/0x560
[17659.120909] kmem_cache_alloc_node+0xac/0x2c0
[17659.125309] __alloc_skb+0x6c/0x260
[17659.128837] tcp_send_ack+0x8c/0x280
[17659.132449] __tcp_ack_snd_check+0x9c/0xf0
[17659.136587] tcp_rcv_established+0x5a4/0xa70
[17659.140899] tcp_v4_do_rcv+0x27c/0x620
[17659.144687] tcp_prequeue_process+0x108/0x170
[17659.149085] tcp_recvmsg+0x940/0x1020
[17659.152787] inet_recvmsg+0x124/0x180
[17659.156488] sock_recvmsg+0x64/0x80
[17659.160012] SyS_recvfrom+0xd8/0x180
[17659.163626] __sys_trace_return+0x0/0x4
[17659.167506] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=23 cpu=1 pid=13
[17659.174000] free_debug_processing+0x1d4/0x2c0
[17659.178486] __slab_free+0x240/0x390
[17659.182100] kmem_cache_free+0x24c/0x270
[17659.186062] kfree_skbmem+0xa0/0xb0
[17659.189587] __kfree_skb+0x28/0x40
[17659.193025] napi_gro_receive+0x168/0x1c0
[17659.197074] hns_nic_rx_up_pro+0x58/0x90
[17659.201038] hns_nic_rx_poll_one+0x518/0xbc0
[17659.205352] hns_nic_common_poll+0x94/0x140
[17659.209576] net_rx_action+0x458/0x5e0
[17659.213363] __do_softirq+0x1b8/0x480
[17659.217062] run_ksoftirqd+0x64/0x80
[17659.220679] smpboot_thread_fn+0x224/0x310
[17659.224821] kthread+0x150/0x170
[17659.228084] ret_from_fork+0x10/0x40
BUG: KASAN: use-after-free in hns_nic_net_xmit+0x8c/0xc0...
[17751.080490] __slab_alloc+0x52c/0x560
[17751.084188] kmem_cache_alloc+0x244/0x280
[17751.088238] __build_skb+0x40/0x150
[17751.091764] build_skb+0x28/0x100
[17751.095115] __alloc_rx_skb+0x94/0x150
[17751.098900] __napi_alloc_skb+0x34/0x90
[17751.102776] hns_nic_rx_poll_one+0x180/0xbc0
[17751.107097] hns_nic_common_poll+0x94/0x140
[17751.111333] net_rx_action+0x458/0x5e0
[17751.115123] __do_softirq+0x1b8/0x480
[17751.118823] run_ksoftirqd+0x64/0x80
[17751.122437] smpboot_thread_fn+0x224/0x310
[17751.126575] kthread+0x150/0x170
[17751.129838] ret_from_fork+0x10/0x40
[17751.133454] INFO: Freed in kfree_skbmem+0xa0/0xb0 age=19 cpu=7 pid=43
[17751.139951] free_debug_processing+0x1d4/0x2c0
[17751.144436] __slab_free+0x240/0x390
[17751.148051] kmem_cache_free+0x24c/0x270
[17751.152014] kfree_skbmem+0xa0/0xb0
[17751.155543] __kfree_skb+0x28/0x40
[17751.159022] napi_gro_receive+0x168/0x1c0
[17751.163074] hns_nic_rx_up_pro+0x58/0x90
[17751.167041] hns_nic_rx_poll_one+0x518/0xbc0
[17751.171358] hns_nic_common_poll+0x94/0x140
[17751.175585] net_rx_action+0x458/0x5e0
[17751.179373] __do_softirq+0x1b8/0x480
[17751.183076] run_ksoftirqd+0x64/0x80
[17751.186691] smpboot_thread_fn+0x224/0x310
[17751.190826] kthread+0x150/0x170
[17751.194093] ret_from_fork+0x10/0x40
Fixes: 13ac695e7ea1 ("net:hns: Add support of Hip06 SoC to the Hislicon Network Subsystem")
Signed-off-by: Yunsheng Lin <[email protected]>
Signed-off-by: lipeng <[email protected]>
Reported-by: Jun He <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int journal_unmap_buffer(journal_t *journal, struct buffer_head *bh)
{
transaction_t *transaction;
struct journal_head *jh;
int may_free = 1;
int ret;
BUFFER_TRACE(bh, "entry");
/*
* It is safe to proceed here without the j_list_lock because the
* buffers cannot be stolen by try_to_free_buffers as long as we are
* holding the page lock. --sct
*/
if (!buffer_jbd(bh))
goto zap_buffer_unlocked;
/* OK, we have data buffer in journaled mode */
write_lock(&journal->j_state_lock);
jbd_lock_bh_state(bh);
spin_lock(&journal->j_list_lock);
jh = jbd2_journal_grab_journal_head(bh);
if (!jh)
goto zap_buffer_no_jh;
/*
* We cannot remove the buffer from checkpoint lists until the
* transaction adding inode to orphan list (let's call it T)
* is committed. Otherwise if the transaction changing the
* buffer would be cleaned from the journal before T is
* committed, a crash will cause that the correct contents of
* the buffer will be lost. On the other hand we have to
* clear the buffer dirty bit at latest at the moment when the
* transaction marking the buffer as freed in the filesystem
* structures is committed because from that moment on the
* buffer can be reallocated and used by a different page.
* Since the block hasn't been freed yet but the inode has
* already been added to orphan list, it is safe for us to add
* the buffer to BJ_Forget list of the newest transaction.
*/
transaction = jh->b_transaction;
if (transaction == NULL) {
/* First case: not on any transaction. If it
* has no checkpoint link, then we can zap it:
* it's a writeback-mode buffer so we don't care
* if it hits disk safely. */
if (!jh->b_cp_transaction) {
JBUFFER_TRACE(jh, "not on any transaction: zap");
goto zap_buffer;
}
if (!buffer_dirty(bh)) {
/* bdflush has written it. We can drop it now */
goto zap_buffer;
}
/* OK, it must be in the journal but still not
* written fully to disk: it's metadata or
* journaled data... */
if (journal->j_running_transaction) {
/* ... and once the current transaction has
* committed, the buffer won't be needed any
* longer. */
JBUFFER_TRACE(jh, "checkpointed: add to BJ_Forget");
ret = __dispose_buffer(jh,
journal->j_running_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* There is no currently-running transaction. So the
* orphan record which we wrote for this file must have
* passed into commit. We must attach this buffer to
* the committing transaction, if it exists. */
if (journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "give to committing trans");
ret = __dispose_buffer(jh,
journal->j_committing_transaction);
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return ret;
} else {
/* The orphan record's transaction has
* committed. We can cleanse this buffer */
clear_buffer_jbddirty(bh);
goto zap_buffer;
}
}
} else if (transaction == journal->j_committing_transaction) {
JBUFFER_TRACE(jh, "on committing transaction");
/*
* The buffer is committing, we simply cannot touch
* it. So we just set j_next_transaction to the
* running transaction (if there is one) and mark
* buffer as freed so that commit code knows it should
* clear dirty bits when it is done with the buffer.
*/
set_buffer_freed(bh);
if (journal->j_running_transaction && buffer_jbddirty(bh))
jh->b_next_transaction = journal->j_running_transaction;
jbd2_journal_put_journal_head(jh);
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
return 0;
} else {
/* Good, the buffer belongs to the running transaction.
* We are writing our own transaction's data, not any
* previous one's, so it is safe to throw it away
* (remember that we expect the filesystem to have set
* i_size already for this truncate so recovery will not
* expose the disk blocks we are discarding here.) */
J_ASSERT_JH(jh, transaction == journal->j_running_transaction);
JBUFFER_TRACE(jh, "on running transaction");
may_free = __dispose_buffer(jh, transaction);
}
zap_buffer:
jbd2_journal_put_journal_head(jh);
zap_buffer_no_jh:
spin_unlock(&journal->j_list_lock);
jbd_unlock_bh_state(bh);
write_unlock(&journal->j_state_lock);
zap_buffer_unlocked:
clear_buffer_dirty(bh);
J_ASSERT_BH(bh, !buffer_jbddirty(bh));
clear_buffer_mapped(bh);
clear_buffer_req(bh);
clear_buffer_new(bh);
bh->b_bdev = NULL;
return may_free;
}
Commit Message: jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer
journal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head
state ala discard_buffer(), but does not touch _Delay or _Unwritten as
discard_buffer() does.
This can be problematic in some areas of the ext4 code which assume
that if they have found a buffer marked unwritten or delay, then it's
a live one. Perhaps those spots should check whether it is mapped
as well, but if jbd2 is going to tear down a buffer, let's really
tear it down completely.
Without this I get some fsx failures on sub-page-block filesystems
up until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb
and 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go
away, because buried within that large change is some more flag
clearing. I still think it's worth doing in jbd2, since
->invalidatepage leads here directly, and it's the right place
to clear away these flags.
Signed-off-by: Eric Sandeen <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-119
Target: 1
Example 2:
Code: PHP_FUNCTION(radius_put_vendor_string)
{
char *str;
int str_len;
long type, vendor;
radius_descriptor *raddesc;
zval *z_radh;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlls", &z_radh, &vendor, &type, &str, &str_len)
== FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(raddesc, radius_descriptor *, &z_radh, -1, "rad_handle", le_radius);
if (rad_put_vendor_string(raddesc->radh, vendor, type, str) == -1) {
RETURN_FALSE;
} else {
RETURN_TRUE;
}
}
Commit Message: Fix a security issue in radius_get_vendor_attr().
The underlying rad_get_vendor_attr() function assumed that it would always be
given valid VSA data. Indeed, the buffer length wasn't even passed in; the
assumption was that the length field within the VSA structure would be valid.
This could result in denial of service by providing a length that would be
beyond the memory limit, or potential arbitrary memory access by providing a
length greater than the actual data given.
rad_get_vendor_attr() has been changed to require the raw data length be
provided, and this is then used to check that the VSA is valid.
Conflicts:
radlib_vs.h
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int timer_start(Unit *u) {
Timer *t = TIMER(u);
TimerValue *v;
assert(t);
assert(t->state == TIMER_DEAD || t->state == TIMER_FAILED);
if (UNIT_TRIGGER(u)->load_state != UNIT_LOADED)
return -ENOENT;
t->last_trigger = DUAL_TIMESTAMP_NULL;
/* Reenable all timers that depend on unit activation time */
LIST_FOREACH(value, v, t->values)
if (v->base == TIMER_ACTIVE)
v->disabled = false;
if (t->stamp_path) {
struct stat st;
if (stat(t->stamp_path, &st) >= 0)
t->last_trigger.realtime = timespec_load(&st.st_atim);
else if (errno == ENOENT)
/* The timer has never run before,
* make sure a stamp file exists.
*/
touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
}
t->result = TIMER_SUCCESS;
timer_enter_waiting(t, true);
return 1;
}
Commit Message: util-lib: use MODE_INVALID as invalid value for mode_t everywhere
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) {
ddjvu_format_t
*format;
ddjvu_page_type_t
type;
Image
*image;
int
ret,
stride;
unsigned char
*q;
ddjvu_rect_t rect;
rect.x = x;
rect.y = y;
rect.w = (unsigned int) w; /* /10 */
rect.h = (unsigned int) h; /* /10 */
image = lc->image;
type = ddjvu_page_get_type(lc->page);
/* stride of this temporary buffer: */
stride = (type == DDJVU_PAGETYPE_BITONAL)?
(image->columns + 7)/8 : image->columns *3;
q = (unsigned char *) AcquireQuantumMemory(image->rows,stride);
if (q == (unsigned char *) NULL)
return;
format = ddjvu_format_create(
(type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24,
/* DDJVU_FORMAT_RGB24
* DDJVU_FORMAT_RGBMASK32*/
/* DDJVU_FORMAT_RGBMASK32 */
0, NULL);
#if 0
/* fixme: ThrowReaderException is a macro, which uses `exception' variable */
if (format == NULL)
{
abort();
/* ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); */
}
#endif
ddjvu_format_set_row_order(format, 1);
ddjvu_format_set_y_direction(format, 1);
ret = ddjvu_page_render(page,
DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */
&rect,
&rect, /* mmc: ?? */
format,
stride, /* ?? */
(char*)q);
(void) ret;
ddjvu_format_release(format);
if (type == DDJVU_PAGETYPE_BITONAL) {
/* */
#if DEBUG
printf("%s: expanding BITONAL page/image\n", __FUNCTION__);
#endif
register IndexPacket *indexes;
size_t bit, byte;
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception);
if (o == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
bit=0;
byte=0;
/* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/
for (x= 0; x < (ssize_t) image->columns; x++)
{
if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)];
if (indexes != (IndexPacket *) NULL)
SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01));
bit++;
if (bit == 8)
bit=0;
byte>>=1;
}
if (SyncAuthenticPixels(image,&image->exception) == MagickFalse)
break;
}
if (!image->ping)
SyncImage(image);
} else {
#if DEBUG
printf("%s: expanding PHOTO page/image\n", __FUNCTION__);
#endif
/* now transfer line-wise: */
ssize_t i;
#if 0
/* old: */
char* r;
#else
register PixelPacket *r;
unsigned char *s;
#endif
s=q;
for (i = 0;i< (ssize_t) image->rows; i++)
{
#if DEBUG
if (i % 1000 == 0) printf("%d\n",i);
#endif
r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception);
if (r == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(r,ScaleCharToQuantum(*s++));
SetPixelGreen(r,ScaleCharToQuantum(*s++));
SetPixelBlue(r,ScaleCharToQuantum(*s++));
r++;
}
(void) SyncAuthenticPixels(image,&image->exception);
}
}
q=(unsigned char *) RelinquishMagickMemory(q);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static bool netlink_tx_is_mmaped(struct sock *sk)
{
return nlk_sk(sk)->tx_ring.pg_vec != NULL;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static blink::WebScreenOrientations stringToOrientations(const AtomicString& orientationString)
{
DEFINE_STATIC_LOCAL(const AtomicString, portrait, ("portrait", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(const AtomicString, landscape, ("landscape", AtomicString::ConstructFromLiteral));
if (orientationString == portrait)
return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary;
if (orientationString == landscape)
return blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary;
unsigned length = 0;
ScreenOrientationInfo* orientationMap = orientationsMap(length);
for (unsigned i = 0; i < length; ++i) {
if (orientationMap[i].name == orientationString)
return orientationMap[i].orientation;
}
return 0;
}
Commit Message: Screen Orientation: use OrientationLockType enum for lockOrientation().
BUG=162827
Review URL: https://codereview.chromium.org/204653002
git-svn-id: svn://svn.chromium.org/blink/trunk@169972 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data)
{
/* This suppresses [Last] button: assistant thinks that
* we never have this page ready unless we are on it
* -> therefore there is at least one non-ready page
* -> therefore it won't show [Last]
*/
/* If processing is finished and if it was terminated because of an error
* the event progress page is selected. So, it does not make sense to show
* the next step button and we MUST NOT clear warnings.
*/
if (!is_processing_finished())
{
/* some pages hide it, so restore it to it's default */
show_next_step_button();
clear_warnings();
}
gtk_widget_hide(g_btn_detail);
gtk_widget_hide(g_btn_onfail);
if (!g_expert_mode)
gtk_widget_hide(g_btn_repeat);
/* Save text fields if changed */
/* Must be called before any GUI operation because the following two
* functions causes recreating of the text items tabs, thus all updates to
* these tabs will be lost */
save_items_from_notepad();
save_text_from_text_view(g_tv_comment, FILENAME_COMMENT);
if (pages[PAGENO_SUMMARY].page_widget == page)
{
if (!g_expert_mode)
{
/* Skip intro screen */
int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL);
log_info("switching to page_no:%d", n);
gtk_notebook_set_current_page(assistant, n);
return;
}
}
if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page)
{
if (highlight_forbidden())
{
add_sensitive_data_warning();
show_warnings();
gtk_expander_set_expanded(g_exp_search, TRUE);
}
else
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE);
show_warnings();
}
if (pages[PAGENO_REVIEW_DATA].page_widget == page)
{
update_ls_details_checkboxes(g_event_selected);
gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt));
}
if (pages[PAGENO_EDIT_COMMENT].page_widget == page)
{
gtk_widget_show(g_btn_detail);
gtk_widget_set_sensitive(g_btn_next, false);
on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL);
}
if (pages[PAGENO_EVENT_PROGRESS].page_widget == page)
{
log_info("g_event_selected:'%s'", g_event_selected);
if (g_event_selected
&& g_event_selected[0]
) {
clear_warnings();
start_event_run(g_event_selected);
}
}
if(pages[PAGENO_EVENT_SELECTOR].page_widget == page)
{
if (!g_expert_mode && !g_auto_event_list)
hide_next_step_button();
}
}
Commit Message: wizard: fix save users changes after reviewing dump dir files
If the user reviewed the dump dir's files during reporting the crash, the
changes was thrown away and original data was passed to the bugzilla bug
report.
report-gtk saves the first text view buffer and then reloads data from the
reported problem directory, which causes that the changes made to those text
views are thrown away.
Function save_text_if_changed(), except of saving text, also reload the files
from dump dir and update gui state from the dump dir. The commit moves the
reloading and updating gui functions away from this function.
Related to rhbz#1270235
Signed-off-by: Matej Habrnal <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: void WebContentsAndroid::OnTransitionElementsFetched(
scoped_ptr<const TransitionLayerData> transition_data,
bool has_transition_data) {
DCHECK(has_transition_data);
JNIEnv* env = AttachCurrentThread();
std::vector<TransitionElement>::const_iterator it =
transition_data->elements.begin();
for (; it != transition_data->elements.end(); ++it) {
ScopedJavaLocalRef<jstring> jstring_name(ConvertUTF8ToJavaString(env,
it->id));
Java_WebContentsImpl_addNavigationTransitionElements(
env, obj_.obj(), jstring_name.obj(),
it->rect.x(), it->rect.y(), it->rect.width(), it->rect.height());
}
ScopedJavaLocalRef<jstring> jstring_css_selector(
ConvertUTF8ToJavaString(env, transition_data->css_selector));
Java_WebContentsImpl_onTransitionElementsFetched(
env, obj_.obj(), jstring_css_selector.obj());
}
Commit Message: Revert "Load web contents after tab is created."
This reverts commit 4c55f398def3214369aefa9f2f2e8f5940d3799d.
BUG=432562
[email protected],[email protected],[email protected]
Review URL: https://codereview.chromium.org/894003005
Cr-Commit-Position: refs/heads/master@{#314469}
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IHEVCD_ERROR_T ihevcd_parse_mastering_disp_params_sei(codec_t *ps_codec)
{
parse_ctxt_t *ps_parse = &ps_codec->s_parse;
bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm;
UWORD32 value;
mastering_dis_col_vol_sei_params_t *ps_mastering_dis_col_vol;
WORD32 i;
ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1;
ps_mastering_dis_col_vol = &ps_parse->s_sei_params.s_mastering_dis_col_vol_sei_params;
for(i = 0; i < 3; i++)
{
BITS_PARSE("display_primaries_x[c]", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->au2_display_primaries_x[i] = value;
BITS_PARSE("display_primaries_y[c]", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->au2_display_primaries_y[i] = value;
}
BITS_PARSE("white_point_x", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->u2_white_point_x = value;
BITS_PARSE("white_point_y", value, ps_bitstrm, 16);
ps_mastering_dis_col_vol->u2_white_point_y = value;
BITS_PARSE("max_display_mastering_luminance", value, ps_bitstrm, 32);
ps_mastering_dis_col_vol->u4_max_display_mastering_luminance = value;
BITS_PARSE("min_display_mastering_luminance", value, ps_bitstrm, 32);
ps_mastering_dis_col_vol->u4_min_display_mastering_luminance = value;
return (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
}
Commit Message: Ensure CTB size > 16 for clips with tiles and width/height >= 4096
For clips with tiles and dimensions >= 4096,
CTB size of 16 can result in tile position > 255.
This is not supported by the decoder
Bug: 37930177
Test: ran poc w/o crashing
Change-Id: I2f223a124c4ea9bfd98343343fd010d80a5dd8bd
(cherry picked from commit 248e72c7a8c7c382ff4397868a6c7453a6453141)
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int tls1_cbc_remove_padding(const SSL* s,
SSL3_RECORD *rec,
unsigned block_size,
unsigned mac_size)
{
unsigned padding_length, good, to_check, i;
const char has_explicit_iv =
s->version >= TLS1_1_VERSION || s->version == DTLS1_VERSION;
const unsigned overhead = 1 /* padding length byte */ +
mac_size +
(has_explicit_iv ? block_size : 0);
/* These lengths are all public so we can test them in non-constant
* time. */
if (overhead > rec->length)
return 0;
padding_length = rec->data[rec->length-1];
/* NB: if compression is in operation the first packet may not be of
padding_length--;
}
Commit Message:
CWE ID: CWE-310
Target: 1
Example 2:
Code: bool ACodec::IdleToLoadedState::onOMXEvent(
OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
switch (event) {
case OMX_EventCmdComplete:
{
if (data1 != (OMX_U32)OMX_CommandStateSet
|| data2 != (OMX_U32)OMX_StateLoaded) {
ALOGE("Unexpected command completion in IdleToLoadedState: %s(%u) %s(%u)",
asString((OMX_COMMANDTYPE)data1), data1,
asString((OMX_STATETYPE)data2), data2);
mCodec->signalError(OMX_ErrorUndefined, FAILED_TRANSACTION);
return true;
}
mCodec->changeState(mCodec->mLoadedState);
return true;
}
default:
return BaseState::onOMXEvent(event, data1, data2);
}
}
Commit Message: Fix initialization of AAC presentation struct
Otherwise the new size checks trip on this.
Bug: 27207275
Change-Id: I1f8f01097e3a88ff041b69279a6121be842f1766
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool init_features(ASS_Shaper *shaper)
{
shaper->features = calloc(sizeof(hb_feature_t), NUM_FEATURES);
if (!shaper->features)
return false;
shaper->n_features = NUM_FEATURES;
shaper->features[VERT].tag = HB_TAG('v', 'e', 'r', 't');
shaper->features[VERT].end = UINT_MAX;
shaper->features[VKNA].tag = HB_TAG('v', 'k', 'n', 'a');
shaper->features[VKNA].end = UINT_MAX;
shaper->features[KERN].tag = HB_TAG('k', 'e', 'r', 'n');
shaper->features[KERN].end = UINT_MAX;
shaper->features[LIGA].tag = HB_TAG('l', 'i', 'g', 'a');
shaper->features[LIGA].end = UINT_MAX;
shaper->features[CLIG].tag = HB_TAG('c', 'l', 'i', 'g');
shaper->features[CLIG].end = UINT_MAX;
return true;
}
Commit Message: shaper: fix reallocation
Update the variable that tracks the allocated size. This potentially
improves performance and avoid some side effects, which lead to
undefined behavior in some cases.
Fixes fuzzer test case id:000051,sig:11,sync:fuzzer3,src:004221.
CWE ID: CWE-399
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: setkey_principal3_2_svc(setkey3_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_3((void *)handle, arg->princ,
arg->keepold,
arg->n_ks_tuple,
arg->ks_tuple,
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
Target: 1
Example 2:
Code: void iods_del(GF_Box *s)
{
GF_ObjectDescriptorBox *ptr = (GF_ObjectDescriptorBox *)s;
if (ptr == NULL) return;
if (ptr->descriptor) gf_odf_desc_del(ptr->descriptor);
gf_free(ptr);
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static PassRefPtrWillBeRawPtr<CreateFileResult> create()
{
return adoptRefWillBeNoop(new CreateFileResult());
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: vrrp_print_json(void)
{
FILE *file;
element e;
struct json_object *array;
if (LIST_ISEMPTY(vrrp_data->vrrp))
return;
file = fopen ("/tmp/keepalived.json","w");
if (!file) {
log_message(LOG_INFO, "Can't open /tmp/keepalived.json (%d: %s)",
errno, strerror(errno));
return;
}
array = json_object_new_array();
for (e = LIST_HEAD(vrrp_data->vrrp); e; ELEMENT_NEXT(e)) {
struct json_object *instance_json, *json_stats, *json_data,
*vips, *evips, *track_ifp, *track_script;
#ifdef _HAVE_FIB_ROUTING_
struct json_object *vroutes, *vrules;
#endif
element f;
vrrp_t *vrrp = ELEMENT_DATA(e);
instance_json = json_object_new_object();
json_stats = json_object_new_object();
json_data = json_object_new_object();
vips = json_object_new_array();
evips = json_object_new_array();
track_ifp = json_object_new_array();
track_script = json_object_new_array();
#ifdef _HAVE_FIB_ROUTING_
vroutes = json_object_new_array();
vrules = json_object_new_array();
#endif
json_object_object_add(json_data, "iname",
json_object_new_string(vrrp->iname));
json_object_object_add(json_data, "dont_track_primary",
json_object_new_int(vrrp->dont_track_primary));
json_object_object_add(json_data, "skip_check_adv_addr",
json_object_new_int(vrrp->skip_check_adv_addr));
json_object_object_add(json_data, "strict_mode",
json_object_new_int((int)vrrp->strict_mode));
#ifdef _HAVE_VRRP_VMAC_
json_object_object_add(json_data, "vmac_ifname",
json_object_new_string(vrrp->vmac_ifname));
#endif
if (!LIST_ISEMPTY(vrrp->track_ifp)) {
for (f = LIST_HEAD(vrrp->track_ifp); f; ELEMENT_NEXT(f)) {
interface_t *ifp = ELEMENT_DATA(f);
json_object_array_add(track_ifp,
json_object_new_string(ifp->ifname));
}
}
json_object_object_add(json_data, "track_ifp", track_ifp);
if (!LIST_ISEMPTY(vrrp->track_script)) {
for (f = LIST_HEAD(vrrp->track_script); f; ELEMENT_NEXT(f)) {
tracked_sc_t *tsc = ELEMENT_DATA(f);
vrrp_script_t *vscript = tsc->scr;
json_object_array_add(track_script,
json_object_new_string(cmd_str(&vscript->script)));
}
}
json_object_object_add(json_data, "track_script", track_script);
json_object_object_add(json_data, "ifp_ifname",
json_object_new_string(vrrp->ifp->ifname));
json_object_object_add(json_data, "master_priority",
json_object_new_int(vrrp->master_priority));
json_object_object_add(json_data, "last_transition",
json_object_new_double(timeval_to_double(&vrrp->last_transition)));
json_object_object_add(json_data, "garp_delay",
json_object_new_double(vrrp->garp_delay / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "garp_refresh",
json_object_new_int((int)vrrp->garp_refresh.tv_sec));
json_object_object_add(json_data, "garp_rep",
json_object_new_int((int)vrrp->garp_rep));
json_object_object_add(json_data, "garp_refresh_rep",
json_object_new_int((int)vrrp->garp_refresh_rep));
json_object_object_add(json_data, "garp_lower_prio_delay",
json_object_new_int((int)(vrrp->garp_lower_prio_delay / TIMER_HZ)));
json_object_object_add(json_data, "garp_lower_prio_rep",
json_object_new_int((int)vrrp->garp_lower_prio_rep));
json_object_object_add(json_data, "lower_prio_no_advert",
json_object_new_int((int)vrrp->lower_prio_no_advert));
json_object_object_add(json_data, "higher_prio_send_advert",
json_object_new_int((int)vrrp->higher_prio_send_advert));
json_object_object_add(json_data, "vrid",
json_object_new_int(vrrp->vrid));
json_object_object_add(json_data, "base_priority",
json_object_new_int(vrrp->base_priority));
json_object_object_add(json_data, "effective_priority",
json_object_new_int(vrrp->effective_priority));
json_object_object_add(json_data, "vipset",
json_object_new_boolean(vrrp->vipset));
if (!LIST_ISEMPTY(vrrp->vip)) {
for (f = LIST_HEAD(vrrp->vip); f; ELEMENT_NEXT(f)) {
ip_address_t *vip = ELEMENT_DATA(f);
char ipaddr[INET6_ADDRSTRLEN];
inet_ntop(vrrp->family, &(vip->u.sin.sin_addr.s_addr),
ipaddr, INET6_ADDRSTRLEN);
json_object_array_add(vips,
json_object_new_string(ipaddr));
}
}
json_object_object_add(json_data, "vips", vips);
if (!LIST_ISEMPTY(vrrp->evip)) {
for (f = LIST_HEAD(vrrp->evip); f; ELEMENT_NEXT(f)) {
ip_address_t *evip = ELEMENT_DATA(f);
char ipaddr[INET6_ADDRSTRLEN];
inet_ntop(vrrp->family, &(evip->u.sin.sin_addr.s_addr),
ipaddr, INET6_ADDRSTRLEN);
json_object_array_add(evips,
json_object_new_string(ipaddr));
}
}
json_object_object_add(json_data, "evips", evips);
json_object_object_add(json_data, "promote_secondaries",
json_object_new_boolean(vrrp->promote_secondaries));
#ifdef _HAVE_FIB_ROUTING_
if (!LIST_ISEMPTY(vrrp->vroutes)) {
for (f = LIST_HEAD(vrrp->vroutes); f; ELEMENT_NEXT(f)) {
ip_route_t *route = ELEMENT_DATA(f);
char *buf = MALLOC(ROUTE_BUF_SIZE);
format_iproute(route, buf, ROUTE_BUF_SIZE);
json_object_array_add(vroutes,
json_object_new_string(buf));
}
}
json_object_object_add(json_data, "vroutes", vroutes);
if (!LIST_ISEMPTY(vrrp->vrules)) {
for (f = LIST_HEAD(vrrp->vrules); f; ELEMENT_NEXT(f)) {
ip_rule_t *rule = ELEMENT_DATA(f);
char *buf = MALLOC(RULE_BUF_SIZE);
format_iprule(rule, buf, RULE_BUF_SIZE);
json_object_array_add(vrules,
json_object_new_string(buf));
}
}
json_object_object_add(json_data, "vrules", vrules);
#endif
json_object_object_add(json_data, "adver_int",
json_object_new_double(vrrp->adver_int / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "master_adver_int",
json_object_new_double(vrrp->master_adver_int / TIMER_HZ_FLOAT));
json_object_object_add(json_data, "accept",
json_object_new_int((int)vrrp->accept));
json_object_object_add(json_data, "nopreempt",
json_object_new_boolean(vrrp->nopreempt));
json_object_object_add(json_data, "preempt_delay",
json_object_new_int((int)(vrrp->preempt_delay / TIMER_HZ)));
json_object_object_add(json_data, "state",
json_object_new_int(vrrp->state));
json_object_object_add(json_data, "wantstate",
json_object_new_int(vrrp->wantstate));
json_object_object_add(json_data, "version",
json_object_new_int(vrrp->version));
if (vrrp->script_backup)
json_object_object_add(json_data, "script_backup",
json_object_new_string(cmd_str(vrrp->script_backup)));
if (vrrp->script_master)
json_object_object_add(json_data, "script_master",
json_object_new_string(cmd_str(vrrp->script_master)));
if (vrrp->script_fault)
json_object_object_add(json_data, "script_fault",
json_object_new_string(cmd_str(vrrp->script_fault)));
if (vrrp->script_stop)
json_object_object_add(json_data, "script_stop",
json_object_new_string(cmd_str(vrrp->script_stop)));
if (vrrp->script)
json_object_object_add(json_data, "script",
json_object_new_string(cmd_str(vrrp->script)));
if (vrrp->script_master_rx_lower_pri)
json_object_object_add(json_data, "script_master_rx_lower_pri",
json_object_new_string(cmd_str(vrrp->script_master_rx_lower_pri)));
json_object_object_add(json_data, "smtp_alert",
json_object_new_boolean(vrrp->smtp_alert));
#ifdef _WITH_VRRP_AUTH_
if (vrrp->auth_type) {
json_object_object_add(json_data, "auth_type",
json_object_new_int(vrrp->auth_type));
if (vrrp->auth_type != VRRP_AUTH_AH) {
char auth_data[sizeof(vrrp->auth_data) + 1];
memcpy(auth_data, vrrp->auth_data, sizeof(vrrp->auth_data));
auth_data[sizeof(vrrp->auth_data)] = '\0';
json_object_object_add(json_data, "auth_data",
json_object_new_string(auth_data));
}
}
else
json_object_object_add(json_data, "auth_type",
json_object_new_int(0));
#endif
json_object_object_add(json_stats, "advert_rcvd",
json_object_new_int64((int64_t)vrrp->stats->advert_rcvd));
json_object_object_add(json_stats, "advert_sent",
json_object_new_int64(vrrp->stats->advert_sent));
json_object_object_add(json_stats, "become_master",
json_object_new_int64(vrrp->stats->become_master));
json_object_object_add(json_stats, "release_master",
json_object_new_int64(vrrp->stats->release_master));
json_object_object_add(json_stats, "packet_len_err",
json_object_new_int64((int64_t)vrrp->stats->packet_len_err));
json_object_object_add(json_stats, "advert_interval_err",
json_object_new_int64((int64_t)vrrp->stats->advert_interval_err));
json_object_object_add(json_stats, "ip_ttl_err",
json_object_new_int64((int64_t)vrrp->stats->ip_ttl_err));
json_object_object_add(json_stats, "invalid_type_rcvd",
json_object_new_int64((int64_t)vrrp->stats->invalid_type_rcvd));
json_object_object_add(json_stats, "addr_list_err",
json_object_new_int64((int64_t)vrrp->stats->addr_list_err));
json_object_object_add(json_stats, "invalid_authtype",
json_object_new_int64(vrrp->stats->invalid_authtype));
#ifdef _WITH_VRRP_AUTH_
json_object_object_add(json_stats, "authtype_mismatch",
json_object_new_int64(vrrp->stats->authtype_mismatch));
json_object_object_add(json_stats, "auth_failure",
json_object_new_int64(vrrp->stats->auth_failure));
#endif
json_object_object_add(json_stats, "pri_zero_rcvd",
json_object_new_int64((int64_t)vrrp->stats->pri_zero_rcvd));
json_object_object_add(json_stats, "pri_zero_sent",
json_object_new_int64((int64_t)vrrp->stats->pri_zero_sent));
json_object_object_add(instance_json, "data", json_data);
json_object_object_add(instance_json, "stats", json_stats);
json_object_array_add(array, instance_json);
}
fprintf(file, "%s", json_object_to_json_string(array));
fclose(file);
}
Commit Message: When opening files for write, ensure they aren't symbolic links
Issue #1048 identified that if, for example, a non privileged user
created a symbolic link from /etc/keepalvied.data to /etc/passwd,
writing to /etc/keepalived.data (which could be invoked via DBus)
would cause /etc/passwd to be overwritten.
This commit stops keepalived writing to pathnames where the ultimate
component is a symbolic link, by setting O_NOFOLLOW whenever opening
a file for writing.
This might break some setups, where, for example, /etc/keepalived.data
was a symbolic link to /home/fred/keepalived.data. If this was the case,
instead create a symbolic link from /home/fred/keepalived.data to
/tmp/keepalived.data, so that the file is still accessible via
/home/fred/keepalived.data.
There doesn't appear to be a way around this backward incompatibility,
since even checking if the pathname is a symbolic link prior to opening
for writing would create a race condition.
Signed-off-by: Quentin Armitage <[email protected]>
CWE ID: CWE-59
Target: 1
Example 2:
Code: static void red_channel_client_pipe_remove(RedChannelClient *rcc, PipeItem *item)
{
rcc->pipe_size--;
ring_remove(&item->link);
}
Commit Message:
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static char *TraceSVGClippath(const unsigned char *blob,size_t length,
const size_t columns,const size_t rows)
{
char
*path,
*message;
MagickBooleanType
in_subpath;
PointInfo
first[3],
last[3],
point[3];
register ssize_t
i;
ssize_t
knot_count,
selector,
x,
y;
path=AcquireString((char *) NULL);
if (path == (char *) NULL)
return((char *) NULL);
message=AcquireString((char *) NULL);
(void) FormatLocaleString(message,MagickPathExtent,(
"<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"
"<svg xmlns=\"http://www.w3.org/2000/svg\""
" width=\"%.20g\" height=\"%.20g\">\n"
"<g>\n"
"<path fill-rule=\"evenodd\" style=\"fill:#00000000;stroke:#00000000;"
"stroke-width:0;stroke-antialiasing:false\" d=\"\n"),(double) columns,
(double) rows);
(void) ConcatenateString(&path,message);
(void) ResetMagickMemory(point,0,sizeof(point));
(void) ResetMagickMemory(first,0,sizeof(first));
(void) ResetMagickMemory(last,0,sizeof(last));
knot_count=0;
in_subpath=MagickFalse;
while (length != 0)
{
selector=(ssize_t) ReadPropertyMSBShort(&blob,&length);
switch (selector)
{
case 0:
case 3:
{
if (knot_count != 0)
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Expected subpath length record.
*/
knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length);
blob+=22;
length-=MagickMin(22,(ssize_t) length);
break;
}
case 1:
case 2:
case 4:
case 5:
{
if (knot_count == 0)
{
/*
Unexpected subpath knot.
*/
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
/*
Add sub-path knot
*/
for (i=0; i < 3; i++)
{
unsigned int
xx,
yy;
yy=(unsigned int) ReadPropertyMSBLong(&blob,&length);
xx=(unsigned int) ReadPropertyMSBLong(&blob,&length);
x=(ssize_t) xx;
if (xx > 2147483647)
x=(ssize_t) xx-4294967295U-1;
y=(ssize_t) yy;
if (yy > 2147483647)
y=(ssize_t) yy-4294967295U-1;
point[i].x=(double) x*columns/4096/4096;
point[i].y=(double) y*rows/4096/4096;
}
if (in_subpath == MagickFalse)
{
(void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n",
point[1].x,point[1].y);
for (i=0; i < 3; i++)
{
first[i]=point[i];
last[i]=point[i];
}
}
else
{
/*
Handle special cases when Bezier curves are used to describe
corners and straight lines.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(point[0].x == point[1].x) && (point[0].y == point[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g\n",point[1].x,point[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g\n",last[2].x,
last[2].y,point[0].x,point[0].y,point[1].x,point[1].y);
for (i=0; i < 3; i++)
last[i]=point[i];
}
(void) ConcatenateString(&path,message);
in_subpath=MagickTrue;
knot_count--;
/*
Close the subpath if there are no more knots.
*/
if (knot_count == 0)
{
/*
Same special handling as above except we compare to the
first point in the path and close the path.
*/
if ((last[1].x == last[2].x) && (last[1].y == last[2].y) &&
(first[0].x == first[1].x) && (first[0].y == first[1].y))
(void) FormatLocaleString(message,MagickPathExtent,
"L %g %g Z\n",first[1].x,first[1].y);
else
(void) FormatLocaleString(message,MagickPathExtent,
"C %g %g %g %g %g %g Z\n",last[2].x,
last[2].y,first[0].x,first[0].y,first[1].x,first[1].y);
(void) ConcatenateString(&path,message);
in_subpath=MagickFalse;
}
break;
}
case 6:
case 7:
case 8:
default:
{
blob+=24;
length-=MagickMin(24,(ssize_t) length);
break;
}
}
}
/*
Return an empty SVG image if the path does not have knots.
*/
(void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n");
message=DestroyString(message);
return(path);
}
Commit Message: Prevent buffer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void snd_usb_mixer_free(struct usb_mixer_interface *mixer)
{
kfree(mixer->id_elems);
if (mixer->urb) {
kfree(mixer->urb->transfer_buffer);
usb_free_urb(mixer->urb);
}
usb_free_urb(mixer->rc_urb);
kfree(mixer->rc_setup_packet);
kfree(mixer);
}
Commit Message: ALSA: usb-audio: Kill stray URB at exiting
USB-audio driver may leave a stray URB for the mixer interrupt when it
exits by some error during probe. This leads to a use-after-free
error as spotted by syzkaller like:
==================================================================
BUG: KASAN: use-after-free in snd_usb_mixer_interrupt+0x604/0x6f0
Call Trace:
<IRQ>
__dump_stack lib/dump_stack.c:16
dump_stack+0x292/0x395 lib/dump_stack.c:52
print_address_description+0x78/0x280 mm/kasan/report.c:252
kasan_report_error mm/kasan/report.c:351
kasan_report+0x23d/0x350 mm/kasan/report.c:409
__asan_report_load8_noabort+0x19/0x20 mm/kasan/report.c:430
snd_usb_mixer_interrupt+0x604/0x6f0 sound/usb/mixer.c:2490
__usb_hcd_giveback_urb+0x2e0/0x650 drivers/usb/core/hcd.c:1779
....
Allocated by task 1484:
save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59
save_stack+0x43/0xd0 mm/kasan/kasan.c:447
set_track mm/kasan/kasan.c:459
kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551
kmem_cache_alloc_trace+0x11e/0x2d0 mm/slub.c:2772
kmalloc ./include/linux/slab.h:493
kzalloc ./include/linux/slab.h:666
snd_usb_create_mixer+0x145/0x1010 sound/usb/mixer.c:2540
create_standard_mixer_quirk+0x58/0x80 sound/usb/quirks.c:516
snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560
create_composite_quirk+0x1c4/0x3e0 sound/usb/quirks.c:59
snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560
usb_audio_probe+0x1040/0x2c10 sound/usb/card.c:618
....
Freed by task 1484:
save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59
save_stack+0x43/0xd0 mm/kasan/kasan.c:447
set_track mm/kasan/kasan.c:459
kasan_slab_free+0x72/0xc0 mm/kasan/kasan.c:524
slab_free_hook mm/slub.c:1390
slab_free_freelist_hook mm/slub.c:1412
slab_free mm/slub.c:2988
kfree+0xf6/0x2f0 mm/slub.c:3919
snd_usb_mixer_free+0x11a/0x160 sound/usb/mixer.c:2244
snd_usb_mixer_dev_free+0x36/0x50 sound/usb/mixer.c:2250
__snd_device_free+0x1ff/0x380 sound/core/device.c:91
snd_device_free_all+0x8f/0xe0 sound/core/device.c:244
snd_card_do_free sound/core/init.c:461
release_card_device+0x47/0x170 sound/core/init.c:181
device_release+0x13f/0x210 drivers/base/core.c:814
....
Actually such a URB is killed properly at disconnection when the
device gets probed successfully, and what we need is to apply it for
the error-path, too.
In this patch, we apply snd_usb_mixer_disconnect() at releasing.
Also introduce a new flag, disconnected, to struct usb_mixer_interface
for not performing the disconnection procedure twice.
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: ASN1_INTEGER *ASN1_INTEGER_dup(const ASN1_INTEGER *x)
{
return M_ASN1_INTEGER_dup(x);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: OMX_ERRORTYPE omx_video::free_buffer(OMX_IN OMX_HANDLETYPE hComp,
OMX_IN OMX_U32 port,
OMX_IN OMX_BUFFERHEADERTYPE* buffer)
{
(void)hComp;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
unsigned int nPortIndex;
DEBUG_PRINT_LOW("In for encoder free_buffer");
if (m_state == OMX_StateIdle &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
DEBUG_PRINT_LOW(" free buffer while Component in Loading pending");
} else if ((m_sInPortDef.bEnabled == OMX_FALSE && port == PORT_INDEX_IN)||
(m_sOutPortDef.bEnabled == OMX_FALSE && port == PORT_INDEX_OUT)) {
DEBUG_PRINT_LOW("Free Buffer while port %u disabled", (unsigned int)port);
} else if (m_state == OMX_StateExecuting || m_state == OMX_StatePause) {
DEBUG_PRINT_ERROR("ERROR: Invalid state to free buffer,ports need to be disabled");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
return eRet;
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid state to free buffer,port lost Buffers");
post_event(OMX_EventError,
OMX_ErrorPortUnpopulated,
OMX_COMPONENT_GENERATE_EVENT);
}
if (port == PORT_INDEX_IN) {
nPortIndex = buffer - ((!meta_mode_enable)?m_inp_mem_ptr:meta_buffer_hdr);
DEBUG_PRINT_LOW("free_buffer on i/p port - Port idx %u, actual cnt %u",
nPortIndex, (unsigned int)m_sInPortDef.nBufferCountActual);
if (nPortIndex < m_sInPortDef.nBufferCountActual) {
BITMASK_CLEAR(&m_inp_bm_count,nPortIndex);
free_input_buffer (buffer);
m_sInPortDef.bPopulated = OMX_FALSE;
/*Free the Buffer Header*/
if (release_input_done()
#ifdef _ANDROID_ICS_
&& !meta_mode_enable
#endif
) {
input_use_buffer = false;
if (m_inp_mem_ptr) {
DEBUG_PRINT_LOW("Freeing m_inp_mem_ptr");
free (m_inp_mem_ptr);
m_inp_mem_ptr = NULL;
}
if (m_pInput_pmem) {
DEBUG_PRINT_LOW("Freeing m_pInput_pmem");
free(m_pInput_pmem);
m_pInput_pmem = NULL;
}
#ifdef USE_ION
if (m_pInput_ion) {
DEBUG_PRINT_LOW("Freeing m_pInput_ion");
free(m_pInput_ion);
m_pInput_ion = NULL;
}
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: free_buffer ,Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING)
&& release_input_done()) {
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_INPUT_DISABLE_PENDING);
post_event(OMX_CommandPortDisable,
PORT_INDEX_IN,
OMX_COMPONENT_GENERATE_EVENT);
}
} else if (port == PORT_INDEX_OUT) {
nPortIndex = buffer - (OMX_BUFFERHEADERTYPE*)m_out_mem_ptr;
DEBUG_PRINT_LOW("free_buffer on o/p port - Port idx %u, actual cnt %u",
nPortIndex, (unsigned int)m_sOutPortDef.nBufferCountActual);
if (nPortIndex < m_sOutPortDef.nBufferCountActual) {
BITMASK_CLEAR(&m_out_bm_count,nPortIndex);
m_sOutPortDef.bPopulated = OMX_FALSE;
free_output_buffer (buffer);
if (release_output_done()) {
output_use_buffer = false;
if (m_out_mem_ptr) {
DEBUG_PRINT_LOW("Freeing m_out_mem_ptr");
free (m_out_mem_ptr);
m_out_mem_ptr = NULL;
}
if (m_pOutput_pmem) {
DEBUG_PRINT_LOW("Freeing m_pOutput_pmem");
free(m_pOutput_pmem);
m_pOutput_pmem = NULL;
}
#ifdef USE_ION
if (m_pOutput_ion) {
DEBUG_PRINT_LOW("Freeing m_pOutput_ion");
free(m_pOutput_ion);
m_pOutput_ion = NULL;
}
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: free_buffer , Port Index Invalid");
eRet = OMX_ErrorBadPortIndex;
}
if (BITMASK_PRESENT((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING)
&& release_output_done() ) {
DEBUG_PRINT_LOW("FreeBuffer : If any Disable event pending,post it");
DEBUG_PRINT_LOW("MOVING TO DISABLED STATE");
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_OUTPUT_DISABLE_PENDING);
post_event(OMX_CommandPortDisable,
PORT_INDEX_OUT,
OMX_COMPONENT_GENERATE_EVENT);
}
} else {
eRet = OMX_ErrorBadPortIndex;
}
if ((eRet == OMX_ErrorNone) &&
(BITMASK_PRESENT(&m_flags ,OMX_COMPONENT_LOADING_PENDING))) {
if (release_done()) {
if (dev_stop() != 0) {
DEBUG_PRINT_ERROR("ERROR: dev_stop() FAILED");
eRet = OMX_ErrorHardware;
}
BITMASK_CLEAR((&m_flags),OMX_COMPONENT_LOADING_PENDING);
post_event(OMX_CommandStateSet, OMX_StateLoaded,
OMX_COMPONENT_GENERATE_EVENT);
} else {
DEBUG_PRINT_HIGH("in free buffer, release not done, need to free more buffers input %" PRIx64" output %" PRIx64,
m_out_bm_count, m_inp_bm_count);
}
}
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Add safety checks to free only as many buffers were allocated.
Fixes: Heap Overflow and Possible Local Privilege Escalation in
MediaServer (libOmxVenc problem)
Bug: 27532497
Change-Id: I31e576ef9dc542df73aa6b0ea113d72724b50fc6
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void _moddeinit(module_unload_intent_t intent)
{
service_named_unbind_command("chanserv", &cs_flags);
}
Commit Message: chanserv/flags: make Anope FLAGS compatibility an option
Previously, ChanServ FLAGS behavior could be modified by registering or
dropping the keyword nicks "LIST", "CLEAR", and "MODIFY".
Now, a configuration option is available that when turned on (default),
disables registration of these keyword nicks and enables this
compatibility feature. When turned off, registration of these keyword
nicks is possible, and compatibility to Anope's FLAGS command is
disabled.
Fixes atheme/atheme#397
CWE ID: CWE-284
Target: 1
Example 2:
Code: static inline struct shmid_kernel *shm_obtain_object(struct ipc_namespace *ns, int id)
{
struct kern_ipc_perm *ipcp = ipc_obtain_object(&shm_ids(ns), id);
if (IS_ERR(ipcp))
return ERR_CAST(ipcp);
return container_of(ipcp, struct shmid_kernel, shm_perm);
}
Commit Message: ipc,shm: fix shm_file deletion races
When IPC_RMID races with other shm operations there's potential for
use-after-free of the shm object's associated file (shm_file).
Here's the race before this patch:
TASK 1 TASK 2
------ ------
shm_rmid()
ipc_lock_object()
shmctl()
shp = shm_obtain_object_check()
shm_destroy()
shum_unlock()
fput(shp->shm_file)
ipc_lock_object()
shmem_lock(shp->shm_file)
<OOPS>
The oops is caused because shm_destroy() calls fput() after dropping the
ipc_lock. fput() clears the file's f_inode, f_path.dentry, and
f_path.mnt, which causes various NULL pointer references in task 2. I
reliably see the oops in task 2 if with shmlock, shmu
This patch fixes the races by:
1) set shm_file=NULL in shm_destroy() while holding ipc_object_lock().
2) modify at risk operations to check shm_file while holding
ipc_object_lock().
Example workloads, which each trigger oops...
Workload 1:
while true; do
id=$(shmget 1 4096)
shm_rmid $id &
shmlock $id &
wait
done
The oops stack shows accessing NULL f_inode due to racing fput:
_raw_spin_lock
shmem_lock
SyS_shmctl
Workload 2:
while true; do
id=$(shmget 1 4096)
shmat $id 4096 &
shm_rmid $id &
wait
done
The oops stack is similar to workload 1 due to NULL f_inode:
touch_atime
shmem_mmap
shm_mmap
mmap_region
do_mmap_pgoff
do_shmat
SyS_shmat
Workload 3:
while true; do
id=$(shmget 1 4096)
shmlock $id
shm_rmid $id &
shmunlock $id &
wait
done
The oops stack shows second fput tripping on an NULL f_inode. The
first fput() completed via from shm_destroy(), but a racing thread did
a get_file() and queued this fput():
locks_remove_flock
__fput
____fput
task_work_run
do_notify_resume
int_signal
Fixes: c2c737a0461e ("ipc,shm: shorten critical region for shmat")
Fixes: 2caacaa82a51 ("ipc,shm: shorten critical region for shmctl")
Signed-off-by: Greg Thelen <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: <[email protected]> # 3.10.17+ 3.11.6+
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void V8TestObject::DocumentFragmentAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_documentFragmentAttribute_Getter");
test_object_v8_internal::DocumentFragmentAttributeAttributeGetter(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const Chapters* Segment::GetChapters() const
{
return m_pChapters;
}
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
Target: 1
Example 2:
Code: static bool update_nohz_stats(struct rq *rq, bool force)
{
#ifdef CONFIG_NO_HZ_COMMON
unsigned int cpu = rq->cpu;
if (!rq->has_blocked_load)
return false;
if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
return false;
if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
return true;
update_blocked_averages(cpu);
return rq->has_blocked_load;
#else
return false;
#endif
}
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IHEVCD_ERROR_T ihevcd_parse_pps(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 pps_id;
pps_t *ps_pps;
sps_t *ps_sps;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
if(0 == ps_codec->i4_sps_done)
return IHEVCD_INVALID_HEADER;
UEV_PARSE("pic_parameter_set_id", value, ps_bitstrm);
pps_id = value;
if((pps_id >= MAX_PPS_CNT) || (pps_id < 0))
{
if(ps_codec->i4_pps_done)
return IHEVCD_UNSUPPORTED_PPS_ID;
else
pps_id = 0;
}
ps_pps = (ps_codec->s_parse.ps_pps_base + MAX_PPS_CNT - 1);
ps_pps->i1_pps_id = pps_id;
UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm);
ps_pps->i1_sps_id = value;
ps_pps->i1_sps_id = CLIP3(ps_pps->i1_sps_id, 0, MAX_SPS_CNT - 2);
ps_sps = (ps_codec->s_parse.ps_sps_base + ps_pps->i1_sps_id);
/* If the SPS that is being referred to has not been parsed,
* copy an existing SPS to the current location */
if(0 == ps_sps->i1_sps_valid)
{
return IHEVCD_INVALID_HEADER;
/*
sps_t *ps_sps_ref = ps_codec->ps_sps_base;
while(0 == ps_sps_ref->i1_sps_valid)
ps_sps_ref++;
ihevcd_copy_sps(ps_codec, ps_pps->i1_sps_id, ps_sps_ref->i1_sps_id);
*/
}
BITS_PARSE("dependent_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_dependent_slice_enabled_flag = value;
BITS_PARSE("output_flag_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_output_flag_present_flag = value;
BITS_PARSE("num_extra_slice_header_bits", value, ps_bitstrm, 3);
ps_pps->i1_num_extra_slice_header_bits = value;
BITS_PARSE("sign_data_hiding_flag", value, ps_bitstrm, 1);
ps_pps->i1_sign_data_hiding_flag = value;
BITS_PARSE("cabac_init_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_cabac_init_present_flag = value;
UEV_PARSE("num_ref_idx_l0_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l0_default_active = value + 1;
UEV_PARSE("num_ref_idx_l1_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l1_default_active = value + 1;
SEV_PARSE("pic_init_qp_minus26", value, ps_bitstrm);
ps_pps->i1_pic_init_qp = value + 26;
BITS_PARSE("constrained_intra_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_constrained_intra_pred_flag = value;
BITS_PARSE("transform_skip_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_transform_skip_enabled_flag = value;
BITS_PARSE("cu_qp_delta_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_cu_qp_delta_enabled_flag = value;
if(ps_pps->i1_cu_qp_delta_enabled_flag)
{
UEV_PARSE("diff_cu_qp_delta_depth", value, ps_bitstrm);
ps_pps->i1_diff_cu_qp_delta_depth = value;
}
else
{
ps_pps->i1_diff_cu_qp_delta_depth = 0;
}
ps_pps->i1_log2_min_cu_qp_delta_size = ps_sps->i1_log2_ctb_size - ps_pps->i1_diff_cu_qp_delta_depth;
/* Print different */
SEV_PARSE("cb_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cb_qp_offset = value;
/* Print different */
SEV_PARSE("cr_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cr_qp_offset = value;
/* Print different */
BITS_PARSE("slicelevel_chroma_qp_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag = value;
BITS_PARSE("weighted_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_pred_flag = value;
BITS_PARSE("weighted_bipred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_bipred_flag = value;
BITS_PARSE("transquant_bypass_enable_flag", value, ps_bitstrm, 1);
ps_pps->i1_transquant_bypass_enable_flag = value;
BITS_PARSE("tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_tiles_enabled_flag = value;
BITS_PARSE("entropy_coding_sync_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_entropy_coding_sync_enabled_flag = value;
ps_pps->i1_loop_filter_across_tiles_enabled_flag = 0;
if(ps_pps->i1_tiles_enabled_flag)
{
WORD32 wd = ALIGN64(ps_codec->i4_wd);
WORD32 ht = ALIGN64(ps_codec->i4_ht);
WORD32 max_tile_cols = (wd + MIN_TILE_WD - 1) / MIN_TILE_WD;
WORD32 max_tile_rows = (ht + MIN_TILE_HT - 1) / MIN_TILE_HT;
UEV_PARSE("num_tile_columns_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_columns = value + 1;
UEV_PARSE("num_tile_rows_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_rows = value + 1;
if((ps_pps->i1_num_tile_columns < 1) ||
(ps_pps->i1_num_tile_columns > max_tile_cols) ||
(ps_pps->i1_num_tile_rows < 1) ||
(ps_pps->i1_num_tile_rows > max_tile_rows))
return IHEVCD_INVALID_HEADER;
BITS_PARSE("uniform_spacing_flag", value, ps_bitstrm, 1);
ps_pps->i1_uniform_spacing_flag = value;
{
WORD32 start;
WORD32 i, j;
start = 0;
for(i = 0; i < ps_pps->i1_num_tile_columns; i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_columns - 1))
{
UEV_PARSE("column_width_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_wd_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns -
(i * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns;
}
for(j = 0; j < ps_pps->i1_num_tile_rows; j++)
{
ps_tile = ps_pps->ps_tile + j * ps_pps->i1_num_tile_columns + i;
ps_tile->u1_pos_x = start;
ps_tile->u2_wd = value;
}
start += value;
if((start > ps_sps->i2_pic_wd_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
start = 0;
for(i = 0; i < (ps_pps->i1_num_tile_rows); i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_rows - 1))
{
UEV_PARSE("row_height_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_ht_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows -
(i * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows;
}
for(j = 0; j < ps_pps->i1_num_tile_columns; j++)
{
ps_tile = ps_pps->ps_tile + i * ps_pps->i1_num_tile_columns + j;
ps_tile->u1_pos_y = start;
ps_tile->u2_ht = value;
}
start += value;
if((start > ps_sps->i2_pic_ht_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
}
BITS_PARSE("loop_filter_across_tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_tiles_enabled_flag = value;
}
else
{
/* If tiles are not present, set first tile in each PPS to have tile
width and height equal to picture width and height */
ps_pps->i1_num_tile_columns = 1;
ps_pps->i1_num_tile_rows = 1;
ps_pps->i1_uniform_spacing_flag = 1;
ps_pps->ps_tile->u1_pos_x = 0;
ps_pps->ps_tile->u1_pos_y = 0;
ps_pps->ps_tile->u2_wd = ps_sps->i2_pic_wd_in_ctb;
ps_pps->ps_tile->u2_ht = ps_sps->i2_pic_ht_in_ctb;
}
BITS_PARSE("loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_slices_enabled_flag = value;
BITS_PARSE("deblocking_filter_control_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_control_present_flag = value;
/* Default values */
ps_pps->i1_pic_disable_deblocking_filter_flag = 0;
ps_pps->i1_deblocking_filter_override_enabled_flag = 0;
ps_pps->i1_beta_offset_div2 = 0;
ps_pps->i1_tc_offset_div2 = 0;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
BITS_PARSE("deblocking_filter_override_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_override_enabled_flag = value;
BITS_PARSE("pic_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_disable_deblocking_filter_flag = value;
if(!ps_pps->i1_pic_disable_deblocking_filter_flag)
{
SEV_PARSE("pps_beta_offset_div2", value, ps_bitstrm);
ps_pps->i1_beta_offset_div2 = value;
SEV_PARSE("pps_tc_offset_div2", value, ps_bitstrm);
ps_pps->i1_tc_offset_div2 = value;
}
}
BITS_PARSE("pps_scaling_list_data_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_pps_scaling_list_data_present_flag = value;
if(ps_pps->i1_pps_scaling_list_data_present_flag)
{
COPY_DEFAULT_SCALING_LIST(ps_pps->pi2_scaling_mat);
ihevcd_scaling_list_data(ps_codec, ps_pps->pi2_scaling_mat);
}
BITS_PARSE("lists_modification_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_lists_modification_present_flag = value;
UEV_PARSE("log2_parallel_merge_level_minus2", value, ps_bitstrm);
ps_pps->i1_log2_parallel_merge_level = value + 2;
BITS_PARSE("slice_header_extension_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_slice_header_extension_present_flag = value;
/* Not present in HM */
BITS_PARSE("pps_extension_flag", value, ps_bitstrm, 1);
if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
return IHEVCD_INVALID_PARAMETER;
ps_codec->i4_pps_done = 1;
return ret;
}
Commit Message: Ensure CTB size > 16 for clips with tiles and width/height >= 4096
For clips with tiles and dimensions >= 4096,
CTB size of 16 can result in tile position > 255.
This is not supported by the decoder
Bug: 37930177
Test: ran poc w/o crashing
Change-Id: I2f223a124c4ea9bfd98343343fd010d80a5dd8bd
(cherry picked from commit 248e72c7a8c7c382ff4397868a6c7453a6453141)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderMessageFilter::GetPluginsCallback(
IPC::Message* reply_msg,
const std::vector<webkit::WebPluginInfo>& all_plugins) {
PluginServiceFilter* filter = PluginServiceImpl::GetInstance()->GetFilter();
std::vector<webkit::WebPluginInfo> plugins;
int child_process_id = -1;
int routing_id = MSG_ROUTING_NONE;
for (size_t i = 0; i < all_plugins.size(); ++i) {
webkit::WebPluginInfo plugin(all_plugins[i]);
if (!filter || filter->IsPluginEnabled(child_process_id,
routing_id,
resource_context_,
GURL(),
GURL(),
&plugin)) {
plugins.push_back(plugin);
}
}
ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
Send(reply_msg);
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287
Target: 1
Example 2:
Code: void GLES2DecoderImpl::DoBlitFramebufferCHROMIUM(
GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
GLbitfield mask, GLenum filter) {
DCHECK(!ShouldDeferReads() && !ShouldDeferDraws());
if (!CheckBoundFramebuffersValid("glBlitFramebufferCHROMIUM")) {
return;
}
state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false);
BlitFramebufferHelper(
srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
state_.SetDeviceCapabilityState(GL_SCISSOR_TEST,
state_.enable_flags.scissor_test);
}
Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled.
This is when we expose DrawBuffers extension.
BUG=376951
TEST=the attached test case, webgl conformance
[email protected],[email protected]
Review URL: https://codereview.chromium.org/315283002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: Browser::CreateParams::CreateParams(Type type, Profile* profile)
: type(type),
profile(profile),
host_desktop_type(kDefaultHostDesktopType),
app_type(APP_TYPE_HOST),
initial_show_state(ui::SHOW_STATE_DEFAULT),
is_session_restore(false),
window(NULL) {
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ChromeURLRequestContext::ChromeURLRequestContext(
ContextType type,
chrome_browser_net::LoadTimeStats* load_time_stats)
: load_time_stats_(load_time_stats) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (load_time_stats_)
load_time_stats_->RegisterURLRequestContext(this, type);
}
Commit Message: Revert a workaround commit for a Use-After-Free crash.
Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed.
URLRequestContext does not inherit SupportsWeakPtr now.
R=mmenke
BUG=244746
Review URL: https://chromiumcodereview.appspot.com/16870008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: std::string GetDialogTypeAsString(
ui::SelectFileDialog::Type dialog_type) {
std::string type_str;
switch (dialog_type) {
case ui::SelectFileDialog::SELECT_NONE:
type_str = "full-page";
break;
case ui::SelectFileDialog::SELECT_FOLDER:
type_str = "folder";
break;
case ui::SelectFileDialog::SELECT_UPLOAD_FOLDER:
type_str = "upload-folder";
break;
case ui::SelectFileDialog::SELECT_SAVEAS_FILE:
type_str = "saveas-file";
break;
case ui::SelectFileDialog::SELECT_OPEN_FILE:
type_str = "open-file";
break;
case ui::SelectFileDialog::SELECT_OPEN_MULTI_FILE:
type_str = "open-multi-file";
break;
default:
NOTREACHED();
}
return type_str;
}
Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery.
Previous Review URL: https://codereview.chromium.org/431293002
BUG=374667
TEST=manually
[email protected], [email protected]
Review URL: https://codereview.chromium.org/433733004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::SetURL(const KURL& url) {
const KURL& new_url = url.IsEmpty() ? BlankURL() : url;
if (new_url == url_)
return;
url_ = new_url;
access_entry_from_url_ = nullptr;
UpdateBaseURL();
GetContextFeatures().UrlDidChange(this);
}
Commit Message: Inherit CSP when we inherit the security origin
This prevents attacks that use main window navigation to get out of the
existing csp constraints such as the related bug
Bug: 747847
Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8
Reviewed-on: https://chromium-review.googlesource.com/592027
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#492333}
CWE ID: CWE-732
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: alloc_limit_assert (char *fn_name, size_t size)
{
if (alloc_limit && size > alloc_limit)
{
alloc_limit_failure (fn_name, size);
exit (-1);
}
}
Commit Message: Fix integer overflows and harden memory allocator.
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int dn_hash_sock(struct sock *sk)
{
struct dn_scp *scp = DN_SK(sk);
struct hlist_head *list;
int rv = -EUSERS;
BUG_ON(sk_hashed(sk));
write_lock_bh(&dn_hash_lock);
if (!scp->addrloc && !port_alloc(sk))
goto out;
rv = -EADDRINUSE;
if ((list = dn_find_list(sk)) == NULL)
goto out;
sk_add_node(sk, list);
rv = 0;
out:
write_unlock_bh(&dn_hash_lock);
return rv;
}
Commit Message: net: add validation for the socket syscall protocol argument
郭永刚 reported that one could simply crash the kernel as root by
using a simple program:
int socket_fd;
struct sockaddr_in addr;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = 10;
socket_fd = socket(10,3,0x40000000);
connect(socket_fd , &addr,16);
AF_INET, AF_INET6 sockets actually only support 8-bit protocol
identifiers. inet_sock's skc_protocol field thus is sized accordingly,
thus larger protocol identifiers simply cut off the higher bits and
store a zero in the protocol fields.
This could lead to e.g. NULL function pointer because as a result of
the cut off inet_num is zero and we call down to inet_autobind, which
is NULL for raw sockets.
kernel: Call Trace:
kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70
kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80
kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110
kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80
kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200
kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10
kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89
I found no particular commit which introduced this problem.
CVE: CVE-2015-8543
Cc: Cong Wang <[email protected]>
Reported-by: 郭永刚 <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FakeBluetoothAgentManagerClient::UnregisterAgent(
const dbus::ObjectPath& agent_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "UnregisterAgent: " << agent_path.value();
if (service_provider_ != NULL) {
error_callback.Run(bluetooth_agent_manager::kErrorInvalidArguments,
"Agent still registered");
} else {
callback.Run();
}
}
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:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void InitSkBitmapDataForTransfer(const SkBitmap& bitmap) {
const SkImageInfo& info = bitmap.info();
color_type = info.colorType();
alpha_type = info.alphaType();
width = info.width();
height = info.height();
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125
Target: 1
Example 2:
Code: SPICE_GNUC_VISIBLE int spice_server_is_server_mouse(SpiceServer *s)
{
spice_assert(reds == s);
return reds->mouse_mode == SPICE_MOUSE_MODE_SERVER;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static Image *ReadPIXImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
Quantum
blue,
green,
red;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
size_t
bits_per_pixel,
height,
length,
width;
ssize_t
y;
/*
Open image file.
*/
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);
}
/*
Read PIX image.
*/
width=ReadBlobMSBShort(image);
height=ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image); /* x-offset */
(void) ReadBlobMSBShort(image); /* y-offset */
bits_per_pixel=ReadBlobMSBShort(image);
if ((width == 0UL) || (height == 0UL) || ((bits_per_pixel != 8) &&
(bits_per_pixel != 24)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Initialize image structure.
*/
image->columns=width;
image->rows=height;
if (bits_per_pixel == 8)
if (AcquireImageColormap(image,256) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Convert PIX raster image to pixel packets.
*/
red=(Quantum) 0;
green=(Quantum) 0;
blue=(Quantum) 0;
index=(IndexPacket) 0;
length=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
indexes=GetAuthenticIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (length == 0)
{
length=(size_t) ReadBlobByte(image);
if (bits_per_pixel == 8)
index=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
else
{
blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image));
}
}
if (image->storage_class == PseudoClass)
SetPixelIndex(indexes+x,index);
SetPixelBlue(q,blue);
SetPixelGreen(q,green);
SetPixelRed(q,red);
length--;
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
width=ReadBlobMSBLong(image);
height=ReadBlobMSBLong(image);
(void) ReadBlobMSBShort(image);
(void) ReadBlobMSBShort(image);
bits_per_pixel=ReadBlobMSBShort(image);
status=(width != 0UL) && (height == 0UL) && ((bits_per_pixel == 8) ||
(bits_per_pixel == 24)) ? MagickTrue : MagickFalse;
if (status != MagickFalse)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (status != MagickFalse);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ff_jpeg2000_init_component(Jpeg2000Component *comp,
Jpeg2000CodingStyle *codsty,
Jpeg2000QuantStyle *qntsty,
int cbps, int dx, int dy,
AVCodecContext *avctx)
{
uint8_t log2_band_prec_width, log2_band_prec_height;
int reslevelno, bandno, gbandno = 0, ret, i, j;
uint32_t csize;
if (codsty->nreslevels2decode <= 0) {
av_log(avctx, AV_LOG_ERROR, "nreslevels2decode %d invalid or uninitialized\n", codsty->nreslevels2decode);
return AVERROR_INVALIDDATA;
}
if (ret = ff_jpeg2000_dwt_init(&comp->dwt, comp->coord,
codsty->nreslevels2decode - 1,
codsty->transform))
return ret;
csize = (comp->coord[0][1] - comp->coord[0][0]) *
(comp->coord[1][1] - comp->coord[1][0]);
if (codsty->transform == FF_DWT97) {
comp->i_data = NULL;
comp->f_data = av_malloc_array(csize, sizeof(*comp->f_data));
if (!comp->f_data)
return AVERROR(ENOMEM);
} else {
comp->f_data = NULL;
comp->i_data = av_malloc_array(csize, sizeof(*comp->i_data));
if (!comp->i_data)
return AVERROR(ENOMEM);
}
comp->reslevel = av_malloc_array(codsty->nreslevels, sizeof(*comp->reslevel));
if (!comp->reslevel)
return AVERROR(ENOMEM);
/* LOOP on resolution levels */
for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
int declvl = codsty->nreslevels - reslevelno; // N_L -r see ISO/IEC 15444-1:2002 B.5
Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
/* Compute borders for each resolution level.
* Computation of trx_0, trx_1, try_0 and try_1.
* see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
reslevel->coord[i][j] =
ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1);
reslevel->log2_prec_width = codsty->log2_prec_widths[reslevelno];
reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno];
/* Number of bands for each resolution level */
if (reslevelno == 0)
reslevel->nbands = 1;
else
reslevel->nbands = 3;
/* Number of precincts wich span the tile for resolution level reslevelno
* see B.6 in ISO/IEC 15444-1:2002 eq. B-16
* num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width)
* num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width)
* for Dcinema profiles in JPEG 2000
* num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -|
* num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */
if (reslevel->coord[0][1] == reslevel->coord[0][0])
reslevel->num_precincts_x = 0;
else
reslevel->num_precincts_x =
ff_jpeg2000_ceildivpow2(reslevel->coord[0][1],
reslevel->log2_prec_width) -
(reslevel->coord[0][0] >> reslevel->log2_prec_width);
if (reslevel->coord[1][1] == reslevel->coord[1][0])
reslevel->num_precincts_y = 0;
else
reslevel->num_precincts_y =
ff_jpeg2000_ceildivpow2(reslevel->coord[1][1],
reslevel->log2_prec_height) -
(reslevel->coord[1][0] >> reslevel->log2_prec_height);
reslevel->band = av_malloc_array(reslevel->nbands, sizeof(*reslevel->band));
if (!reslevel->band)
return AVERROR(ENOMEM);
for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {
Jpeg2000Band *band = reslevel->band + bandno;
int cblkno, precno;
int nb_precincts;
/* TODO: Implementation of quantization step not finished,
* see ISO/IEC 15444-1:2002 E.1 and A.6.4. */
switch (qntsty->quantsty) {
uint8_t gain;
int numbps;
case JPEG2000_QSTY_NONE:
/* TODO: to verify. No quantization in this case */
band->f_stepsize = 1;
break;
case JPEG2000_QSTY_SI:
/*TODO: Compute formula to implement. */
numbps = cbps +
lut_gain[codsty->transform == FF_DWT53][bandno + (reslevelno > 0)];
band->f_stepsize = SHL(2048 + qntsty->mant[gbandno],
2 + numbps - qntsty->expn[gbandno]);
break;
case JPEG2000_QSTY_SE:
/* Exponent quantization step.
* Formula:
* delta_b = 2 ^ (R_b - expn_b) * (1 + (mant_b / 2 ^ 11))
* R_b = R_I + log2 (gain_b )
* see ISO/IEC 15444-1:2002 E.1.1 eqn. E-3 and E-4 */
/* TODO/WARN: value of log2 (gain_b ) not taken into account
* but it works (compared to OpenJPEG). Why?
* Further investigation needed. */
gain = cbps;
band->f_stepsize = pow(2.0, gain - qntsty->expn[gbandno]);
band->f_stepsize *= qntsty->mant[gbandno] / 2048.0 + 1.0;
break;
default:
band->f_stepsize = 0;
av_log(avctx, AV_LOG_ERROR, "Unknown quantization format\n");
break;
}
/* FIXME: In openjepg code stespize = stepsize * 0.5. Why?
* If not set output of entropic decoder is not correct. */
if (!av_codec_is_encoder(avctx->codec))
band->f_stepsize *= 0.5;
band->i_stepsize = band->f_stepsize * (1 << 15);
/* computation of tbx_0, tbx_1, tby_0, tby_1
* see ISO/IEC 15444-1:2002 B.5 eq. B-15 and tbl B.1
* codeblock width and height is computed for
* DCI JPEG 2000 codeblock_width = codeblock_width = 32 = 2 ^ 5 */
if (reslevelno == 0) {
/* for reslevelno = 0, only one band, x0_b = y0_b = 0 */
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
band->coord[i][j] =
ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0],
declvl - 1);
log2_band_prec_width = reslevel->log2_prec_width;
log2_band_prec_height = reslevel->log2_prec_height;
/* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */
band->log2_cblk_width = FFMIN(codsty->log2_cblk_width,
reslevel->log2_prec_width);
band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,
reslevel->log2_prec_height);
} else {
/* 3 bands x0_b = 1 y0_b = 0; x0_b = 0 y0_b = 1; x0_b = y0_b = 1 */
/* x0_b and y0_b are computed with ((bandno + 1 >> i) & 1) */
for (i = 0; i < 2; i++)
for (j = 0; j < 2; j++)
/* Formula example for tbx_0 = ceildiv((tcx_0 - 2 ^ (declvl - 1) * x0_b) / declvl) */
band->coord[i][j] =
ff_jpeg2000_ceildivpow2(comp->coord_o[i][j] - comp->coord_o[i][0] -
(((bandno + 1 >> i) & 1) << declvl - 1),
declvl);
/* TODO: Manage case of 3 band offsets here or
* in coding/decoding function? */
/* see ISO/IEC 15444-1:2002 eq. B-17 and eq. B-15 */
band->log2_cblk_width = FFMIN(codsty->log2_cblk_width,
reslevel->log2_prec_width - 1);
band->log2_cblk_height = FFMIN(codsty->log2_cblk_height,
reslevel->log2_prec_height - 1);
log2_band_prec_width = reslevel->log2_prec_width - 1;
log2_band_prec_height = reslevel->log2_prec_height - 1;
}
for (j = 0; j < 2; j++)
band->coord[0][j] = ff_jpeg2000_ceildiv(band->coord[0][j], dx);
for (j = 0; j < 2; j++)
band->coord[1][j] = ff_jpeg2000_ceildiv(band->coord[1][j], dy);
band->prec = av_malloc_array(reslevel->num_precincts_x *
(uint64_t)reslevel->num_precincts_y,
sizeof(*band->prec));
if (!band->prec)
return AVERROR(ENOMEM);
nb_precincts = reslevel->num_precincts_x * reslevel->num_precincts_y;
for (precno = 0; precno < nb_precincts; precno++) {
Jpeg2000Prec *prec = band->prec + precno;
/* TODO: Explain formula for JPEG200 DCINEMA. */
/* TODO: Verify with previous count of codeblocks per band */
/* Compute P_x0 */
prec->coord[0][0] = (precno % reslevel->num_precincts_x) *
(1 << log2_band_prec_width);
prec->coord[0][0] = FFMAX(prec->coord[0][0], band->coord[0][0]);
/* Compute P_y0 */
prec->coord[1][0] = (precno / reslevel->num_precincts_x) *
(1 << log2_band_prec_height);
prec->coord[1][0] = FFMAX(prec->coord[1][0], band->coord[1][0]);
/* Compute P_x1 */
prec->coord[0][1] = prec->coord[0][0] +
(1 << log2_band_prec_width);
prec->coord[0][1] = FFMIN(prec->coord[0][1], band->coord[0][1]);
/* Compute P_y1 */
prec->coord[1][1] = prec->coord[1][0] +
(1 << log2_band_prec_height);
prec->coord[1][1] = FFMIN(prec->coord[1][1], band->coord[1][1]);
prec->nb_codeblocks_width =
ff_jpeg2000_ceildivpow2(prec->coord[0][1] -
prec->coord[0][0],
band->log2_cblk_width);
prec->nb_codeblocks_height =
ff_jpeg2000_ceildivpow2(prec->coord[1][1] -
prec->coord[1][0],
band->log2_cblk_height);
/* Tag trees initialization */
prec->cblkincl =
ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,
prec->nb_codeblocks_height);
if (!prec->cblkincl)
return AVERROR(ENOMEM);
prec->zerobits =
ff_jpeg2000_tag_tree_init(prec->nb_codeblocks_width,
prec->nb_codeblocks_height);
if (!prec->zerobits)
return AVERROR(ENOMEM);
prec->cblk = av_mallocz_array(prec->nb_codeblocks_width *
(uint64_t)prec->nb_codeblocks_height,
sizeof(*prec->cblk));
if (!prec->cblk)
return AVERROR(ENOMEM);
for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
uint16_t Cx0, Cy0;
/* Compute coordinates of codeblocks */
/* Compute Cx0*/
Cx0 = (prec->coord[0][0] >> band->log2_cblk_width) << band->log2_cblk_width;
Cx0 = Cx0 + ((cblkno % prec->nb_codeblocks_width) << band->log2_cblk_width);
cblk->coord[0][0] = FFMAX(Cx0, prec->coord[0][0]);
/* Compute Cy0*/
Cy0 = (prec->coord[1][0] >> band->log2_cblk_height) << band->log2_cblk_height;
Cy0 = Cy0 + ((cblkno / prec->nb_codeblocks_width) << band->log2_cblk_height);
cblk->coord[1][0] = FFMAX(Cy0, prec->coord[1][0]);
/* Compute Cx1 */
cblk->coord[0][1] = FFMIN(Cx0 + (1 << band->log2_cblk_width),
prec->coord[0][1]);
/* Compute Cy1 */
cblk->coord[1][1] = FFMIN(Cy0 + (1 << band->log2_cblk_height),
prec->coord[1][1]);
/* Update code-blocks coordinates according sub-band position */
if ((bandno + !!reslevelno) & 1) {
cblk->coord[0][0] += comp->reslevel[reslevelno-1].coord[0][1] -
comp->reslevel[reslevelno-1].coord[0][0];
cblk->coord[0][1] += comp->reslevel[reslevelno-1].coord[0][1] -
comp->reslevel[reslevelno-1].coord[0][0];
}
if ((bandno + !!reslevelno) & 2) {
cblk->coord[1][0] += comp->reslevel[reslevelno-1].coord[1][1] -
comp->reslevel[reslevelno-1].coord[1][0];
cblk->coord[1][1] += comp->reslevel[reslevelno-1].coord[1][1] -
comp->reslevel[reslevelno-1].coord[1][0];
}
cblk->zero = 0;
cblk->lblock = 3;
cblk->length = 0;
cblk->lengthinc = 0;
cblk->npasses = 0;
}
}
}
}
return 0;
}
Commit Message: jpeg2000: fix dereferencing invalid pointers
Found-by: Laurent Butti <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoBlendEquation(GLenum mode) {
api()->glBlendEquationFn(mode);
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void vma_gap_update(struct vm_area_struct *vma)
{
/*
* As it turns out, RB_DECLARE_CALLBACKS() already created a callback
* function that does exacltly what we want.
*/
vma_gap_callbacks_propagate(&vma->vm_rb, NULL);
}
Commit Message: mm: enforce min addr even if capable() in expand_downwards()
security_mmap_addr() does a capability check with current_cred(), but
we can reach this code from contexts like a VFS write handler where
current_cred() must not be used.
This can be abused on systems without SMAP to make NULL pointer
dereferences exploitable again.
Fixes: 8869477a49c3 ("security: protect from stack expansion into low vm addresses")
Cc: [email protected]
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void UtilityServiceFactory::RegisterServices(ServiceMap* services) {
GetContentClient()->utility()->RegisterServices(services);
service_manager::EmbeddedServiceInfo video_capture_info;
video_capture_info.factory = base::Bind(&CreateVideoCaptureService);
services->insert(
std::make_pair(video_capture::mojom::kServiceName, video_capture_info));
#if BUILDFLAG(ENABLE_PEPPER_CDMS)
service_manager::EmbeddedServiceInfo info;
info.factory = base::Bind(&CreateMediaService);
services->insert(std::make_pair(media::mojom::kMediaServiceName, info));
#endif
service_manager::EmbeddedServiceInfo shape_detection_info;
shape_detection_info.factory =
base::Bind(&shape_detection::ShapeDetectionService::Create);
services->insert(std::make_pair(shape_detection::mojom::kServiceName,
shape_detection_info));
service_manager::EmbeddedServiceInfo data_decoder_info;
data_decoder_info.factory = base::Bind(&CreateDataDecoderService);
services->insert(
std::make_pair(data_decoder::mojom::kServiceName, data_decoder_info));
if (base::FeatureList::IsEnabled(features::kNetworkService)) {
GetContentClient()->utility()->RegisterNetworkBinders(
network_registry_.get());
service_manager::EmbeddedServiceInfo network_info;
network_info.factory = base::Bind(
&UtilityServiceFactory::CreateNetworkService, base::Unretained(this));
network_info.task_runner = ChildProcess::current()->io_task_runner();
services->insert(
std::make_pair(content::mojom::kNetworkServiceName, network_info));
}
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int internal_valid_message_handler(nl_msg *msg, void *arg)
{
wifi_handle handle = (wifi_handle)arg;
hal_info *info = getHalInfo(handle);
WifiEvent event(msg);
int res = event.parse();
if (res < 0) {
ALOGE("Failed to parse event: %d", res);
return NL_SKIP;
}
int cmd = event.get_cmd();
uint32_t vendor_id = 0;
int subcmd = 0;
if (cmd == NL80211_CMD_VENDOR) {
vendor_id = event.get_u32(NL80211_ATTR_VENDOR_ID);
subcmd = event.get_u32(NL80211_ATTR_VENDOR_SUBCMD);
ALOGV("event received %s, vendor_id = 0x%0x, subcmd = 0x%0x",
event.get_cmdString(), vendor_id, subcmd);
} else {
}
bool dispatched = false;
pthread_mutex_lock(&info->cb_lock);
for (int i = 0; i < info->num_event_cb; i++) {
if (cmd == info->event_cb[i].nl_cmd) {
if (cmd == NL80211_CMD_VENDOR
&& ((vendor_id != info->event_cb[i].vendor_id)
|| (subcmd != info->event_cb[i].vendor_subcmd)))
{
/* event for a different vendor, ignore it */
continue;
}
cb_info *cbi = &(info->event_cb[i]);
nl_recvmsg_msg_cb_t cb_func = cbi->cb_func;
void *cb_arg = cbi->cb_arg;
WifiCommand *cmd = (WifiCommand *)cbi->cb_arg;
if (cmd != NULL) {
cmd->addRef();
}
pthread_mutex_unlock(&info->cb_lock);
if (cb_func)
(*cb_func)(msg, cb_arg);
if (cmd != NULL) {
cmd->releaseRef();
}
return NL_OK;
}
}
pthread_mutex_unlock(&info->cb_lock);
return NL_OK;
}
Commit Message: Fix use-after-free in wifi_cleanup()
Release reference to cmd only after possibly calling getType().
BUG: 25753768
Change-Id: Id2156ce51acec04e8364706cf7eafc7d4adae9eb
(cherry picked from commit d7f3cb9915d9ac514393d0ad7767662958054b8f https://googleplex-android-review.git.corp.google.com/#/c/815223)
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void php_snmp_internal(INTERNAL_FUNCTION_PARAMETERS, int st,
struct snmp_session *session,
struct objid_query *objid_query)
{
struct snmp_session *ss;
struct snmp_pdu *pdu=NULL, *response;
struct variable_list *vars;
oid root[MAX_NAME_LEN];
size_t rootlen = 0;
int status, count, found;
char buf[2048];
char buf2[2048];
int keepwalking=1;
char *err;
zval *snmpval = NULL;
int snmp_errno;
/* we start with retval=FALSE. If any actual data is acquired, retval will be set to appropriate type */
RETVAL_FALSE;
/* reset errno and errstr */
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_NOERROR, "");
if (st & SNMP_CMD_WALK) { /* remember root OID */
memmove((char *)root, (char *)(objid_query->vars[0].name), (objid_query->vars[0].name_length) * sizeof(oid));
rootlen = objid_query->vars[0].name_length;
objid_query->offset = objid_query->count;
}
if ((ss = snmp_open(session)) == NULL) {
snmp_error(session, NULL, NULL, &err);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open snmp connection: %s", err);
free(err);
RETVAL_FALSE;
return;
}
if ((st & SNMP_CMD_SET) && objid_query->count > objid_query->step) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_MULTIPLE_SET_QUERIES, "Can not fit all OIDs for SET query into one packet, using multiple queries");
}
while (keepwalking) {
keepwalking = 0;
if (st & SNMP_CMD_WALK) {
if (session->version == SNMP_VERSION_1) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else {
pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
pdu->non_repeaters = objid_query->non_repeaters;
pdu->max_repetitions = objid_query->max_repetitions;
}
snmp_add_null_var(pdu, objid_query->vars[0].name, objid_query->vars[0].name_length);
} else {
if (st & SNMP_CMD_GET) {
pdu = snmp_pdu_create(SNMP_MSG_GET);
} else if (st & SNMP_CMD_GETNEXT) {
pdu = snmp_pdu_create(SNMP_MSG_GETNEXT);
} else if (st & SNMP_CMD_SET) {
pdu = snmp_pdu_create(SNMP_MSG_SET);
} else {
snmp_close(ss);
php_error_docref(NULL TSRMLS_CC, E_ERROR, "Unknown SNMP command (internals)");
RETVAL_FALSE;
return;
}
for (count = 0; objid_query->offset < objid_query->count && count < objid_query->step; objid_query->offset++, count++){
if (st & SNMP_CMD_SET) {
if ((snmp_errno = snmp_add_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value))) {
snprint_objid(buf, sizeof(buf), objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_PARSING_ERROR, "Could not add variable: OID='%s' type='%c' value='%s': %s", buf, objid_query->vars[objid_query->offset].type, objid_query->vars[objid_query->offset].value, snmp_api_errstring(snmp_errno));
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
} else {
snmp_add_null_var(pdu, objid_query->vars[objid_query->offset].name, objid_query->vars[objid_query->offset].name_length);
}
}
if(pdu->variables == NULL){
snmp_free_pdu(pdu);
snmp_close(ss);
RETVAL_FALSE;
return;
}
}
retry:
status = snmp_synch_response(ss, pdu, &response);
if (status == STAT_SUCCESS) {
if (response->errstat == SNMP_ERR_NOERROR) {
if (st & SNMP_CMD_SET) {
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
continue;
}
snmp_free_pdu(response);
snmp_close(ss);
RETVAL_TRUE;
return;
}
for (vars = response->variables; vars; vars = vars->next_variable) {
/* do not output errors as values */
if ( vars->type == SNMP_ENDOFMIBVIEW ||
vars->type == SNMP_NOSUCHOBJECT ||
vars->type == SNMP_NOSUCHINSTANCE ) {
if ((st & SNMP_CMD_WALK) && Z_TYPE_P(return_value) == IS_ARRAY) {
break;
}
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
snprint_value(buf2, sizeof(buf2), vars->name, vars->name_length, vars);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, buf2);
continue;
}
if ((st & SNMP_CMD_WALK) &&
(vars->name_length < rootlen || memcmp(root, vars->name, rootlen * sizeof(oid)))) { /* not part of this subtree */
if (Z_TYPE_P(return_value) == IS_ARRAY) { /* some records are fetched already, shut down further lookup */
keepwalking = 0;
} else {
/* first fetched OID is out of subtree, fallback to GET query */
st |= SNMP_CMD_GET;
st ^= SNMP_CMD_WALK;
objid_query->offset = 0;
keepwalking = 1;
}
break;
}
MAKE_STD_ZVAL(snmpval);
php_snmp_getvalue(vars, snmpval TSRMLS_CC, objid_query->valueretrieval);
if (objid_query->array_output) {
if (Z_TYPE_P(return_value) == IS_BOOL) {
array_init(return_value);
}
if (st & SNMP_NUMERIC_KEYS) {
add_next_index_zval(return_value, snmpval);
} else if (st & SNMP_ORIGINAL_NAMES_AS_KEYS && st & SNMP_CMD_GET) {
found = 0;
for (count = 0; count < objid_query->count; count++) {
if (objid_query->vars[count].name_length == vars->name_length && snmp_oid_compare(objid_query->vars[count].name, objid_query->vars[count].name_length, vars->name, vars->name_length) == 0) {
found = 1;
objid_query->vars[count].name_length = 0; /* mark this name as used */
break;
}
}
if (found) {
add_assoc_zval(return_value, objid_query->vars[count].oid, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not find original OID name for '%s'", buf2);
}
} else if (st & SNMP_USE_SUFFIX_AS_KEYS && st & SNMP_CMD_WALK) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
if (rootlen <= vars->name_length && snmp_oid_compare(root, rootlen, vars->name, rootlen) == 0) {
buf2[0] = '\0';
count = rootlen;
while(count < vars->name_length){
sprintf(buf, "%lu.", vars->name[count]);
strcat(buf2, buf);
count++;
}
buf2[strlen(buf2) - 1] = '\0'; /* remove trailing '.' */
}
add_assoc_zval(return_value, buf2, snmpval);
} else {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
add_assoc_zval(return_value, buf2, snmpval);
}
} else {
*return_value = *snmpval;
zval_copy_ctor(return_value);
zval_ptr_dtor(&snmpval);
break;
}
/* OID increase check */
if (st & SNMP_CMD_WALK) {
if (objid_query->oid_increasing_check == TRUE && snmp_oid_compare(objid_query->vars[0].name, objid_query->vars[0].name_length, vars->name, vars->name_length) >= 0) {
snprint_objid(buf2, sizeof(buf2), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_OID_NOT_INCREASING, "Error: OID not increasing: %s", buf2);
keepwalking = 0;
} else {
memmove((char *)(objid_query->vars[0].name), (char *)vars->name, vars->name_length * sizeof(oid));
objid_query->vars[0].name_length = vars->name_length;
keepwalking = 1;
}
}
}
if (objid_query->offset < objid_query->count) { /* we have unprocessed OIDs */
keepwalking = 1;
}
} else {
if (st & SNMP_CMD_WALK && response->errstat == SNMP_ERR_TOOBIG && objid_query->max_repetitions > 1) { /* Answer will not fit into single packet */
objid_query->max_repetitions /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (!(st & SNMP_CMD_WALK) || response->errstat != SNMP_ERR_NOSUCHNAME || Z_TYPE_P(return_value) == IS_BOOL) {
for ( count=1, vars = response->variables;
vars && count != response->errindex;
vars = vars->next_variable, count++);
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT) && response->errstat == SNMP_ERR_TOOBIG && objid_query->step > 1) { /* Answer will not fit into single packet */
objid_query->offset = ((objid_query->offset > objid_query->step) ? (objid_query->offset - objid_query->step) : 0 );
objid_query->step /= 2;
snmp_free_pdu(response);
keepwalking = 1;
continue;
}
if (vars) {
snprint_objid(buf, sizeof(buf), vars->name, vars->name_length);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at '%s': %s", buf, snmp_errstring(response->errstat));
} else {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_ERROR_IN_REPLY, "Error in packet at %u object_id: %s", response->errindex, snmp_errstring(response->errstat));
}
if (st & (SNMP_CMD_GET | SNMP_CMD_GETNEXT)) { /* cut out bogus OID and retry */
if ((pdu = snmp_fix_pdu(response, ((st & SNMP_CMD_GET) ? SNMP_MSG_GET : SNMP_MSG_GETNEXT) )) != NULL) {
snmp_free_pdu(response);
goto retry;
}
}
snmp_free_pdu(response);
snmp_close(ss);
if (objid_query->array_output) {
zval_dtor(return_value);
}
RETVAL_FALSE;
return;
}
}
} else if (status == STAT_TIMEOUT) {
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_TIMEOUT, "No response from %s", session->peername);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
} else { /* status == STAT_ERROR */
snmp_error(ss, NULL, NULL, &err);
php_snmp_error(getThis(), NULL TSRMLS_CC, PHP_SNMP_ERRNO_GENERIC, "Fatal error: %s", err);
free(err);
if (objid_query->array_output) {
zval_dtor(return_value);
}
snmp_close(ss);
RETVAL_FALSE;
return;
}
if (response) {
snmp_free_pdu(response);
}
} /* keepwalking */
snmp_close(ss);
}
Commit Message:
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: kadm5_create_principal_3(void *server_handle,
kadm5_principal_ent_t entry, long mask,
int n_ks_tuple, krb5_key_salt_tuple *ks_tuple,
char *password)
{
krb5_db_entry *kdb;
osa_princ_ent_rec adb;
kadm5_policy_ent_rec polent;
krb5_boolean have_polent = FALSE;
krb5_int32 now;
krb5_tl_data *tl_data_tail;
unsigned int ret;
kadm5_server_handle_t handle = server_handle;
krb5_keyblock *act_mkey;
krb5_kvno act_kvno;
int new_n_ks_tuple = 0;
krb5_key_salt_tuple *new_ks_tuple = NULL;
CHECK_HANDLE(server_handle);
krb5_clear_error_message(handle->context);
check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password);
/*
* Argument sanity checking, and opening up the DB
*/
if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) ||
(mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) ||
(mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) ||
(mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) ||
(mask & KADM5_FAIL_AUTH_COUNT))
return KADM5_BAD_MASK;
if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0)
return KADM5_BAD_MASK;
if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR))
return KADM5_BAD_MASK;
if((mask & ~ALL_PRINC_MASK))
return KADM5_BAD_MASK;
if (entry == NULL)
return EINVAL;
/*
* Check to see if the principal exists
*/
ret = kdb_get_entry(handle, entry->principal, &kdb, &adb);
switch(ret) {
case KADM5_UNK_PRINC:
break;
case 0:
kdb_free_entry(handle, kdb, &adb);
return KADM5_DUP;
default:
return ret;
}
kdb = krb5_db_alloc(handle->context, NULL, sizeof(*kdb));
if (kdb == NULL)
return ENOMEM;
memset(kdb, 0, sizeof(*kdb));
memset(&adb, 0, sizeof(osa_princ_ent_rec));
/*
* If a policy was specified, load it.
* If we can not find the one specified return an error
*/
if ((mask & KADM5_POLICY)) {
ret = get_policy(handle, entry->policy, &polent, &have_polent);
if (ret)
goto cleanup;
}
if (password) {
ret = passwd_check(handle, password, have_polent ? &polent : NULL,
entry->principal);
if (ret)
goto cleanup;
}
/*
* Start populating the various DB fields, using the
* "defaults" for fields that were not specified by the
* mask.
*/
if ((ret = krb5_timeofday(handle->context, &now)))
goto cleanup;
kdb->magic = KRB5_KDB_MAGIC_NUMBER;
kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */
if ((mask & KADM5_ATTRIBUTES))
kdb->attributes = entry->attributes;
else
kdb->attributes = handle->params.flags;
if ((mask & KADM5_MAX_LIFE))
kdb->max_life = entry->max_life;
else
kdb->max_life = handle->params.max_life;
if (mask & KADM5_MAX_RLIFE)
kdb->max_renewable_life = entry->max_renewable_life;
else
kdb->max_renewable_life = handle->params.max_rlife;
if ((mask & KADM5_PRINC_EXPIRE_TIME))
kdb->expiration = entry->princ_expire_time;
else
kdb->expiration = handle->params.expiration;
kdb->pw_expiration = 0;
if (have_polent) {
if(polent.pw_max_life)
kdb->pw_expiration = now + polent.pw_max_life;
else
kdb->pw_expiration = 0;
}
if ((mask & KADM5_PW_EXPIRATION))
kdb->pw_expiration = entry->pw_expiration;
kdb->last_success = 0;
kdb->last_failed = 0;
kdb->fail_auth_count = 0;
/* this is kind of gross, but in order to free the tl data, I need
to free the entire kdb entry, and that will try to free the
principal. */
if ((ret = kadm5_copy_principal(handle->context,
entry->principal, &(kdb->princ))))
goto cleanup;
if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now)))
goto cleanup;
if (mask & KADM5_TL_DATA) {
/* splice entry->tl_data onto the front of kdb->tl_data */
for (tl_data_tail = entry->tl_data; tl_data_tail;
tl_data_tail = tl_data_tail->tl_data_next)
{
ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail);
if( ret )
goto cleanup;
}
}
/*
* We need to have setup the TL data, so we have strings, so we can
* check enctype policy, which is why we check/initialize ks_tuple
* this late.
*/
ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple,
&new_n_ks_tuple, &new_ks_tuple);
if (ret)
goto cleanup;
/* initialize the keys */
ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey);
if (ret)
goto cleanup;
if (mask & KADM5_KEY_DATA) {
/* The client requested no keys for this principal. */
assert(entry->n_key_data == 0);
} else if (password) {
ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple,
new_n_ks_tuple, password,
(mask & KADM5_KVNO)?entry->kvno:1,
FALSE, kdb);
} else {
/* Null password means create with random key (new in 1.8). */
ret = krb5_dbe_crk(handle->context, &master_keyblock,
new_ks_tuple, new_n_ks_tuple, FALSE, kdb);
}
if (ret)
goto cleanup;
/* Record the master key VNO used to encrypt this entry's keys */
ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno);
if (ret)
goto cleanup;
ret = k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_PRECOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
if (ret)
goto cleanup;
/* populate the admin-server-specific fields. In the OV server,
this used to be in a separate database. Since there's already
marshalling code for the admin fields, to keep things simple,
I'm going to keep it, and make all the admin stuff occupy a
single tl_data record, */
adb.admin_history_kvno = INITIAL_HIST_KVNO;
if (mask & KADM5_POLICY) {
adb.aux_attributes = KADM5_POLICY;
/* this does *not* need to be strdup'ed, because adb is xdr */
/* encoded in osa_adb_create_princ, and not ever freed */
adb.policy = entry->policy;
}
/* In all cases key and the principal data is set, let the database provider know */
kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ;
/* store the new db entry */
ret = kdb_put_entry(handle, kdb, &adb);
(void) k5_kadm5_hook_create(handle->context, handle->hook_handles,
KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask,
new_n_ks_tuple, new_ks_tuple, password);
cleanup:
free(new_ks_tuple);
krb5_db_free_principal(handle->context, kdb);
if (have_polent)
(void) kadm5_free_policy_ent(handle->lhandle, &polent);
return ret;
}
Commit Message: Check for null kadm5 policy name [CVE-2015-8630]
In kadm5_create_principal_3() and kadm5_modify_principal(), check for
entry->policy being null when KADM5_POLICY is included in the mask.
CVE-2015-8630:
In MIT krb5 1.12 and later, an authenticated attacker with permission
to modify a principal entry can cause kadmind to dereference a null
pointer by supplying a null policy value but including KADM5_POLICY in
the mask.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8342 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID:
Target: 1
Example 2:
Code: bool PermissionsData::HasWithheldImpliedAllHosts() const {
base::AutoLock auto_lock(runtime_lock_);
return !withheld_permissions_unsafe_->explicit_hosts().is_empty() ||
!withheld_permissions_unsafe_->scriptable_hosts().is_empty();
}
Commit Message: [Extensions] Restrict tabs.captureVisibleTab()
Modify the permissions for tabs.captureVisibleTab(). Instead of just
checking for <all_urls> and assuming its safe, do the following:
- If the page is a "normal" web page (e.g., http/https), allow the
capture if the extension has activeTab granted or <all_urls>.
- If the page is a file page (file:///), allow the capture if the
extension has file access *and* either of the <all_urls> or
activeTab permissions.
- If the page is a chrome:// page, allow the capture only if the
extension has activeTab granted.
Bug: 810220
Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304
Reviewed-on: https://chromium-review.googlesource.com/981195
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Karan Bhatia <[email protected]>
Cr-Commit-Position: refs/heads/master@{#548891}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void FrameLoader::LoadInSameDocument(
const KURL& url,
scoped_refptr<SerializedScriptValue> state_object,
FrameLoadType frame_load_type,
HistoryItem* history_item,
ClientRedirectPolicy client_redirect,
Document* initiating_document) {
DCHECK(!state_object || frame_load_type == kFrameLoadTypeBackForward);
DetachDocumentLoader(provisional_document_loader_);
if (!frame_->GetPage())
return;
SaveScrollState();
KURL old_url = frame_->GetDocument()->Url();
bool hash_change = EqualIgnoringFragmentIdentifier(url, old_url) &&
url.FragmentIdentifier() != old_url.FragmentIdentifier();
if (hash_change) {
frame_->GetEventHandler().StopAutoscroll();
frame_->DomWindow()->EnqueueHashchangeEvent(old_url, url);
}
document_loader_->SetIsClientRedirect(client_redirect ==
ClientRedirectPolicy::kClientRedirect);
if (history_item)
document_loader_->SetItemForHistoryNavigation(history_item);
UpdateForSameDocumentNavigation(url, kSameDocumentNavigationDefault, nullptr,
kScrollRestorationAuto, frame_load_type,
initiating_document);
document_loader_->GetInitialScrollState().was_scrolled_by_user = false;
frame_->GetDocument()->CheckCompleted();
std::unique_ptr<HistoryItem::ViewState> view_state;
if (history_item && history_item->GetViewState()) {
view_state =
std::make_unique<HistoryItem::ViewState>(*history_item->GetViewState());
}
frame_->DomWindow()->StatePopped(state_object
? std::move(state_object)
: SerializedScriptValue::NullValue());
if (history_item) {
RestoreScrollPositionAndViewState(frame_load_type, kHistorySameDocumentLoad,
view_state.get(),
history_item->ScrollRestorationType());
}
ProcessFragment(url, frame_load_type, kNavigationWithinSameDocument);
TakeObjectSnapshot();
}
Commit Message: Fix detach with open()ed document leaving parent loading indefinitely
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Bug: 803416
Test: fast/loader/document-open-iframe-then-detach.html
Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6
Reviewed-on: https://chromium-review.googlesource.com/887298
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Nate Chapin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532967}
CWE ID: CWE-362
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: virtual void SetUpCommandLine(CommandLine* command_line) {
GpuFeatureTest::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableThreadedCompositing);
}
Commit Message: Revert 124346 - Add basic threaded compositor test to gpu_feature_browsertest.cc
BUG=113159
Review URL: http://codereview.chromium.org/9509001
[email protected]
Review URL: https://chromiumcodereview.appspot.com/9561011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@124356 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: void EnableAction(MediaSessionAction action) {
actions_.insert(action);
NotifyUpdatedActions();
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool smb_splice_chain(uint8_t **poutbuf, uint8_t smb_command,
uint8_t wct, const uint16_t *vwv,
size_t bytes_alignment,
uint32_t num_bytes, const uint8_t *bytes)
{
uint8_t *outbuf;
size_t old_size, new_size;
size_t ofs;
size_t chain_padding = 0;
size_t bytes_padding = 0;
bool first_request;
old_size = talloc_get_size(*poutbuf);
/*
* old_size == smb_wct means we're pushing the first request in for
* libsmb/
*/
first_request = (old_size == smb_wct);
if (!first_request && ((old_size % 4) != 0)) {
/*
* Align the wct field of subsequent requests to a 4-byte
* boundary
*/
chain_padding = 4 - (old_size % 4);
}
/*
* After the old request comes the new wct field (1 byte), the vwv's
* and the num_bytes field. After at we might need to align the bytes
* given to us to "bytes_alignment", increasing the num_bytes value.
*/
new_size = old_size + chain_padding + 1 + wct * sizeof(uint16_t) + 2;
if ((bytes_alignment != 0) && ((new_size % bytes_alignment) != 0)) {
bytes_padding = bytes_alignment - (new_size % bytes_alignment);
}
new_size += bytes_padding + num_bytes;
if ((smb_command != SMBwriteX) && (new_size > 0xffff)) {
DEBUG(1, ("splice_chain: %u bytes won't fit\n",
(unsigned)new_size));
return false;
}
outbuf = TALLOC_REALLOC_ARRAY(NULL, *poutbuf, uint8_t, new_size);
if (outbuf == NULL) {
DEBUG(0, ("talloc failed\n"));
return false;
}
*poutbuf = outbuf;
if (first_request) {
SCVAL(outbuf, smb_com, smb_command);
} else {
size_t andx_cmd_ofs;
if (!find_andx_cmd_ofs(outbuf, &andx_cmd_ofs)) {
DEBUG(1, ("invalid command chain\n"));
*poutbuf = TALLOC_REALLOC_ARRAY(
NULL, *poutbuf, uint8_t, old_size);
return false;
}
if (chain_padding != 0) {
memset(outbuf + old_size, 0, chain_padding);
old_size += chain_padding;
}
SCVAL(outbuf, andx_cmd_ofs, smb_command);
SSVAL(outbuf, andx_cmd_ofs + 2, old_size - 4);
}
ofs = old_size;
/*
* Push the chained request:
*
* wct field
*/
SCVAL(outbuf, ofs, wct);
ofs += 1;
/*
* vwv array
*/
memcpy(outbuf + ofs, vwv, sizeof(uint16_t) * wct);
ofs += sizeof(uint16_t) * wct;
/*
* bcc (byte count)
*/
SSVAL(outbuf, ofs, num_bytes + bytes_padding);
ofs += sizeof(uint16_t);
/*
* padding
*/
if (bytes_padding != 0) {
memset(outbuf + ofs, 0, bytes_padding);
ofs += bytes_padding;
}
/*
* The bytes field
*/
memcpy(outbuf + ofs, bytes, num_bytes);
return true;
}
Commit Message:
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: rpki_rtr_print(netdissect_options *ndo, register const u_char *pptr, register u_int len)
{
u_int tlen, pdu_type, pdu_len;
const u_char *tptr;
const rpki_rtr_pdu *pdu_header;
tptr = pptr;
tlen = len;
if (!ndo->ndo_vflag) {
ND_PRINT((ndo, ", RPKI-RTR"));
return;
}
while (tlen >= sizeof(rpki_rtr_pdu)) {
ND_TCHECK2(*tptr, sizeof(rpki_rtr_pdu));
pdu_header = (const rpki_rtr_pdu *)tptr;
pdu_type = pdu_header->pdu_type;
pdu_len = EXTRACT_32BITS(pdu_header->length);
ND_TCHECK2(*tptr, pdu_len);
/* infinite loop check */
if (!pdu_type || !pdu_len) {
break;
}
if (tlen < pdu_len) {
goto trunc;
}
/*
* Print the PDU.
*/
if (rpki_rtr_pdu_print(ndo, tptr, 8))
goto trunc;
tlen -= pdu_len;
tptr += pdu_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t%s", tstr));
}
Commit Message: CVE-2017-13050/RPKI-Router: fix a few bugs
The decoder didn't properly check that the PDU length stored in the PDU
header is correct. The only check in place was in rpki_rtr_print() and it
tested whether the length is zero but that is not sufficient. Make all
necessary length and bounds checks, both generic and type-specific, in
rpki_rtr_pdu_print() and reduce rpki_rtr_print() to a simple loop.
This also fixes a minor bug and PDU type 0 (Serial Notify from RFC 6810
Section 5.2) is valid again.
In rpki_rtr_pdu_print() any protocol version was considered version 0,
fix it to skip the rest of input if the PDU protocol version is unknown.
Ibid, the PDU type 10 (Error Report from RFC 6810 Section 5.10) case
block didn't consider the "Length of Error Text" data element mandatory,
put it right.
Ibid, when printing an encapsulated PDU, give itself (via recursion)
respective buffer length to make it possible to tell whether the
encapsulated PDU fits. Do not recurse deeper than 2nd level.
Update prior RPKI-Router test cases that now stop to decode earlier
because of the stricter checks.
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
Target: 1
Example 2:
Code: void HTMLInputElement::EndEditing() {
DCHECK(GetDocument().IsActive());
if (!GetDocument().IsActive())
return;
if (!IsTextField())
return;
LocalFrame* frame = GetDocument().GetFrame();
frame->GetSpellChecker().DidEndEditingOnTextField(this);
frame->GetPage()->GetChromeClient().DidEndEditingOnTextField(*this);
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virDomainDetachDevice(virDomainPtr domain, const char *xml)
{
virConnectPtr conn;
VIR_DOMAIN_DEBUG(domain, "xml=%s", xml);
virResetLastError();
virCheckDomainReturn(domain, -1);
conn = domain->conn;
virCheckNonNullArgGoto(xml, error);
virCheckReadOnlyGoto(conn->flags, error);
if (conn->driver->domainDetachDevice) {
int ret;
ret = conn->driver->domainDetachDevice(domain, xml);
if (ret < 0)
goto error;
return ret;
}
virReportUnsupportedError();
error:
virDispatchError(domain->conn);
return -1;
}
Commit Message: virDomainGetTime: Deny on RO connections
We have a policy that if API may end up talking to a guest agent
it should require RW connection. We don't obey the rule in
virDomainGetTime().
Signed-off-by: Michal Privoznik <[email protected]>
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) {
if (network_state_ != kNetworkLoading)
return;
double time = WTF::CurrentTime();
double timedelta = time - previous_progress_time_;
if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) {
ScheduleEvent(EventTypeNames::progress);
previous_progress_time_ = time;
sent_stalled_event_ = false;
if (GetLayoutObject())
GetLayoutObject()->UpdateFromElement();
} else if (timedelta > 3.0 && !sent_stalled_event_) {
ScheduleEvent(EventTypeNames::stalled);
sent_stalled_event_ = true;
SetShouldDelayLoadEvent(false);
}
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int igmp_mc_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"Idx\tDevice : Count Querier\tGroup Users Timer\tReporter\n");
else {
struct ip_mc_list *im = (struct ip_mc_list *)v;
struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq);
char *querier;
#ifdef CONFIG_IP_MULTICAST
querier = IGMP_V1_SEEN(state->in_dev) ? "V1" :
IGMP_V2_SEEN(state->in_dev) ? "V2" :
"V3";
#else
querier = "NONE";
#endif
if (rcu_dereference(state->in_dev->mc_list) == im) {
seq_printf(seq, "%d\t%-10s: %5d %7s\n",
state->dev->ifindex, state->dev->name, state->in_dev->mc_count, querier);
}
seq_printf(seq,
"\t\t\t\t%08X %5d %d:%08lX\t\t%d\n",
im->multiaddr, im->users,
im->tm_running, im->tm_running ?
jiffies_to_clock_t(im->timer.expires-jiffies) : 0,
im->reporter);
}
return 0;
}
Commit Message: igmp: Avoid zero delay when receiving odd mixture of IGMP queries
Commit 5b7c84066733c5dfb0e4016d939757b38de189e4 ('ipv4: correct IGMP
behavior on v3 query during v2-compatibility mode') added yet another
case for query parsing, which can result in max_delay = 0. Substitute
a value of 1, as in the usual v3 case.
Reported-by: Simon McVittie <[email protected]>
References: http://bugs.debian.org/654876
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) {
ALOGV("entering parseChunk %lld/%d", (long long)*offset, depth);
uint32_t hdr[2];
if (mDataSource->readAt(*offset, hdr, 8) < 8) {
return ERROR_IO;
}
uint64_t chunk_size = ntohl(hdr[0]);
int32_t chunk_type = ntohl(hdr[1]);
off64_t data_offset = *offset + 8;
if (chunk_size == 1) {
if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) {
return ERROR_IO;
}
chunk_size = ntoh64(chunk_size);
data_offset += 8;
if (chunk_size < 16) {
return ERROR_MALFORMED;
}
} else if (chunk_size == 0) {
if (depth == 0) {
off64_t sourceSize;
if (mDataSource->getSize(&sourceSize) == OK) {
chunk_size = (sourceSize - *offset);
} else {
ALOGE("atom size is 0, and data source has no size");
return ERROR_MALFORMED;
}
} else {
*offset += 4;
return OK;
}
} else if (chunk_size < 8) {
ALOGE("invalid chunk size: %" PRIu64, chunk_size);
return ERROR_MALFORMED;
}
char chunk[5];
MakeFourCCString(chunk_type, chunk);
ALOGV("chunk: %s @ %lld, %d", chunk, (long long)*offset, depth);
if (kUseHexDump) {
static const char kWhitespace[] = " ";
const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth];
printf("%sfound chunk '%s' of size %" PRIu64 "\n", indent, chunk, chunk_size);
char buffer[256];
size_t n = chunk_size;
if (n > sizeof(buffer)) {
n = sizeof(buffer);
}
if (mDataSource->readAt(*offset, buffer, n)
< (ssize_t)n) {
return ERROR_IO;
}
hexdump(buffer, n);
}
PathAdder autoAdder(&mPath, chunk_type);
off64_t chunk_data_size = *offset + chunk_size - data_offset;
if (chunk_type != FOURCC('c', 'p', 'r', 't')
&& chunk_type != FOURCC('c', 'o', 'v', 'r')
&& mPath.size() == 5 && underMetaDataPath(mPath)) {
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
return OK;
}
switch(chunk_type) {
case FOURCC('m', 'o', 'o', 'v'):
case FOURCC('t', 'r', 'a', 'k'):
case FOURCC('m', 'd', 'i', 'a'):
case FOURCC('m', 'i', 'n', 'f'):
case FOURCC('d', 'i', 'n', 'f'):
case FOURCC('s', 't', 'b', 'l'):
case FOURCC('m', 'v', 'e', 'x'):
case FOURCC('m', 'o', 'o', 'f'):
case FOURCC('t', 'r', 'a', 'f'):
case FOURCC('m', 'f', 'r', 'a'):
case FOURCC('u', 'd', 't', 'a'):
case FOURCC('i', 'l', 's', 't'):
case FOURCC('s', 'i', 'n', 'f'):
case FOURCC('s', 'c', 'h', 'i'):
case FOURCC('e', 'd', 't', 's'):
{
if (chunk_type == FOURCC('m', 'o', 'o', 'f') && !mMoofFound) {
mMoofFound = true;
mMoofOffset = *offset;
}
if (chunk_type == FOURCC('s', 't', 'b', 'l')) {
ALOGV("sampleTable chunk is %" PRIu64 " bytes long.", chunk_size);
if (mDataSource->flags()
& (DataSource::kWantsPrefetching
| DataSource::kIsCachingDataSource)) {
sp<MPEG4DataSource> cachedSource =
new MPEG4DataSource(mDataSource);
if (cachedSource->setCachedRange(*offset, chunk_size) == OK) {
mDataSource = cachedSource;
}
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->sampleTable = new SampleTable(mDataSource);
}
bool isTrack = false;
if (chunk_type == FOURCC('t', 'r', 'a', 'k')) {
isTrack = true;
Track *track = new Track;
track->next = NULL;
if (mLastTrack) {
mLastTrack->next = track;
} else {
mFirstTrack = track;
}
mLastTrack = track;
track->meta = new MetaData;
track->includes_expensive_metadata = false;
track->skipTrack = false;
track->timescale = 0;
track->meta->setCString(kKeyMIMEType, "application/octet-stream");
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
if (isTrack) {
if (mLastTrack->skipTrack) {
Track *cur = mFirstTrack;
if (cur == mLastTrack) {
delete cur;
mFirstTrack = mLastTrack = NULL;
} else {
while (cur && cur->next != mLastTrack) {
cur = cur->next;
}
cur->next = NULL;
delete mLastTrack;
mLastTrack = cur;
}
return OK;
}
status_t err = verifyTrack(mLastTrack);
if (err != OK) {
return err;
}
} else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) {
mInitCheck = OK;
if (!mIsDrm) {
return UNKNOWN_ERROR; // Return a dummy error.
} else {
return OK;
}
}
break;
}
case FOURCC('e', 'l', 's', 't'):
{
*offset += chunk_size;
uint8_t version;
if (mDataSource->readAt(data_offset, &version, 1) < 1) {
return ERROR_IO;
}
uint32_t entry_count;
if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) {
return ERROR_IO;
}
if (entry_count != 1) {
ALOGW("ignoring edit list with %d entries", entry_count);
} else if (mHeaderTimescale == 0) {
ALOGW("ignoring edit list because timescale is 0");
} else {
off64_t entriesoffset = data_offset + 8;
uint64_t segment_duration;
int64_t media_time;
if (version == 1) {
if (!mDataSource->getUInt64(entriesoffset, &segment_duration) ||
!mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) {
return ERROR_IO;
}
} else if (version == 0) {
uint32_t sd;
int32_t mt;
if (!mDataSource->getUInt32(entriesoffset, &sd) ||
!mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) {
return ERROR_IO;
}
segment_duration = sd;
media_time = mt;
} else {
return ERROR_IO;
}
uint64_t halfscale = mHeaderTimescale / 2;
segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
int64_t duration;
int32_t samplerate;
if (!mLastTrack) {
return ERROR_MALFORMED;
}
if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
int64_t delay = (media_time * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
int64_t paddingus = duration - (segment_duration + media_time);
if (paddingus < 0) {
paddingus = 0;
}
int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
}
}
break;
}
case FOURCC('f', 'r', 'm', 'a'):
{
*offset += chunk_size;
uint32_t original_fourcc;
if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) {
return ERROR_IO;
}
original_fourcc = ntohl(original_fourcc);
ALOGV("read original format: %d", original_fourcc);
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc));
uint32_t num_channels = 0;
uint32_t sample_rate = 0;
if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) {
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
}
break;
}
case FOURCC('t', 'e', 'n', 'c'):
{
*offset += chunk_size;
if (chunk_size < 32) {
return ERROR_MALFORMED;
}
char buf[4];
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) {
return ERROR_IO;
}
uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf));
if (defaultAlgorithmId > 1) {
return ERROR_MALFORMED;
}
memset(buf, 0, 4);
if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) {
return ERROR_IO;
}
uint32_t defaultIVSize = ntohl(*((int32_t*)buf));
if ((defaultAlgorithmId == 0 && defaultIVSize != 0) ||
(defaultAlgorithmId != 0 && defaultIVSize == 0)) {
return ERROR_MALFORMED;
} else if (defaultIVSize != 0 &&
defaultIVSize != 8 &&
defaultIVSize != 16) {
return ERROR_MALFORMED;
}
uint8_t defaultKeyId[16];
if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId);
mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize);
mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16);
break;
}
case FOURCC('t', 'k', 'h', 'd'):
{
*offset += chunk_size;
status_t err;
if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) {
return err;
}
break;
}
case FOURCC('p', 's', 's', 'h'):
{
*offset += chunk_size;
PsshInfo pssh;
if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) {
return ERROR_IO;
}
uint32_t psshdatalen = 0;
if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) {
return ERROR_IO;
}
pssh.datalen = ntohl(psshdatalen);
ALOGV("pssh data size: %d", pssh.datalen);
if (chunk_size < 20 || pssh.datalen > chunk_size - 20) {
return ERROR_MALFORMED;
}
pssh.data = new (std::nothrow) uint8_t[pssh.datalen];
if (pssh.data == NULL) {
return ERROR_MALFORMED;
}
ALOGV("allocated pssh @ %p", pssh.data);
ssize_t requested = (ssize_t) pssh.datalen;
if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) {
return ERROR_IO;
}
mPssh.push_back(pssh);
break;
}
case FOURCC('m', 'd', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 4 || mLastTrack == NULL) {
return ERROR_MALFORMED;
}
uint8_t version;
if (mDataSource->readAt(
data_offset, &version, sizeof(version))
< (ssize_t)sizeof(version)) {
return ERROR_IO;
}
off64_t timescale_offset;
if (version == 1) {
timescale_offset = data_offset + 4 + 16;
} else if (version == 0) {
timescale_offset = data_offset + 4 + 8;
} else {
return ERROR_IO;
}
uint32_t timescale;
if (mDataSource->readAt(
timescale_offset, ×cale, sizeof(timescale))
< (ssize_t)sizeof(timescale)) {
return ERROR_IO;
}
if (!timescale) {
ALOGE("timescale should not be ZERO.");
return ERROR_MALFORMED;
}
mLastTrack->timescale = ntohl(timescale);
int64_t duration = 0;
if (version == 1) {
if (mDataSource->readAt(
timescale_offset + 4, &duration, sizeof(duration))
< (ssize_t)sizeof(duration)) {
return ERROR_IO;
}
if (duration != -1) {
duration = ntoh64(duration);
}
} else {
uint32_t duration32;
if (mDataSource->readAt(
timescale_offset + 4, &duration32, sizeof(duration32))
< (ssize_t)sizeof(duration32)) {
return ERROR_IO;
}
if (duration32 != 0xffffffff) {
duration = ntohl(duration32);
}
}
if (duration != 0 && mLastTrack->timescale != 0) {
mLastTrack->meta->setInt64(
kKeyDuration, (duration * 1000000) / mLastTrack->timescale);
}
uint8_t lang[2];
off64_t lang_offset;
if (version == 1) {
lang_offset = timescale_offset + 4 + 8;
} else if (version == 0) {
lang_offset = timescale_offset + 4 + 4;
} else {
return ERROR_IO;
}
if (mDataSource->readAt(lang_offset, &lang, sizeof(lang))
< (ssize_t)sizeof(lang)) {
return ERROR_IO;
}
char lang_code[4];
lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60;
lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60;
lang_code[2] = (lang[1] & 0x1f) + 0x60;
lang_code[3] = '\0';
mLastTrack->meta->setCString(
kKeyMediaLanguage, lang_code);
break;
}
case FOURCC('s', 't', 's', 'd'):
{
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t buffer[8];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 8) < 8) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
uint32_t entry_count = U32_AT(&buffer[4]);
if (entry_count > 1) {
const char *mime;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) &&
strcasecmp(mime, "application/octet-stream")) {
mLastTrack->skipTrack = true;
*offset += chunk_size;
break;
}
}
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + 8;
for (uint32_t i = 0; i < entry_count; ++i) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'a'):
case FOURCC('e', 'n', 'c', 'a'):
case FOURCC('s', 'a', 'm', 'r'):
case FOURCC('s', 'a', 'w', 'b'):
{
uint8_t buffer[8 + 20];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint32_t num_channels = U16_AT(&buffer[16]);
uint16_t sample_size = U16_AT(&buffer[18]);
uint32_t sample_rate = U32_AT(&buffer[24]) >> 16;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'a')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate);
}
ALOGV("*** coding='%s' %d channels, size %d, rate %d\n",
chunk, num_channels, sample_size, sample_rate);
mLastTrack->meta->setInt32(kKeyChannelCount, num_channels);
mLastTrack->meta->setInt32(kKeySampleRate, sample_rate);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'p', '4', 'v'):
case FOURCC('e', 'n', 'c', 'v'):
case FOURCC('s', '2', '6', '3'):
case FOURCC('H', '2', '6', '3'):
case FOURCC('h', '2', '6', '3'):
case FOURCC('a', 'v', 'c', '1'):
case FOURCC('h', 'v', 'c', '1'):
case FOURCC('h', 'e', 'v', '1'):
{
mHasVideo = true;
uint8_t buffer[78];
if (chunk_data_size < (ssize_t)sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) {
return ERROR_IO;
}
uint16_t data_ref_index __unused = U16_AT(&buffer[6]);
uint16_t width = U16_AT(&buffer[6 + 18]);
uint16_t height = U16_AT(&buffer[6 + 20]);
if (width == 0) width = 352;
if (height == 0) height = 288;
if (mLastTrack == NULL)
return ERROR_MALFORMED;
if (chunk_type != FOURCC('e', 'n', 'c', 'v')) {
mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type));
}
mLastTrack->meta->setInt32(kKeyWidth, width);
mLastTrack->meta->setInt32(kKeyHeight, height);
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset + sizeof(buffer);
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('s', 't', 'c', 'o'):
case FOURCC('c', 'o', '6', '4'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setChunkOffsetParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'c'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleToChunkParams(
data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 'z'):
case FOURCC('s', 't', 'z', '2'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
status_t err =
mLastTrack->sampleTable->setSampleSizeParams(
chunk_type, data_offset, chunk_data_size);
*offset += chunk_size;
if (err != OK) {
return err;
}
size_t max_size;
err = mLastTrack->sampleTable->getMaxSampleSize(&max_size);
if (err != OK) {
return err;
}
if (max_size != 0) {
if (max_size > SIZE_MAX - 10 * 2) {
ALOGE("max sample size too big: %zu", max_size);
return ERROR_MALFORMED;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2);
} else {
uint32_t width, height;
if (!mLastTrack->meta->findInt32(kKeyWidth, (int32_t*)&width) ||
!mLastTrack->meta->findInt32(kKeyHeight,(int32_t*) &height)) {
ALOGE("No width or height, assuming worst case 1080p");
width = 1920;
height = 1080;
} else {
if (width > 32768 || height > 32768) {
ALOGE("can't support %u x %u video", width, height);
return ERROR_MALFORMED;
}
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192;
} else {
max_size = width * height * 3 / 2;
}
mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size);
}
const char *mime;
CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp("video/", mime, 6)) {
size_t nSamples = mLastTrack->sampleTable->countSamples();
int64_t durationUs;
if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > 0) {
int32_t frameRate = (nSamples * 1000000LL +
(durationUs >> 1)) / durationUs;
mLastTrack->meta->setInt32(kKeyFrameRate, frameRate);
}
}
}
break;
}
case FOURCC('s', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('c', 't', 't', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setCompositionTimeToSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC('s', 't', 's', 's'):
{
if ((mLastTrack == NULL) || (mLastTrack->sampleTable == NULL))
return ERROR_MALFORMED;
*offset += chunk_size;
status_t err =
mLastTrack->sampleTable->setSyncSampleParams(
data_offset, chunk_data_size);
if (err != OK) {
return err;
}
break;
}
case FOURCC(0xA9, 'x', 'y', 'z'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
char buffer[18];
off64_t location_length = chunk_data_size - 5;
if (location_length >= (off64_t) sizeof(buffer)) {
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset + 4, buffer, location_length) < location_length) {
return ERROR_IO;
}
buffer[location_length] = '\0';
mFileMetaData->setCString(kKeyLocation, buffer);
break;
}
case FOURCC('e', 's', 'd', 's'):
{
*offset += chunk_size;
if (chunk_data_size < 4) {
return ERROR_MALFORMED;
}
uint8_t buffer[256];
if (chunk_data_size > (off64_t)sizeof(buffer)) {
return ERROR_BUFFER_TOO_SMALL;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
return ERROR_MALFORMED;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4);
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) {
status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio(
&buffer[4], chunk_data_size - 4);
if (err != OK) {
return err;
}
}
if (mPath.size() >= 2
&& mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'v')) {
ESDS esds(&buffer[4], chunk_data_size - 4);
uint8_t objectTypeIndication;
if (esds.getObjectTypeIndication(&objectTypeIndication) == OK) {
if (objectTypeIndication >= 0x60 && objectTypeIndication <= 0x65) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG2);
}
}
}
break;
}
case FOURCC('a', 'v', 'c', 'C'):
{
*offset += chunk_size;
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size);
break;
}
case FOURCC('h', 'v', 'c', 'C'):
{
sp<ABuffer> buffer = new ABuffer(chunk_data_size);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(
kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size);
*offset += chunk_size;
break;
}
case FOURCC('d', '2', '6', '3'):
{
*offset += chunk_size;
/*
* d263 contains a fixed 7 bytes part:
* vendor - 4 bytes
* version - 1 byte
* level - 1 byte
* profile - 1 byte
* optionally, "d263" box itself may contain a 16-byte
* bit rate box (bitr)
* average bit rate - 4 bytes
* max bit rate - 4 bytes
*/
char buffer[23];
if (chunk_data_size != 7 &&
chunk_data_size != 23) {
ALOGE("Incorrect D263 box size %lld", (long long)chunk_data_size);
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, chunk_data_size) < chunk_data_size) {
return ERROR_IO;
}
if (mLastTrack == NULL)
return ERROR_MALFORMED;
mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size);
break;
}
case FOURCC('m', 'e', 't', 'a'):
{
off64_t stop_offset = *offset + chunk_size;
*offset = data_offset;
bool isParsingMetaKeys = underQTMetaPath(mPath, 2);
if (!isParsingMetaKeys) {
uint8_t buffer[4];
if (chunk_data_size < (off64_t)sizeof(buffer)) {
*offset = stop_offset;
return ERROR_MALFORMED;
}
if (mDataSource->readAt(
data_offset, buffer, 4) < 4) {
*offset = stop_offset;
return ERROR_IO;
}
if (U32_AT(buffer) != 0) {
*offset = stop_offset;
return OK;
}
*offset += sizeof(buffer);
}
while (*offset < stop_offset) {
status_t err = parseChunk(offset, depth + 1);
if (err != OK) {
return err;
}
}
if (*offset != stop_offset) {
return ERROR_MALFORMED;
}
break;
}
case FOURCC('m', 'e', 'a', 'n'):
case FOURCC('n', 'a', 'm', 'e'):
case FOURCC('d', 'a', 't', 'a'):
{
*offset += chunk_size;
if (mPath.size() == 6 && underMetaDataPath(mPath)) {
status_t err = parseITunesMetaData(data_offset, chunk_data_size);
if (err != OK) {
return err;
}
}
break;
}
case FOURCC('m', 'v', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 32) {
return ERROR_MALFORMED;
}
uint8_t header[32];
if (mDataSource->readAt(
data_offset, header, sizeof(header))
< (ssize_t)sizeof(header)) {
return ERROR_IO;
}
uint64_t creationTime;
uint64_t duration = 0;
if (header[0] == 1) {
creationTime = U64_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[20]);
duration = U64_AT(&header[24]);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (header[0] != 0) {
return ERROR_MALFORMED;
} else {
creationTime = U32_AT(&header[4]);
mHeaderTimescale = U32_AT(&header[12]);
uint32_t d32 = U32_AT(&header[16]);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
String8 s;
convertTimeToDate(creationTime, &s);
mFileMetaData->setCString(kKeyDate, s.string());
break;
}
case FOURCC('m', 'e', 'h', 'd'):
{
*offset += chunk_size;
if (chunk_data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t flags[4];
if (mDataSource->readAt(
data_offset, flags, sizeof(flags))
< (ssize_t)sizeof(flags)) {
return ERROR_IO;
}
uint64_t duration = 0;
if (flags[0] == 1) {
if (chunk_data_size < 12) {
return ERROR_MALFORMED;
}
mDataSource->getUInt64(data_offset + 4, &duration);
if (duration == 0xffffffffffffffff) {
duration = 0;
}
} else if (flags[0] == 0) {
uint32_t d32;
mDataSource->getUInt32(data_offset + 4, &d32);
if (d32 == 0xffffffff) {
d32 = 0;
}
duration = d32;
} else {
return ERROR_MALFORMED;
}
if (duration != 0 && mHeaderTimescale != 0) {
mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale);
}
break;
}
case FOURCC('m', 'd', 'a', 't'):
{
ALOGV("mdat chunk, drm: %d", mIsDrm);
mMdatFound = true;
if (!mIsDrm) {
*offset += chunk_size;
break;
}
if (chunk_size < 8) {
return ERROR_MALFORMED;
}
return parseDrmSINF(offset, data_offset);
}
case FOURCC('h', 'd', 'l', 'r'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
break;
}
uint32_t buffer;
if (mDataSource->readAt(
data_offset + 8, &buffer, 4) < 4) {
return ERROR_IO;
}
uint32_t type = ntohl(buffer);
if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) {
if (mLastTrack != NULL) {
mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP);
}
}
break;
}
case FOURCC('k', 'e', 'y', 's'):
{
*offset += chunk_size;
if (underQTMetaPath(mPath, 3)) {
parseQTMetaKey(data_offset, chunk_data_size);
}
break;
}
case FOURCC('t', 'r', 'e', 'x'):
{
*offset += chunk_size;
if (chunk_data_size < 24) {
return ERROR_IO;
}
Trex trex;
if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) ||
!mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) ||
!mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) ||
!mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) ||
!mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) {
return ERROR_IO;
}
mTrex.add(trex);
break;
}
case FOURCC('t', 'x', '3', 'g'):
{
if (mLastTrack == NULL)
return ERROR_MALFORMED;
uint32_t type;
const void *data;
size_t size = 0;
if (!mLastTrack->meta->findData(
kKeyTextFormatData, &type, &data, &size)) {
size = 0;
}
if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) {
return ERROR_MALFORMED;
}
uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size];
if (buffer == NULL) {
return ERROR_MALFORMED;
}
if (size > 0) {
memcpy(buffer, data, size);
}
if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size))
< chunk_size) {
delete[] buffer;
buffer = NULL;
*offset += chunk_size;
return ERROR_IO;
}
mLastTrack->meta->setData(
kKeyTextFormatData, 0, buffer, size + chunk_size);
delete[] buffer;
*offset += chunk_size;
break;
}
case FOURCC('c', 'o', 'v', 'r'):
{
*offset += chunk_size;
if (mFileMetaData != NULL) {
ALOGV("chunk_data_size = %" PRId64 " and data_offset = %" PRId64,
chunk_data_size, data_offset);
if (chunk_data_size < 0 || static_cast<uint64_t>(chunk_data_size) >= SIZE_MAX - 1) {
return ERROR_MALFORMED;
}
sp<ABuffer> buffer = new ABuffer(chunk_data_size + 1);
if (buffer->data() == NULL) {
ALOGE("b/28471206");
return NO_MEMORY;
}
if (mDataSource->readAt(
data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) {
return ERROR_IO;
}
const int kSkipBytesOfDataBox = 16;
if (chunk_data_size <= kSkipBytesOfDataBox) {
return ERROR_MALFORMED;
}
mFileMetaData->setData(
kKeyAlbumArt, MetaData::TYPE_NONE,
buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox);
}
break;
}
case FOURCC('t', 'i', 't', 'l'):
case FOURCC('p', 'e', 'r', 'f'):
case FOURCC('a', 'u', 't', 'h'):
case FOURCC('g', 'n', 'r', 'e'):
case FOURCC('a', 'l', 'b', 'm'):
case FOURCC('y', 'r', 'r', 'c'):
{
*offset += chunk_size;
status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth);
if (err != OK) {
return err;
}
break;
}
case FOURCC('I', 'D', '3', '2'):
{
*offset += chunk_size;
if (chunk_data_size < 6) {
return ERROR_MALFORMED;
}
parseID3v2MetaData(data_offset + 6);
break;
}
case FOURCC('-', '-', '-', '-'):
{
mLastCommentMean.clear();
mLastCommentName.clear();
mLastCommentData.clear();
*offset += chunk_size;
break;
}
case FOURCC('s', 'i', 'd', 'x'):
{
parseSegmentIndex(data_offset, chunk_data_size);
*offset += chunk_size;
return UNKNOWN_ERROR; // stop parsing after sidx
}
default:
{
if (underQTMetaPath(mPath, 3)) {
parseQTMetaVal(chunk_type, data_offset, chunk_data_size);
}
*offset += chunk_size;
break;
}
}
return OK;
}
Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track.
GenericSource: return error when no track exists.
SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor.
Bug: 21657957
Bug: 23705695
Bug: 22802344
Bug: 28799341
Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04
(cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13)
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool SectionHasAutofilledField(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
Commit Message: [AF] Don't simplify/dedupe suggestions for (partially) filled sections.
Since Autofill does not fill field by field anymore, this simplifying
and deduping of suggestions is not useful anymore.
Bug: 858820
Cq-Include-Trybots: luci.chromium.try:ios-simulator-full-configs;master.tryserver.chromium.mac:ios-simulator-cronet
Change-Id: I36f7cfe425a0bdbf5ba7503a3d96773b405cc19b
Reviewed-on: https://chromium-review.googlesource.com/1128255
Reviewed-by: Roger McFarlane <[email protected]>
Commit-Queue: Sebastien Seguin-Gagnon <[email protected]>
Cr-Commit-Position: refs/heads/master@{#573315}
CWE ID:
Target: 1
Example 2:
Code: static void tg3_dump_state(struct tg3 *tp)
{
int i;
u32 *regs;
regs = kzalloc(TG3_REG_BLK_SIZE, GFP_ATOMIC);
if (!regs)
return;
if (tg3_flag(tp, PCI_EXPRESS)) {
/* Read up to but not including private PCI registers */
for (i = 0; i < TG3_PCIE_TLDLPL_PORT; i += sizeof(u32))
regs[i / sizeof(u32)] = tr32(i);
} else
tg3_dump_legacy_regs(tp, regs);
for (i = 0; i < TG3_REG_BLK_SIZE / sizeof(u32); i += 4) {
if (!regs[i + 0] && !regs[i + 1] &&
!regs[i + 2] && !regs[i + 3])
continue;
netdev_err(tp->dev, "0x%08x: 0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
i * 4,
regs[i + 0], regs[i + 1], regs[i + 2], regs[i + 3]);
}
kfree(regs);
for (i = 0; i < tp->irq_cnt; i++) {
struct tg3_napi *tnapi = &tp->napi[i];
/* SW status block */
netdev_err(tp->dev,
"%d: Host status block [%08x:%08x:(%04x:%04x:%04x):(%04x:%04x)]\n",
i,
tnapi->hw_status->status,
tnapi->hw_status->status_tag,
tnapi->hw_status->rx_jumbo_consumer,
tnapi->hw_status->rx_consumer,
tnapi->hw_status->rx_mini_consumer,
tnapi->hw_status->idx[0].rx_producer,
tnapi->hw_status->idx[0].tx_consumer);
netdev_err(tp->dev,
"%d: NAPI info [%08x:%08x:(%04x:%04x:%04x):%04x:(%04x:%04x:%04x:%04x)]\n",
i,
tnapi->last_tag, tnapi->last_irq_tag,
tnapi->tx_prod, tnapi->tx_cons, tnapi->tx_pending,
tnapi->rx_rcb_ptr,
tnapi->prodring.rx_std_prod_idx,
tnapi->prodring.rx_std_cons_idx,
tnapi->prodring.rx_jmb_prod_idx,
tnapi->prodring.rx_jmb_cons_idx);
}
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ExtensionBrowserTest::OpenWindow(content::WebContents* contents,
const GURL& url,
bool newtab_process_should_equal_opener,
content::WebContents** newtab_result) {
content::WebContentsAddedObserver tab_added_observer;
ASSERT_TRUE(content::ExecuteScript(contents,
"window.open('" + url.spec() + "');"));
content::WebContents* newtab = tab_added_observer.GetWebContents();
ASSERT_TRUE(newtab);
WaitForLoadStop(newtab);
EXPECT_EQ(url, newtab->GetLastCommittedURL());
if (newtab_process_should_equal_opener) {
EXPECT_EQ(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
} else {
EXPECT_NE(contents->GetMainFrame()->GetSiteInstance(),
newtab->GetMainFrame()->GetSiteInstance());
}
if (newtab_result)
*newtab_result = newtab;
}
Commit Message: [Extensions] Update navigations across hypothetical extension extents
Update code to treat navigations across hypothetical extension extents
(e.g. for nonexistent extensions) the same as we do for navigations
crossing installed extension extents.
Bug: 598265
Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b
Reviewed-on: https://chromium-review.googlesource.com/617180
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#495779}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CtcpHandler::defaultHandler(const QString &cmd, CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype);
Q_UNUSED(target);
if(!_ignoreListManager->ctcpMatch(prefix, network()->networkName())) {
QString str = tr("Received unknown CTCP %1 by %2").arg(cmd).arg(prefix);
if(!param.isEmpty())
str.append(tr(" with arguments: %1").arg(param));
emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", str);
}
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool Allowed(const Extension* extension, const GURL& url) {
return Allowed(extension, url, -1);
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
{
FLAC__ASSERT(0 != decoder);
FLAC__ASSERT(0 != decoder->private_);
FLAC__ASSERT(0 != decoder->protected_);
if(!FLAC__stream_decoder_flush(decoder)) {
/* above call sets the state for us */
return false;
}
#if FLAC__HAS_OGG
/*@@@ could go in !internal_reset_hack block below */
if(decoder->private_->is_ogg)
FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
#endif
/* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
* (internal_reset_hack) don't try to rewind since we are already at
* the beginning of the stream and don't want to fail if the input is
* not seekable.
*/
if(!decoder->private_->internal_reset_hack) {
if(decoder->private_->file == stdin)
return false; /* can't rewind stdin, reset fails */
if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
return false; /* seekable and seek fails, reset fails */
}
else
decoder->private_->internal_reset_hack = false;
decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
decoder->private_->has_stream_info = false;
if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
free(decoder->private_->seek_table.data.seek_table.points);
decoder->private_->seek_table.data.seek_table.points = 0;
decoder->private_->has_seek_table = false;
}
decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
/*
* This goes in reset() and not flush() because according to the spec, a
* fixed-blocksize stream must stay that way through the whole stream.
*/
decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
/* We initialize the FLAC__MD5Context even though we may never use it. This
* is because md5 checking may be turned on to start and then turned off if
* a seek occurs. So we init the context here and finalize it in
* FLAC__stream_decoder_finish() to make sure things are always cleaned up
* properly.
*/
FLAC__MD5Init(&decoder->private_->md5context);
decoder->private_->first_frame_offset = 0;
decoder->private_->unparseable_frame_count = 0;
return true;
}
Commit Message: Avoid free-before-initialize vulnerability in heap
Bug: 27211885
Change-Id: Ib9c93bd9ffdde2a5f8d31a86f06e267dc9c152db
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: ssize_t v9fs_list_xattr(FsContext *ctx, const char *path,
void *value, size_t vsize)
{
ssize_t size = 0;
void *ovalue = value;
XattrOperations *xops;
char *orig_value, *orig_value_start;
ssize_t xattr_len, parsed_len = 0, attr_len;
char *dirpath, *name;
int dirfd;
/* Get the actual len */
dirpath = g_path_get_dirname(path);
dirfd = local_opendir_nofollow(ctx, dirpath);
g_free(dirpath);
if (dirfd == -1) {
return -1;
}
name = g_path_get_basename(path);
xattr_len = flistxattrat_nofollow(dirfd, name, value, 0);
if (xattr_len <= 0) {
g_free(name);
close_preserve_errno(dirfd);
return xattr_len;
}
/* Now fetch the xattr and find the actual size */
orig_value = g_malloc(xattr_len);
xattr_len = flistxattrat_nofollow(dirfd, name, orig_value, xattr_len);
g_free(name);
close_preserve_errno(dirfd);
if (xattr_len < 0) {
return -1;
}
orig_value_start = orig_value;
while (xattr_len > parsed_len) {
xops = get_xattr_operations(ctx->xops, orig_value);
if (!xops) {
goto next_entry;
}
if (!value) {
size += xops->listxattr(ctx, path, orig_value, value, vsize);
} else {
size = xops->listxattr(ctx, path, orig_value, value, vsize);
if (size < 0) {
goto err_out;
}
value += size;
vsize -= size;
}
next_entry:
/* Got the next entry */
attr_len = strlen(orig_value) + 1;
parsed_len += attr_len;
orig_value += attr_len;
}
if (value) {
size = value - ovalue;
}
err_out:
g_free(orig_value_start);
return size;
}
Commit Message:
CWE ID: CWE-772
Target: 1
Example 2:
Code: static pdf_xref_entry *pdf_get_incremental_xref_entry(fz_context *ctx, pdf_document *doc, int i)
{
pdf_xref *xref;
pdf_xref_subsec *sub;
/* Make a new final xref section if we haven't already */
ensure_incremental_xref(ctx, doc);
xref = &doc->xref_sections[doc->xref_base];
if (i >= xref->num_objects)
pdf_resize_xref(ctx, doc, i + 1);
sub = xref->subsec;
assert(sub != NULL && sub->next == NULL);
assert(i >= sub->start && i < sub->start + sub->len);
doc->xref_index[i] = 0;
return &sub->table[i - sub->start];
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: pk_copy_error(krb5_context context,
hx509_context hx509ctx,
int hxret,
const char *fmt,
...)
{
va_list va;
char *s, *f;
int ret;
va_start(va, fmt);
ret = vasprintf(&f, fmt, va);
va_end(va);
if (ret == -1 || f == NULL) {
krb5_clear_error_message(context);
return;
}
s = hx509_get_error_string(hx509ctx, hxret);
if (s == NULL) {
krb5_clear_error_message(context);
free(f);
return;
}
krb5_set_error_message(context, hxret, "%s: %s", f, s);
free(s);
free(f);
}
Commit Message: CVE-2019-12098: krb5: always confirm PA-PKINIT-KX for anon PKINIT
RFC8062 Section 7 requires verification of the PA-PKINIT-KX key excahnge
when anonymous PKINIT is used. Failure to do so can permit an active
attacker to become a man-in-the-middle.
Introduced by a1ef548600c5bb51cf52a9a9ea12676506ede19f. First tagged
release Heimdal 1.4.0.
CVSS:3.0/AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:L/A:N (4.8)
Change-Id: I6cc1c0c24985936468af08693839ac6c3edda133
Signed-off-by: Jeffrey Altman <[email protected]>
Approved-by: Jeffrey Altman <[email protected]>
(cherry picked from commit 38c797e1ae9b9c8f99ae4aa2e73957679031fd2b)
CWE ID: CWE-320
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const BlockEntry* Track::GetEOS() const
{
return &m_eos;
}
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
Target: 1
Example 2:
Code: struct rtable *ip_route_output_key_hash_rcu(struct net *net, struct flowi4 *fl4,
struct fib_result *res,
const struct sk_buff *skb)
{
struct net_device *dev_out = NULL;
int orig_oif = fl4->flowi4_oif;
unsigned int flags = 0;
struct rtable *rth;
int err = -ENETUNREACH;
if (fl4->saddr) {
rth = ERR_PTR(-EINVAL);
if (ipv4_is_multicast(fl4->saddr) ||
ipv4_is_lbcast(fl4->saddr) ||
ipv4_is_zeronet(fl4->saddr))
goto out;
/* I removed check for oif == dev_out->oif here.
It was wrong for two reasons:
1. ip_dev_find(net, saddr) can return wrong iface, if saddr
is assigned to multiple interfaces.
2. Moreover, we are allowed to send packets with saddr
of another iface. --ANK
*/
if (fl4->flowi4_oif == 0 &&
(ipv4_is_multicast(fl4->daddr) ||
ipv4_is_lbcast(fl4->daddr))) {
/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
dev_out = __ip_dev_find(net, fl4->saddr, false);
if (!dev_out)
goto out;
/* Special hack: user can direct multicasts
and limited broadcast via necessary interface
without fiddling with IP_MULTICAST_IF or IP_PKTINFO.
This hack is not just for fun, it allows
vic,vat and friends to work.
They bind socket to loopback, set ttl to zero
and expect that it will work.
From the viewpoint of routing cache they are broken,
because we are not allowed to build multicast path
with loopback source addr (look, routing cache
cannot know, that ttl is zero, so that packet
will not leave this host and route is valid).
Luckily, this hack is good workaround.
*/
fl4->flowi4_oif = dev_out->ifindex;
goto make_route;
}
if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) {
/* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */
if (!__ip_dev_find(net, fl4->saddr, false))
goto out;
}
}
if (fl4->flowi4_oif) {
dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif);
rth = ERR_PTR(-ENODEV);
if (!dev_out)
goto out;
/* RACE: Check return value of inet_select_addr instead. */
if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) {
rth = ERR_PTR(-ENETUNREACH);
goto out;
}
if (ipv4_is_local_multicast(fl4->daddr) ||
ipv4_is_lbcast(fl4->daddr) ||
fl4->flowi4_proto == IPPROTO_IGMP) {
if (!fl4->saddr)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_LINK);
goto make_route;
}
if (!fl4->saddr) {
if (ipv4_is_multicast(fl4->daddr))
fl4->saddr = inet_select_addr(dev_out, 0,
fl4->flowi4_scope);
else if (!fl4->daddr)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_HOST);
}
}
if (!fl4->daddr) {
fl4->daddr = fl4->saddr;
if (!fl4->daddr)
fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK);
dev_out = net->loopback_dev;
fl4->flowi4_oif = LOOPBACK_IFINDEX;
res->type = RTN_LOCAL;
flags |= RTCF_LOCAL;
goto make_route;
}
err = fib_lookup(net, fl4, res, 0);
if (err) {
res->fi = NULL;
res->table = NULL;
if (fl4->flowi4_oif &&
(ipv4_is_multicast(fl4->daddr) ||
!netif_index_is_l3_master(net, fl4->flowi4_oif))) {
/* Apparently, routing tables are wrong. Assume,
that the destination is on link.
WHY? DW.
Because we are allowed to send to iface
even if it has NO routes and NO assigned
addresses. When oif is specified, routing
tables are looked up with only one purpose:
to catch if destination is gatewayed, rather than
direct. Moreover, if MSG_DONTROUTE is set,
we send packet, ignoring both routing tables
and ifaddr state. --ANK
We could make it even if oif is unknown,
likely IPv6, but we do not.
*/
if (fl4->saddr == 0)
fl4->saddr = inet_select_addr(dev_out, 0,
RT_SCOPE_LINK);
res->type = RTN_UNICAST;
goto make_route;
}
rth = ERR_PTR(err);
goto out;
}
if (res->type == RTN_LOCAL) {
if (!fl4->saddr) {
if (res->fi->fib_prefsrc)
fl4->saddr = res->fi->fib_prefsrc;
else
fl4->saddr = fl4->daddr;
}
/* L3 master device is the loopback for that domain */
dev_out = l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) ? :
net->loopback_dev;
/* make sure orig_oif points to fib result device even
* though packet rx/tx happens over loopback or l3mdev
*/
orig_oif = FIB_RES_OIF(*res);
fl4->flowi4_oif = dev_out->ifindex;
flags |= RTCF_LOCAL;
goto make_route;
}
fib_select_path(net, res, fl4, skb);
dev_out = FIB_RES_DEV(*res);
fl4->flowi4_oif = dev_out->ifindex;
make_route:
rth = __mkroute_output(res, fl4, orig_oif, dev_out, flags);
out:
return rth;
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg)
IPC_MESSAGE_HANDLER(GpuChannelMsg_Initialize, OnInitialize)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_CreateOffscreenCommandBuffer,
OnCreateOffscreenCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_DestroyCommandBuffer,
OnDestroyCommandBuffer)
IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuChannelMsg_WillGpuSwitchOccur,
OnWillGpuSwitchOccur)
IPC_MESSAGE_HANDLER(GpuChannelMsg_CloseChannel, OnCloseChannel)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled) << msg.type();
return handled;
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
{
AVFilterContext *ctx = inlink->dst;
FPSContext *s = ctx->priv;
AVFilterLink *outlink = ctx->outputs[0];
int64_t delta;
int i, ret;
s->frames_in++;
/* discard frames until we get the first timestamp */
if (s->pts == AV_NOPTS_VALUE) {
if (buf->pts != AV_NOPTS_VALUE) {
ret = write_to_fifo(s->fifo, buf);
if (ret < 0)
return ret;
if (s->start_time != DBL_MAX && s->start_time != AV_NOPTS_VALUE) {
double first_pts = s->start_time * AV_TIME_BASE;
first_pts = FFMIN(FFMAX(first_pts, INT64_MIN), INT64_MAX);
s->first_pts = s->pts = av_rescale_q(first_pts, AV_TIME_BASE_Q,
inlink->time_base);
av_log(ctx, AV_LOG_VERBOSE, "Set first pts to (in:%"PRId64" out:%"PRId64")\n",
s->first_pts, av_rescale_q(first_pts, AV_TIME_BASE_Q,
outlink->time_base));
} else {
s->first_pts = s->pts = buf->pts;
}
} else {
av_log(ctx, AV_LOG_WARNING, "Discarding initial frame(s) with no "
"timestamp.\n");
av_frame_free(&buf);
s->drop++;
}
return 0;
}
/* now wait for the next timestamp */
if (buf->pts == AV_NOPTS_VALUE) {
return write_to_fifo(s->fifo, buf);
}
/* number of output frames */
delta = av_rescale_q_rnd(buf->pts - s->pts, inlink->time_base,
outlink->time_base, s->rounding);
if (delta < 1) {
/* drop the frame and everything buffered except the first */
AVFrame *tmp;
int drop = av_fifo_size(s->fifo)/sizeof(AVFrame*);
av_log(ctx, AV_LOG_DEBUG, "Dropping %d frame(s).\n", drop);
s->drop += drop;
av_fifo_generic_read(s->fifo, &tmp, sizeof(tmp), NULL);
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, tmp);
av_frame_free(&buf);
return ret;
}
/* can output >= 1 frames */
for (i = 0; i < delta; i++) {
AVFrame *buf_out;
av_fifo_generic_read(s->fifo, &buf_out, sizeof(buf_out), NULL);
/* duplicate the frame if needed */
if (!av_fifo_size(s->fifo) && i < delta - 1) {
AVFrame *dup = av_frame_clone(buf_out);
av_log(ctx, AV_LOG_DEBUG, "Duplicating frame.\n");
if (dup)
ret = write_to_fifo(s->fifo, dup);
else
ret = AVERROR(ENOMEM);
if (ret < 0) {
av_frame_free(&buf_out);
av_frame_free(&buf);
return ret;
}
s->dup++;
}
buf_out->pts = av_rescale_q(s->first_pts, inlink->time_base,
outlink->time_base) + s->frames_out;
if ((ret = ff_filter_frame(outlink, buf_out)) < 0) {
av_frame_free(&buf);
return ret;
}
s->frames_out++;
}
flush_fifo(s->fifo);
ret = write_to_fifo(s->fifo, buf);
s->pts = s->first_pts + av_rescale_q(s->frames_out, outlink->time_base, inlink->time_base);
return ret;
}
Commit Message: avfilter/vf_fps: make sure the fifo is not empty before using it
Fixes Ticket2905
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static void ping_set_saddr(struct sock *sk, struct sockaddr *saddr)
{
if (saddr->sa_family == AF_INET) {
struct inet_sock *isk = inet_sk(sk);
struct sockaddr_in *addr = (struct sockaddr_in *) saddr;
isk->inet_rcv_saddr = isk->inet_saddr = addr->sin_addr.s_addr;
#if IS_ENABLED(CONFIG_IPV6)
} else if (saddr->sa_family == AF_INET6) {
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) saddr;
struct ipv6_pinfo *np = inet6_sk(sk);
sk->sk_v6_rcv_saddr = np->saddr = addr->sin6_addr;
#endif
}
}
Commit Message: ping: prevent NULL pointer dereference on write to msg_name
A plain read() on a socket does set msg->msg_name to NULL. So check for
NULL pointer first.
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct extent_tree *__grab_extent_tree(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct extent_tree *et;
nid_t ino = inode->i_ino;
mutex_lock(&sbi->extent_tree_lock);
et = radix_tree_lookup(&sbi->extent_tree_root, ino);
if (!et) {
et = f2fs_kmem_cache_alloc(extent_tree_slab, GFP_NOFS);
f2fs_radix_tree_insert(&sbi->extent_tree_root, ino, et);
memset(et, 0, sizeof(struct extent_tree));
et->ino = ino;
et->root = RB_ROOT;
et->cached_en = NULL;
rwlock_init(&et->lock);
INIT_LIST_HEAD(&et->list);
atomic_set(&et->node_cnt, 0);
atomic_inc(&sbi->total_ext_tree);
} else {
atomic_dec(&sbi->total_zombie_tree);
list_del_init(&et->list);
}
mutex_unlock(&sbi->extent_tree_lock);
/* never died until evict_inode */
F2FS_I(inode)->extent_tree = et;
return et;
}
Commit Message: f2fs: fix a bug caused by NULL extent tree
Thread A: Thread B:
-f2fs_remount
-sbi->mount_opt.opt = 0;
<--- -f2fs_iget
-do_read_inode
-f2fs_init_extent_tree
-F2FS_I(inode)->extent_tree is NULL
-default_options && parse_options
-remount return
<--- -f2fs_map_blocks
-f2fs_lookup_extent_tree
-f2fs_bug_on(sbi, !et);
The same problem with f2fs_new_inode.
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: cib_recv_tls(gnutls_session * session)
{
char *buf = NULL;
int rc = 0;
int len = 0;
int chunk_size = 1024;
if (session == NULL) {
return NULL;
}
buf = calloc(1, chunk_size);
while (TRUE) {
errno = 0;
rc = gnutls_record_recv(*session, buf + len, chunk_size);
crm_trace("Got %d more bytes. errno=%d", rc, errno);
if (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN) {
crm_trace("Retry");
} else if (rc == GNUTLS_E_UNEXPECTED_PACKET_LENGTH) {
crm_trace("Session disconnected");
goto bail;
} else if (rc < 0) {
crm_err("Error receiving message: %s (%d)", gnutls_strerror(rc), rc);
goto bail;
} else if (rc == chunk_size) {
len += rc;
chunk_size *= 2;
buf = realloc(buf, len + chunk_size);
crm_trace("Retry with %d more bytes", (int)chunk_size);
CRM_ASSERT(buf != NULL);
} else if (buf[len + rc - 1] != 0) {
crm_trace("Last char is %d '%c'", buf[len + rc - 1], buf[len + rc - 1]);
crm_trace("Retry with %d more bytes", (int)chunk_size);
len += rc;
buf = realloc(buf, len + chunk_size);
CRM_ASSERT(buf != NULL);
} else {
crm_trace("Got %d more bytes", (int)rc);
return buf;
}
}
bail:
free(buf);
return NULL;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399
Target: 1
Example 2:
Code: void mbedtls_ecp_point_free( mbedtls_ecp_point *pt )
{
if( pt == NULL )
return;
mbedtls_mpi_free( &( pt->X ) );
mbedtls_mpi_free( &( pt->Y ) );
mbedtls_mpi_free( &( pt->Z ) );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: horizontalDifference8(unsigned char *ip, int n, int stride,
unsigned short *wp, uint16 *From8)
{
register int r1, g1, b1, a1, r2, g2, b2, a2, mask;
#undef CLAMP
#define CLAMP(v) (From8[(v)])
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
r1 = CLAMP(ip[3]); wp[3] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[4]); wp[4] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[5]); wp[5] = (uint16)((b1-b2) & mask); b2 = b1;
wp += 3;
ip += 3;
}
} else if (stride == 4) {
r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]);
b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
r1 = CLAMP(ip[4]); wp[4] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = CLAMP(ip[5]); wp[5] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = CLAMP(ip[6]); wp[6] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = CLAMP(ip[7]); wp[7] = (uint16)((a1-a2) & mask); a2 = a1;
wp += 4;
ip += 4;
}
} else {
wp += n + stride - 1; /* point to last one */
ip += n + stride - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--)
}
}
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DOMHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
host_ = frame_host;
}
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
Target: 1
Example 2:
Code: DeliverDeviceEvents(WindowPtr pWin, InternalEvent *event, GrabPtr grab,
WindowPtr stopAt, DeviceIntPtr dev)
{
Window child = None;
int deliveries = 0;
int mask;
verify_internal_event(event);
while (pWin) {
if ((mask = EventIsDeliverable(dev, event->any.type, pWin))) {
/* XI2 events first */
if (mask & EVENT_XI2_MASK) {
deliveries =
DeliverOneEvent(event, dev, XI2, pWin, child, grab);
if (deliveries > 0)
break;
}
/* XI events */
if (mask & EVENT_XI1_MASK) {
deliveries = DeliverOneEvent(event, dev, XI, pWin, child, grab);
if (deliveries > 0)
break;
}
/* Core event */
if ((mask & EVENT_CORE_MASK) && IsMaster(dev) && dev->coreEvents) {
deliveries =
DeliverOneEvent(event, dev, CORE, pWin, child, grab);
if (deliveries > 0)
break;
}
}
if ((deliveries < 0) || (pWin == stopAt) ||
(mask & EVENT_DONT_PROPAGATE_MASK)) {
deliveries = 0;
break;
}
child = pWin->drawable.id;
pWin = pWin->parent;
}
return deliveries;
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __sync_task_rss_stat(struct task_struct *task, struct mm_struct *mm)
{
int i;
for (i = 0; i < NR_MM_COUNTERS; i++) {
if (task->rss_stat.count[i]) {
add_mm_counter(mm, i, task->rss_stat.count[i]);
task->rss_stat.count[i] = 0;
}
}
task->rss_stat.events = 0;
}
Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode
commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream.
In some cases it may happen that pmd_none_or_clear_bad() is called with
the mmap_sem hold in read mode. In those cases the huge page faults can
allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a
false positive from pmd_bad() that will not like to see a pmd
materializing as trans huge.
It's not khugepaged causing the problem, khugepaged holds the mmap_sem
in write mode (and all those sites must hold the mmap_sem in read mode
to prevent pagetables to go away from under them, during code review it
seems vm86 mode on 32bit kernels requires that too unless it's
restricted to 1 thread per process or UP builds). The race is only with
the huge pagefaults that can convert a pmd_none() into a
pmd_trans_huge().
Effectively all these pmd_none_or_clear_bad() sites running with
mmap_sem in read mode are somewhat speculative with the page faults, and
the result is always undefined when they run simultaneously. This is
probably why it wasn't common to run into this. For example if the
madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page
fault, the hugepage will not be zapped, if the page fault runs first it
will be zapped.
Altering pmd_bad() not to error out if it finds hugepmds won't be enough
to fix this, because zap_pmd_range would then proceed to call
zap_pte_range (which would be incorrect if the pmd become a
pmd_trans_huge()).
The simplest way to fix this is to read the pmd in the local stack
(regardless of what we read, no need of actual CPU barriers, only
compiler barrier needed), and be sure it is not changing under the code
that computes its value. Even if the real pmd is changing under the
value we hold on the stack, we don't care. If we actually end up in
zap_pte_range it means the pmd was not none already and it was not huge,
and it can't become huge from under us (khugepaged locking explained
above).
All we need is to enforce that there is no way anymore that in a code
path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad
can run into a hugepmd. The overhead of a barrier() is just a compiler
tweak and should not be measurable (I only added it for THP builds). I
don't exclude different compiler versions may have prevented the race
too by caching the value of *pmd on the stack (that hasn't been
verified, but it wouldn't be impossible considering
pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines
and there's no external function called in between pmd_trans_huge and
pmd_none_or_clear_bad).
if (pmd_trans_huge(*pmd)) {
if (next-addr != HPAGE_PMD_SIZE) {
VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem));
split_huge_page_pmd(vma->vm_mm, pmd);
} else if (zap_huge_pmd(tlb, vma, pmd, addr))
continue;
/* fall through */
}
if (pmd_none_or_clear_bad(pmd))
Because this race condition could be exercised without special
privileges this was reported in CVE-2012-1179.
The race was identified and fully explained by Ulrich who debugged it.
I'm quoting his accurate explanation below, for reference.
====== start quote =======
mapcount 0 page_mapcount 1
kernel BUG at mm/huge_memory.c:1384!
At some point prior to the panic, a "bad pmd ..." message similar to the
following is logged on the console:
mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7).
The "bad pmd ..." message is logged by pmd_clear_bad() before it clears
the page's PMD table entry.
143 void pmd_clear_bad(pmd_t *pmd)
144 {
-> 145 pmd_ERROR(*pmd);
146 pmd_clear(pmd);
147 }
After the PMD table entry has been cleared, there is an inconsistency
between the actual number of PMD table entries that are mapping the page
and the page's map count (_mapcount field in struct page). When the page
is subsequently reclaimed, __split_huge_page() detects this inconsistency.
1381 if (mapcount != page_mapcount(page))
1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n",
1383 mapcount, page_mapcount(page));
-> 1384 BUG_ON(mapcount != page_mapcount(page));
The root cause of the problem is a race of two threads in a multithreaded
process. Thread B incurs a page fault on a virtual address that has never
been accessed (PMD entry is zero) while Thread A is executing an madvise()
system call on a virtual address within the same 2 MB (huge page) range.
virtual address space
.---------------------.
| |
| |
.-|---------------------|
| | |
| | |<-- B(fault)
| | |
2 MB | |/////////////////////|-.
huge < |/////////////////////| > A(range)
page | |/////////////////////|-'
| | |
| | |
'-|---------------------|
| |
| |
'---------------------'
- Thread A is executing an madvise(..., MADV_DONTNEED) system call
on the virtual address range "A(range)" shown in the picture.
sys_madvise
// Acquire the semaphore in shared mode.
down_read(¤t->mm->mmap_sem)
...
madvise_vma
switch (behavior)
case MADV_DONTNEED:
madvise_dontneed
zap_page_range
unmap_vmas
unmap_page_range
zap_pud_range
zap_pmd_range
//
// Assume that this huge page has never been accessed.
// I.e. content of the PMD entry is zero (not mapped).
//
if (pmd_trans_huge(*pmd)) {
// We don't get here due to the above assumption.
}
//
// Assume that Thread B incurred a page fault and
.---------> // sneaks in here as shown below.
| //
| if (pmd_none_or_clear_bad(pmd))
| {
| if (unlikely(pmd_bad(*pmd)))
| pmd_clear_bad
| {
| pmd_ERROR
| // Log "bad pmd ..." message here.
| pmd_clear
| // Clear the page's PMD entry.
| // Thread B incremented the map count
| // in page_add_new_anon_rmap(), but
| // now the page is no longer mapped
| // by a PMD entry (-> inconsistency).
| }
| }
|
v
- Thread B is handling a page fault on virtual address "B(fault)" shown
in the picture.
...
do_page_fault
__do_page_fault
// Acquire the semaphore in shared mode.
down_read_trylock(&mm->mmap_sem)
...
handle_mm_fault
if (pmd_none(*pmd) && transparent_hugepage_enabled(vma))
// We get here due to the above assumption (PMD entry is zero).
do_huge_pmd_anonymous_page
alloc_hugepage_vma
// Allocate a new transparent huge page here.
...
__do_huge_pmd_anonymous_page
...
spin_lock(&mm->page_table_lock)
...
page_add_new_anon_rmap
// Here we increment the page's map count (starts at -1).
atomic_set(&page->_mapcount, 0)
set_pmd_at
// Here we set the page's PMD entry which will be cleared
// when Thread A calls pmd_clear_bad().
...
spin_unlock(&mm->page_table_lock)
The mmap_sem does not prevent the race because both threads are acquiring
it in shared mode (down_read). Thread B holds the page_table_lock while
the page's map count and PMD table entry are updated. However, Thread A
does not synchronize on that lock.
====== end quote =======
[[email protected]: checkpatch fixes]
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: Andrea Arcangeli <[email protected]>
Acked-by: Johannes Weiner <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Dave Jones <[email protected]>
Acked-by: Larry Woodman <[email protected]>
Acked-by: Rik van Riel <[email protected]>
Cc: Mark Salter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int translate_desc(struct vhost_dev *dev, u64 addr, u32 len,
struct iovec iov[], int iov_size)
{
const struct vhost_memory_region *reg;
struct vhost_memory *mem;
struct iovec *_iov;
u64 s = 0;
int ret = 0;
rcu_read_lock();
mem = rcu_dereference(dev->memory);
while ((u64)len > s) {
u64 size;
if (unlikely(ret >= iov_size)) {
ret = -ENOBUFS;
break;
}
reg = find_region(mem, addr, len);
if (unlikely(!reg)) {
ret = -EFAULT;
break;
}
_iov = iov + ret;
size = reg->memory_size - addr + reg->guest_phys_addr;
_iov->iov_len = min((u64)len, size);
_iov->iov_base = (void __user *)(unsigned long)
(reg->userspace_addr + addr - reg->guest_phys_addr);
s += size;
addr += size;
++ret;
}
rcu_read_unlock();
return ret;
}
Commit Message: vhost: fix length for cross region descriptor
If a single descriptor crosses a region, the
second chunk length should be decremented
by size translated so far, instead it includes
the full descriptor length.
Signed-off-by: Michael S. Tsirkin <[email protected]>
Acked-by: Jason Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void __show_regs(struct pt_regs *regs)
{
unsigned long flags;
char buf[64];
show_regs_print_info(KERN_DEFAULT);
print_symbol("PC is at %s\n", instruction_pointer(regs));
print_symbol("LR is at %s\n", regs->ARM_lr);
printk("pc : [<%08lx>] lr : [<%08lx>] psr: %08lx\n"
"sp : %08lx ip : %08lx fp : %08lx\n",
regs->ARM_pc, regs->ARM_lr, regs->ARM_cpsr,
regs->ARM_sp, regs->ARM_ip, regs->ARM_fp);
printk("r10: %08lx r9 : %08lx r8 : %08lx\n",
regs->ARM_r10, regs->ARM_r9,
regs->ARM_r8);
printk("r7 : %08lx r6 : %08lx r5 : %08lx r4 : %08lx\n",
regs->ARM_r7, regs->ARM_r6,
regs->ARM_r5, regs->ARM_r4);
printk("r3 : %08lx r2 : %08lx r1 : %08lx r0 : %08lx\n",
regs->ARM_r3, regs->ARM_r2,
regs->ARM_r1, regs->ARM_r0);
flags = regs->ARM_cpsr;
buf[0] = flags & PSR_N_BIT ? 'N' : 'n';
buf[1] = flags & PSR_Z_BIT ? 'Z' : 'z';
buf[2] = flags & PSR_C_BIT ? 'C' : 'c';
buf[3] = flags & PSR_V_BIT ? 'V' : 'v';
buf[4] = '\0';
printk("Flags: %s IRQs o%s FIQs o%s Mode %s ISA %s Segment %s\n",
buf, interrupts_enabled(regs) ? "n" : "ff",
fast_interrupts_enabled(regs) ? "n" : "ff",
processor_modes[processor_mode(regs)],
isa_modes[isa_mode(regs)],
get_fs() == get_ds() ? "kernel" : "user");
#ifdef CONFIG_CPU_CP15
{
unsigned int ctrl;
buf[0] = '\0';
#ifdef CONFIG_CPU_CP15_MMU
{
unsigned int transbase, dac;
asm("mrc p15, 0, %0, c2, c0\n\t"
"mrc p15, 0, %1, c3, c0\n"
: "=r" (transbase), "=r" (dac));
snprintf(buf, sizeof(buf), " Table: %08x DAC: %08x",
transbase, dac);
}
#endif
asm("mrc p15, 0, %0, c1, c0\n" : "=r" (ctrl));
printk("Control: %08x%s\n", ctrl, buf);
}
#endif
}
Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork
Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to
prevent it from being used as a covert channel between two tasks.
There are more and more applications coming to Windows RT,
Wine could support them, but mostly they expect to have
the thread environment block (TEB) in TPIDRURW.
This patch preserves that register per thread instead of clearing it.
Unlike the TPIDRURO, which is already switched, the TPIDRURW
can be updated from userspace so needs careful treatment in the case that we
modify TPIDRURW and call fork(). To avoid this we must always read
TPIDRURW in copy_thread.
Signed-off-by: André Hentschel <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
Signed-off-by: Jonathan Austin <[email protected]>
Signed-off-by: Russell King <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: IW_IMPL(int) iw_get_input_density(struct iw_context *ctx,
double *px, double *py, int *pcode)
{
*px = 1.0;
*py = 1.0;
*pcode = ctx->img1.density_code;
if(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) {
*px = ctx->img1.density_x;
*py = ctx->img1.density_y;
return 1;
}
return 0;
}
Commit Message: Double-check that the input image's density is valid
Fixes a bug that could result in division by zero, at least for a JPEG
source image.
Fixes issues #19, #20
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
{
struct fsck_gitmodules_data *data = vdata;
const char *subsection, *key;
int subsection_len;
char *name;
if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
!subsection)
return 0;
name = xmemdupz(subsection, subsection_len);
if (check_submodule_name(name) < 0)
data->ret |= report(data->options, data->obj,
FSCK_MSG_GITMODULES_NAME,
"disallowed submodule name: %s",
name);
free(name);
return 0;
}
Commit Message: fsck: detect submodule urls starting with dash
Urls with leading dashes can cause mischief on older
versions of Git. We should detect them so that they can be
rejected by receive.fsckObjects, preventing modern versions
of git from being a vector by which attacks can spread.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: ar6000_cleanup_module(void)
{
int i = 0;
struct net_device *ar6000_netdev;
#ifdef ADAPTIVE_POWER_THROUGHPUT_CONTROL
/* Delete the Adaptive Power Control timer */
if (timer_pending(&aptcTimer)) {
del_timer_sync(&aptcTimer);
}
#endif /* ADAPTIVE_POWER_THROUGHPUT_CONTROL */
for (i=0; i < MAX_AR6000; i++) {
if (ar6000_devices[i] != NULL) {
ar6000_netdev = ar6000_devices[i];
ar6000_devices[i] = NULL;
ar6000_destroy(ar6000_netdev, 1);
}
}
HIFShutDownDevice(NULL);
a_module_debug_support_cleanup();
AR_DEBUG_PRINTF(ATH_DEBUG_INFO,("ar6000_cleanup: success\n"));
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(imageaffinematrixget)
{
double affine[6];
long type;
zval *options;
zval **tmp;
int res = GD_FALSE, i;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &type, &options) == FAILURE) {
return;
}
switch((gdAffineStandardMatrix)type) {
case GD_AFFINE_TRANSLATE:
case GD_AFFINE_SCALE: {
double x, y;
if (Z_TYPE_P(options) != IS_ARRAY) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Array expected as options");
}
if (zend_hash_find(HASH_OF(options), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
x = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(options), "y", sizeof("y"), (void **)&tmp) != FAILURE) {
convert_to_double_ex(tmp);
y = Z_DVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (type == GD_AFFINE_TRANSLATE) {
res = gdAffineTranslate(affine, x, y);
} else {
res = gdAffineScale(affine, x, y);
}
break;
}
case GD_AFFINE_ROTATE:
case GD_AFFINE_SHEAR_HORIZONTAL:
case GD_AFFINE_SHEAR_VERTICAL: {
double angle;
convert_to_double_ex(&options);
angle = Z_DVAL_P(options);
if (type == GD_AFFINE_SHEAR_HORIZONTAL) {
res = gdAffineShearHorizontal(affine, angle);
} else if (type == GD_AFFINE_SHEAR_VERTICAL) {
res = gdAffineShearVertical(affine, angle);
} else {
res = gdAffineRotate(affine, angle);
}
break;
}
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %li", type);
RETURN_FALSE;
}
if (res == GD_FALSE) {
RETURN_FALSE;
} else {
array_init(return_value);
for (i = 0; i < 6; i++) {
add_index_double(return_value, i, affine[i]);
}
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
Target: 1
Example 2:
Code: LoginBigUserView* LockContentsView::TestApi::opt_secondary_big_view() const {
return view_->opt_secondary_big_view_;
}
Commit Message: cros: Check initial auth type when showing views login.
Bug: 859611
Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058
Reviewed-on: https://chromium-review.googlesource.com/1123056
Reviewed-by: Xiaoyin Hu <[email protected]>
Commit-Queue: Jacob Dufault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572224}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVQcowState *s = bs->opaque;
unsigned int len, i;
int ret = 0;
QCowHeader header;
QemuOpts *opts;
Error *local_err = NULL;
uint64_t ext_end;
uint64_t l1_vm_state_index;
const char *opt_overlap_check;
int overlap_check_template = 0;
ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read qcow2 header");
goto fail;
}
be32_to_cpus(&header.magic);
be32_to_cpus(&header.version);
be64_to_cpus(&header.backing_file_offset);
be32_to_cpus(&header.backing_file_size);
be64_to_cpus(&header.size);
be32_to_cpus(&header.cluster_bits);
be32_to_cpus(&header.crypt_method);
be64_to_cpus(&header.l1_table_offset);
be32_to_cpus(&header.l1_size);
be64_to_cpus(&header.refcount_table_offset);
be32_to_cpus(&header.refcount_table_clusters);
be64_to_cpus(&header.snapshots_offset);
be32_to_cpus(&header.nb_snapshots);
if (header.magic != QCOW_MAGIC) {
error_setg(errp, "Image is not in qcow2 format");
ret = -EINVAL;
goto fail;
}
if (header.version < 2 || header.version > 3) {
report_unsupported(bs, errp, "QCOW version %d", header.version);
ret = -ENOTSUP;
goto fail;
}
s->qcow_version = header.version;
/* Initialise cluster size */
if (header.cluster_bits < MIN_CLUSTER_BITS ||
header.cluster_bits > MAX_CLUSTER_BITS) {
error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
ret = -EINVAL;
goto fail;
}
s->cluster_bits = header.cluster_bits;
s->cluster_size = 1 << s->cluster_bits;
s->cluster_sectors = 1 << (s->cluster_bits - 9);
/* Initialise version 3 header fields */
if (header.version == 2) {
header.incompatible_features = 0;
header.compatible_features = 0;
header.autoclear_features = 0;
header.refcount_order = 4;
header.header_length = 72;
} else {
be64_to_cpus(&header.incompatible_features);
be64_to_cpus(&header.compatible_features);
be64_to_cpus(&header.autoclear_features);
be32_to_cpus(&header.refcount_order);
be32_to_cpus(&header.header_length);
if (header.header_length < 104) {
error_setg(errp, "qcow2 header too short");
ret = -EINVAL;
goto fail;
}
}
if (header.header_length > s->cluster_size) {
error_setg(errp, "qcow2 header exceeds cluster size");
ret = -EINVAL;
goto fail;
}
if (header.header_length > sizeof(header)) {
s->unknown_header_fields_size = header.header_length - sizeof(header);
s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
s->unknown_header_fields_size);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
"fields");
goto fail;
}
}
if (header.backing_file_offset > s->cluster_size) {
error_setg(errp, "Invalid backing file offset");
ret = -EINVAL;
goto fail;
}
if (header.backing_file_offset) {
ext_end = header.backing_file_offset;
} else {
ext_end = 1 << header.cluster_bits;
}
/* Handle feature bits */
s->incompatible_features = header.incompatible_features;
s->compatible_features = header.compatible_features;
s->autoclear_features = header.autoclear_features;
if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
void *feature_table = NULL;
qcow2_read_extensions(bs, header.header_length, ext_end,
&feature_table, NULL);
report_unsupported_feature(bs, errp, feature_table,
s->incompatible_features &
~QCOW2_INCOMPAT_MASK);
ret = -ENOTSUP;
g_free(feature_table);
goto fail;
}
if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
/* Corrupt images may not be written to unless they are being repaired
*/
if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
"read/write");
ret = -EACCES;
goto fail;
}
}
/* Check support for various header values */
if (header.refcount_order != 4) {
report_unsupported(bs, errp, "%d bit reference counts",
1 << header.refcount_order);
ret = -ENOTSUP;
goto fail;
}
s->refcount_order = header.refcount_order;
if (header.crypt_method > QCOW_CRYPT_AES) {
error_setg(errp, "Unsupported encryption method: %i",
header.crypt_method);
ret = -EINVAL;
goto fail;
}
s->crypt_method_header = header.crypt_method;
if (s->crypt_method_header) {
bs->encrypted = 1;
}
s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
s->l2_size = 1 << s->l2_bits;
bs->total_sectors = header.size / 512;
s->csize_shift = (62 - (s->cluster_bits - 8));
s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
s->refcount_table_offset = header.refcount_table_offset;
s->refcount_table_size =
header.refcount_table_clusters << (s->cluster_bits - 3);
if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
error_setg(errp, "Reference count table too large");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, s->refcount_table_offset,
s->refcount_table_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid reference count table offset");
goto fail;
}
/* Snapshot table offset/length */
if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
error_setg(errp, "Too many snapshots");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.snapshots_offset,
header.nb_snapshots,
sizeof(QCowSnapshotHeader));
if (ret < 0) {
error_setg(errp, "Invalid snapshot table offset");
goto fail;
}
/* read the level 1 table */
if (header.l1_size > 0x2000000) {
/* 32 MB L1 table is enough for 2 PB images at 64k cluster size
* (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
error_setg(errp, "Active L1 table too large");
ret = -EFBIG;
goto fail;
ret = -EFBIG;
goto fail;
}
s->l1_size = header.l1_size;
l1_vm_state_index = size_to_l1(s, header.size);
if (l1_vm_state_index > INT_MAX) {
error_setg(errp, "Image is too big");
ret = -EFBIG;
goto fail;
}
s->l1_vm_state_index = l1_vm_state_index;
/* the L1 table must contain at least enough entries to put
header.size bytes */
if (s->l1_size < s->l1_vm_state_index) {
error_setg(errp, "L1 table is too small");
ret = -EINVAL;
goto fail;
}
ret = validate_table_offset(bs, header.l1_table_offset,
header.l1_size, sizeof(uint64_t));
if (ret < 0) {
error_setg(errp, "Invalid L1 table offset");
goto fail;
}
s->l1_table_offset = header.l1_table_offset;
if (s->l1_size > 0) {
s->l1_table = g_malloc0(
align_offset(s->l1_size * sizeof(uint64_t), 512));
ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
s->l1_size * sizeof(uint64_t));
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read L1 table");
goto fail;
}
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
}
/* alloc L2 table/refcount block cache */
s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
s->cluster_cache = g_malloc(s->cluster_size);
/* one more sector for decompressed data alignment */
s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
+ 512);
s->cluster_cache_offset = -1;
s->flags = flags;
ret = qcow2_refcount_init(bs);
if (ret != 0) {
error_setg_errno(errp, -ret, "Could not initialize refcount handling");
goto fail;
}
QLIST_INIT(&s->cluster_allocs);
QTAILQ_INIT(&s->discards);
/* read qcow2 extensions */
if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
&local_err)) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
/* read the backing file name */
if (header.backing_file_offset != 0) {
len = header.backing_file_size;
if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
error_setg(errp, "Backing file name too long");
ret = -EINVAL;
goto fail;
}
ret = bdrv_pread(bs->file, header.backing_file_offset,
bs->backing_file, len);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read backing file name");
goto fail;
}
bs->backing_file[len] = '\0';
}
/* Internal snapshots */
s->snapshots_offset = header.snapshots_offset;
s->nb_snapshots = header.nb_snapshots;
ret = qcow2_read_snapshots(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not read snapshots");
goto fail;
}
/* Clear unknown autoclear feature bits */
if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
s->autoclear_features = 0;
ret = qcow2_update_header(bs);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not update qcow2 header");
goto fail;
}
}
/* Initialise locks */
qemu_co_mutex_init(&s->lock);
/* Repair image if dirty */
if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
(s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
BdrvCheckResult result = {0};
ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
if (ret < 0) {
error_setg_errno(errp, -ret, "Could not repair dirty image");
goto fail;
}
}
/* Enable lazy_refcounts according to image and command line options */
opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
qemu_opts_absorb_qdict(opts, options, &local_err);
if (local_err) {
error_propagate(errp, local_err);
ret = -EINVAL;
goto fail;
}
s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
(s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
flags & BDRV_O_UNMAP);
s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
s->discard_passthrough[QCOW2_DISCARD_OTHER] =
qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
if (!strcmp(opt_overlap_check, "none")) {
overlap_check_template = 0;
} else if (!strcmp(opt_overlap_check, "constant")) {
overlap_check_template = QCOW2_OL_CONSTANT;
} else if (!strcmp(opt_overlap_check, "cached")) {
overlap_check_template = QCOW2_OL_CACHED;
} else if (!strcmp(opt_overlap_check, "all")) {
overlap_check_template = QCOW2_OL_ALL;
} else {
error_setg(errp, "Unsupported value '%s' for qcow2 option "
"'overlap-check'. Allowed are either of the following: "
"none, constant, cached, all", opt_overlap_check);
qemu_opts_del(opts);
ret = -EINVAL;
goto fail;
}
s->overlap_check = 0;
for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
/* overlap-check defines a template bitmask, but every flag may be
* overwritten through the associated boolean option */
s->overlap_check |=
qemu_opt_get_bool(opts, overlap_bool_option_names[i],
overlap_check_template & (1 << i)) << i;
}
qemu_opts_del(opts);
if (s->use_lazy_refcounts && s->qcow_version < 3) {
error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
"qemu 1.1 compatibility level");
ret = -EINVAL;
goto fail;
}
#ifdef DEBUG_ALLOC
{
BdrvCheckResult result = {0};
qcow2_check_refcounts(bs, &result, 0);
}
#endif
return ret;
fail:
g_free(s->unknown_header_fields);
cleanup_unknown_header_ext(bs);
qcow2_free_snapshots(bs);
qcow2_refcount_close(bs);
g_free(s->l1_table);
/* else pre-write overlap checks in cache_destroy may crash */
s->l1_table = NULL;
if (s->l2_table_cache) {
qcow2_cache_destroy(bs, s->l2_table_cache);
}
if (s->refcount_block_cache) {
qcow2_cache_destroy(bs, s->refcount_block_cache);
}
g_free(s->cluster_cache);
qemu_vfree(s->cluster_data);
return ret;
}
Commit Message:
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: IHEVCD_ERROR_T ihevcd_cabac_init(cab_ctxt_t *ps_cabac,
bitstrm_t *ps_bitstrm,
WORD32 qp,
WORD32 cabac_init_idc,
const UWORD8 *pu1_init_ctxt)
{
/* Sanity checks */
ASSERT(ps_cabac != NULL);
ASSERT(ps_bitstrm != NULL);
ASSERT((qp >= 0) && (qp < 52));
ASSERT((cabac_init_idc >= 0) && (cabac_init_idc < 3));
UNUSED(qp);
UNUSED(cabac_init_idc);
/* CABAC engine uses 32 bit range instead of 9 bits as specified by
* the spec. This is done to reduce number of renormalizations
*/
/* cabac engine initialization */
#if FULLRANGE
ps_cabac->u4_range = (UWORD32)510 << RANGE_SHIFT;
BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst,
ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, (9 + RANGE_SHIFT));
#else
ps_cabac->u4_range = (UWORD32)510;
BITS_GET(ps_cabac->u4_ofst, ps_bitstrm->pu4_buf, ps_bitstrm->u4_bit_ofst,
ps_bitstrm->u4_cur_word, ps_bitstrm->u4_nxt_word, 9);
#endif
/* cabac context initialization based on init idc and slice qp */
memcpy(ps_cabac->au1_ctxt_models,
pu1_init_ctxt,
IHEVC_CAB_CTXT_END);
DEBUG_RANGE_OFST("init", ps_cabac->u4_range, ps_cabac->u4_ofst);
return ((IHEVCD_ERROR_T)IHEVCD_SUCCESS);
}
Commit Message: Return error from cabac init if offset is greater than range
When the offset was greater than range, the bitstream was read
more than the valid range in leaf-level cabac parsing modules.
Error check was added to cabac init to fix this issue. Additionally
end of slice and slice error were signalled to suppress further
parsing of current slice.
Bug: 34897036
Change-Id: I1263f1d1219684ffa6e952c76e5a08e9a933c9d2
(cherry picked from commit 3b175da88a1807d19cdd248b74bce60e57f05c6a)
(cherry picked from commit b92314c860d01d754ef579eafe55d7377962b3ba)
CWE ID: CWE-119
Target: 1
Example 2:
Code: DOMWindow::~DOMWindow() {
DCHECK(!frame_);
}
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:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: GF_Err urn_Read(GF_Box *s, GF_BitStream *bs)
{
u32 i, to_read;
char *tmpName;
GF_DataEntryURNBox *ptr = (GF_DataEntryURNBox *)s;
if (! ptr->size ) return GF_OK;
to_read = (u32) ptr->size;
tmpName = (char*)gf_malloc(sizeof(char) * to_read);
if (!tmpName) return GF_OUT_OF_MEM;
gf_bs_read_data(bs, tmpName, to_read);
i = 0;
while ( (tmpName[i] != 0) && (i < to_read) ) {
i++;
}
if (i == to_read) {
gf_free(tmpName);
return GF_ISOM_INVALID_FILE;
}
if (i == to_read - 1) {
ptr->nameURN = tmpName;
ptr->location = NULL;
return GF_OK;
}
ptr->nameURN = (char*)gf_malloc(sizeof(char) * (i+1));
if (!ptr->nameURN) {
gf_free(tmpName);
return GF_OUT_OF_MEM;
}
ptr->location = (char*)gf_malloc(sizeof(char) * (to_read - i - 1));
if (!ptr->location) {
gf_free(tmpName);
gf_free(ptr->nameURN);
ptr->nameURN = NULL;
return GF_OUT_OF_MEM;
}
memcpy(ptr->nameURN, tmpName, i + 1);
memcpy(ptr->location, tmpName + i + 1, (to_read - i - 1));
gf_free(tmpName);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PlatformSensor::UpdateSharedBuffer(const SensorReading& reading) {
ReadingBuffer* buffer =
static_cast<ReadingBuffer*>(shared_buffer_mapping_.get());
auto& seqlock = buffer->seqlock.value();
seqlock.WriteBegin();
buffer->reading = reading;
seqlock.WriteEnd();
}
Commit Message: android: Fix sensors in device service.
This patch fixes a bug that prevented more than one sensor data
to be available at once when using the device motion/orientation
API.
The issue was introduced by this other patch [1] which fixed
some security-related issues in the way shared memory region
handles are managed throughout Chromium (more details at
https://crbug.com/789959).
The device service´s sensor implementation doesn´t work
correctly because it assumes it is possible to create a
writable mapping of a given shared memory region at any
time. This assumption is not correct on Android, once an
Ashmem region has been turned read-only, such mappings
are no longer possible.
To fix the implementation, this CL changes the following:
- PlatformSensor used to require moving a
mojo::ScopedSharedBufferMapping into the newly-created
instance. Said mapping being owned by and destroyed
with the PlatformSensor instance.
With this patch, the constructor instead takes a single
pointer to the corresponding SensorReadingSharedBuffer,
i.e. the area in memory where the sensor-specific
reading data is located, and can be either updated
or read-from.
Note that the PlatformSensor does not own the mapping
anymore.
- PlatformSensorProviderBase holds the *single* writable
mapping that is used to store all SensorReadingSharedBuffer
buffers. It is created just after the region itself,
and thus can be used even after the region's access
mode has been changed to read-only.
Addresses within the mapping will be passed to
PlatformSensor constructors, computed from the
mapping's base address plus a sensor-specific
offset.
The mapping is now owned by the
PlatformSensorProviderBase instance.
Note that, security-wise, nothing changes, because all
mojo::ScopedSharedBufferMapping before the patch actually
pointed to the same writable-page in memory anyway.
Since unit or integration tests didn't catch the regression
when [1] was submitted, this patch was tested manually by
running a newly-built Chrome apk in the Android emulator
and on a real device running Android O.
[1] https://chromium-review.googlesource.com/c/chromium/src/+/805238
BUG=805146
[email protected],[email protected],[email protected],[email protected]
Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44
Reviewed-on: https://chromium-review.googlesource.com/891180
Commit-Queue: David Turner <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Matthew Cary <[email protected]>
Reviewed-by: Alexandr Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#532607}
CWE ID: CWE-732
Target: 1
Example 2:
Code: void virtio_config_modern_writel(VirtIODevice *vdev,
uint32_t addr, uint32_t data)
{
VirtioDeviceClass *k = VIRTIO_DEVICE_GET_CLASS(vdev);
uint32_t val = data;
if (addr + sizeof(val) > vdev->config_len) {
return;
}
stl_le_p(vdev->config + addr, val);
if (k->set_config) {
k->set_config(vdev, vdev->config);
}
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: virDomainMigratePrepareTunnel3Params(virConnectPtr conn,
virStreamPtr st,
virTypedParameterPtr params,
int nparams,
const char *cookiein,
int cookieinlen,
char **cookieout,
int *cookieoutlen,
unsigned int flags)
{
VIR_DEBUG("conn=%p, stream=%p, params=%p, nparams=%d, cookiein=%p, "
"cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x",
conn, st, params, nparams, cookiein, cookieinlen,
cookieout, cookieoutlen, flags);
VIR_TYPED_PARAMS_DEBUG(params, nparams);
virResetLastError();
virCheckConnectReturn(conn, -1);
virCheckReadOnlyGoto(conn->flags, error);
if (conn != st->conn) {
virReportInvalidArg(conn, "%s",
_("conn must match stream connection"));
goto error;
}
if (conn->driver->domainMigratePrepareTunnel3Params) {
int rv;
rv = conn->driver->domainMigratePrepareTunnel3Params(
conn, st, params, nparams, cookiein, cookieinlen,
cookieout, cookieoutlen, flags);
if (rv < 0)
goto error;
return rv;
}
virReportUnsupportedError();
error:
virDispatchError(conn);
return -1;
}
Commit Message: virDomainGetTime: Deny on RO connections
We have a policy that if API may end up talking to a guest agent
it should require RW connection. We don't obey the rule in
virDomainGetTime().
Signed-off-by: Michal Privoznik <[email protected]>
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static char *get_pid_environ_val(pid_t pid,char *val){
char temp[500];
int i=0;
int foundit=0;
FILE *fp;
sprintf(temp,"/proc/%d/environ",pid);
fp=fopen(temp,"r");
if(fp==NULL)
return NULL;
for(;;){
temp[i]=fgetc(fp);
if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){
char *ret;
temp[i]=0;
ret=malloc(strlen(temp)+10);
sprintf(ret,"%s",temp);
fclose(fp);
return ret;
}
switch(temp[i]){
case EOF:
fclose(fp);
return NULL;
case '=':
temp[i]=0;
if(!strcmp(temp,val)){
foundit=1;
}
i=0;
break;
case '\0':
i=0;
break;
default:
i++;
}
}
}
Commit Message: Fix memory overflow if the name of an environment is larger than 500 characters. Bug found by Adam Sampson.
CWE ID: CWE-119
Target: 1
Example 2:
Code: find_min_mtu(struct ofproto *p)
{
struct ofport *ofport;
int mtu = 0;
HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
struct netdev *netdev = ofport->netdev;
int dev_mtu;
/* Skip any overridden port, since that's what we're trying to set. */
if (ofport_is_mtu_overridden(p, ofport)) {
continue;
}
if (netdev_get_mtu(netdev, &dev_mtu)) {
continue;
}
if (!mtu || dev_mtu < mtu) {
mtu = dev_mtu;
}
}
return mtu ? mtu: ETH_PAYLOAD_MAX;
}
Commit Message: ofproto: Fix OVS crash when reverting old flows in bundle commit
During bundle commit flows which are added in bundle are applied
to ofproto in-order. In case if a flow cannot be added (e.g. flow
action is go-to group id which does not exist), OVS tries to
revert back all previous flows which were successfully applied
from the same bundle. This is possible since OVS maintains list
of old flows which were replaced by flows from the bundle.
While reinserting old flows ovs asserts due to check on rule
state != RULE_INITIALIZED. This will work only for new flows, but
for old flow the rule state will be RULE_REMOVED. This is causing
an assert and OVS crash.
The ovs assert check should be modified to != RULE_INSERTED to prevent
any existing rule being re-inserted and allow new rules and old rules
(in case of revert) to get inserted.
Here is an example to trigger the assert:
$ ovs-vsctl add-br br-test -- set Bridge br-test datapath_type=netdev
$ cat flows.txt
flow add table=1,priority=0,in_port=2,actions=NORMAL
flow add table=1,priority=0,in_port=3,actions=NORMAL
$ ovs-ofctl dump-flows -OOpenflow13 br-test
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=2 actions=NORMAL
cookie=0x0, duration=2.465s, table=1, n_packets=0, n_bytes=0, priority=0,in_port=3 actions=NORMAL
$ cat flow-modify.txt
flow modify table=1,priority=0,in_port=2,actions=drop
flow modify table=1,priority=0,in_port=3,actions=group:10
$ ovs-ofctl bundle br-test flow-modify.txt -OOpenflow13
First flow rule will be modified since it is a valid rule. However second
rule is invalid since no group with id 10 exists. Bundle commit tries to
revert (insert) the first rule to old flow which results in ovs_assert at
ofproto_rule_insert__() since old rule->state = RULE_REMOVED.
Signed-off-by: Vishal Deep Ajmera <[email protected]>
Signed-off-by: Ben Pfaff <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void commit_tree(struct mount *mnt, struct mount *shadows)
{
struct mount *parent = mnt->mnt_parent;
struct mount *m;
LIST_HEAD(head);
struct mnt_namespace *n = parent->mnt_ns;
BUG_ON(parent == mnt);
list_add_tail(&head, &mnt->mnt_list);
list_for_each_entry(m, &head, mnt_list)
m->mnt_ns = n;
list_splice(&head, n->list.prev);
attach_shadowed(mnt, parent, shadows);
touch_mnt_namespace(n);
}
Commit Message: mnt: Add a per mount namespace limit on the number of mounts
CAI Qian <[email protected]> pointed out that the semantics
of shared subtrees make it possible to create an exponentially
increasing number of mounts in a mount namespace.
mkdir /tmp/1 /tmp/2
mount --make-rshared /
for i in $(seq 1 20) ; do mount --bind /tmp/1 /tmp/2 ; done
Will create create 2^20 or 1048576 mounts, which is a practical problem
as some people have managed to hit this by accident.
As such CVE-2016-6213 was assigned.
Ian Kent <[email protected]> described the situation for autofs users
as follows:
> The number of mounts for direct mount maps is usually not very large because of
> the way they are implemented, large direct mount maps can have performance
> problems. There can be anywhere from a few (likely case a few hundred) to less
> than 10000, plus mounts that have been triggered and not yet expired.
>
> Indirect mounts have one autofs mount at the root plus the number of mounts that
> have been triggered and not yet expired.
>
> The number of autofs indirect map entries can range from a few to the common
> case of several thousand and in rare cases up to between 30000 and 50000. I've
> not heard of people with maps larger than 50000 entries.
>
> The larger the number of map entries the greater the possibility for a large
> number of active mounts so it's not hard to expect cases of a 1000 or somewhat
> more active mounts.
So I am setting the default number of mounts allowed per mount
namespace at 100,000. This is more than enough for any use case I
know of, but small enough to quickly stop an exponential increase
in mounts. Which should be perfect to catch misconfigurations and
malfunctioning programs.
For anyone who needs a higher limit this can be changed by writing
to the new /proc/sys/fs/mount-max sysctl.
Tested-by: CAI Qian <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-400
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t MPEG4Source::fragmentedRead(
MediaBuffer **out, const ReadOptions *options) {
ALOGV("MPEG4Source::fragmentedRead");
CHECK(mStarted);
*out = NULL;
int64_t targetSampleTimeUs = -1;
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
int numSidxEntries = mSegments.size();
if (numSidxEntries != 0) {
int64_t totalTime = 0;
off64_t totalOffset = mFirstMoofOffset;
for (int i = 0; i < numSidxEntries; i++) {
const SidxEntry *se = &mSegments[i];
if (totalTime + se->mDurationUs > seekTimeUs) {
if ((mode == ReadOptions::SEEK_NEXT_SYNC) ||
(mode == ReadOptions::SEEK_CLOSEST_SYNC &&
(seekTimeUs - totalTime) > (totalTime + se->mDurationUs - seekTimeUs))) {
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
break;
}
totalTime += se->mDurationUs;
totalOffset += se->mSize;
}
mCurrentMoofOffset = totalOffset;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&totalOffset);
mCurrentTime = totalTime * mTimescale / 1000000ll;
}
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
}
off64_t offset = 0;
size_t size;
uint32_t cts = 0;
bool isSyncSample = false;
bool newBuffer = false;
if (mBuffer == NULL) {
newBuffer = true;
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
Sample lastSample = mCurrentSamples[mCurrentSamples.size() - 1];
off64_t nextMoof = mNextMoofOffset; // lastSample.offset + lastSample.size;
mCurrentMoofOffset = nextMoof;
mCurrentSamples.clear();
mCurrentSampleIndex = 0;
parseChunk(&nextMoof);
if (mCurrentSampleIndex >= mCurrentSamples.size()) {
return ERROR_END_OF_STREAM;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
offset = smpl->offset;
size = smpl->size;
cts = mCurrentTime;
mCurrentTime += smpl->duration;
isSyncSample = (mCurrentSampleIndex == 0); // XXX
status_t err = mGroup->acquire_buffer(&mBuffer);
if (err != OK) {
CHECK(mBuffer == NULL);
ALOGV("acquire_buffer returned %d", err);
return err;
}
if (size > mBuffer->size()) {
ALOGE("buffer too small: %zu > %zu", size, mBuffer->size());
return ERROR_BUFFER_TOO_SMALL;
}
}
const Sample *smpl = &mCurrentSamples[mCurrentSampleIndex];
const sp<MetaData> bufmeta = mBuffer->meta_data();
bufmeta->clear();
if (smpl->encryptedsizes.size()) {
bufmeta->setData(kKeyPlainSizes, 0,
smpl->clearsizes.array(), smpl->clearsizes.size() * 4);
bufmeta->setData(kKeyEncryptedSizes, 0,
smpl->encryptedsizes.array(), smpl->encryptedsizes.size() * 4);
bufmeta->setData(kKeyCryptoIV, 0, smpl->iv, 16); // use 16 or the actual size?
bufmeta->setInt32(kKeyCryptoDefaultIVSize, mDefaultIVSize);
bufmeta->setInt32(kKeyCryptoMode, mCryptoMode);
bufmeta->setData(kKeyCryptoKey, 0, mCryptoKey, 16);
}
if (!mIsAVC || mWantsNALFragments) {
if (newBuffer) {
if (!isInRange((size_t)0u, mBuffer->size(), size)) {
mBuffer->release();
mBuffer = NULL;
ALOGE("fragmentedRead ERROR_MALFORMED size %zu", size);
return ERROR_MALFORMED;
}
ssize_t num_bytes_read =
mDataSource->readAt(offset, (uint8_t *)mBuffer->data(), size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGE("i/o error");
return ERROR_IO;
}
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
}
if (!mIsAVC) {
*out = mBuffer;
mBuffer = NULL;
return OK;
}
CHECK(mBuffer->range_length() >= mNALLengthSize);
const uint8_t *src =
(const uint8_t *)mBuffer->data() + mBuffer->range_offset();
size_t nal_size = parseNALSize(src);
if (mNALLengthSize > SIZE_MAX - nal_size) {
ALOGE("b/24441553, b/24445122");
}
if (mBuffer->range_length() - mNALLengthSize < nal_size) {
ALOGE("incomplete NAL unit.");
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
MediaBuffer *clone = mBuffer->clone();
CHECK(clone != NULL);
clone->set_range(mBuffer->range_offset() + mNALLengthSize, nal_size);
CHECK(mBuffer != NULL);
mBuffer->set_range(
mBuffer->range_offset() + mNALLengthSize + nal_size,
mBuffer->range_length() - mNALLengthSize - nal_size);
if (mBuffer->range_length() == 0) {
mBuffer->release();
mBuffer = NULL;
}
*out = clone;
return OK;
} else {
ALOGV("whole NAL");
ssize_t num_bytes_read = 0;
int32_t drm = 0;
bool usesDRM = (mFormat->findInt32(kKeyIsDRM, &drm) && drm != 0);
void *data = NULL;
bool isMalFormed = false;
if (usesDRM) {
if (mBuffer == NULL || !isInRange((size_t)0u, mBuffer->size(), size)) {
isMalFormed = true;
} else {
data = mBuffer->data();
}
} else {
int32_t max_size;
if (mFormat == NULL
|| !mFormat->findInt32(kKeyMaxInputSize, &max_size)
|| !isInRange((size_t)0u, (size_t)max_size, size)) {
isMalFormed = true;
} else {
data = mSrcBuffer;
}
}
if (isMalFormed || data == NULL) {
ALOGE("isMalFormed size %zu", size);
if (mBuffer != NULL) {
mBuffer->release();
mBuffer = NULL;
}
return ERROR_MALFORMED;
}
num_bytes_read = mDataSource->readAt(offset, data, size);
if (num_bytes_read < (ssize_t)size) {
mBuffer->release();
mBuffer = NULL;
ALOGE("i/o error");
return ERROR_IO;
}
if (usesDRM) {
CHECK(mBuffer != NULL);
mBuffer->set_range(0, size);
} else {
uint8_t *dstData = (uint8_t *)mBuffer->data();
size_t srcOffset = 0;
size_t dstOffset = 0;
while (srcOffset < size) {
isMalFormed = !isInRange((size_t)0u, size, srcOffset, mNALLengthSize);
size_t nalLength = 0;
if (!isMalFormed) {
nalLength = parseNALSize(&mSrcBuffer[srcOffset]);
srcOffset += mNALLengthSize;
isMalFormed = !isInRange((size_t)0u, size, srcOffset, nalLength)
|| !isInRange((size_t)0u, mBuffer->size(), dstOffset, (size_t)4u)
|| !isInRange((size_t)0u, mBuffer->size(), dstOffset + 4, nalLength);
}
if (isMalFormed) {
ALOGE("Video is malformed; nalLength %zu", nalLength);
mBuffer->release();
mBuffer = NULL;
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= mBuffer->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &mSrcBuffer[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, size);
CHECK(mBuffer != NULL);
mBuffer->set_range(0, dstOffset);
}
mBuffer->meta_data()->setInt64(
kKeyTime, ((int64_t)cts * 1000000) / mTimescale);
if (targetSampleTimeUs >= 0) {
mBuffer->meta_data()->setInt64(
kKeyTargetTime, targetSampleTimeUs);
}
if (isSyncSample) {
mBuffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
}
++mCurrentSampleIndex;
*out = mBuffer;
mBuffer = NULL;
return OK;
}
}
Commit Message: Fix out-of-bounds write
Bug: 26365349
Change-Id: Ia363d9f8c231cf255dea852e0bbf5ca466c7990b
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port,
const void *val, unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
memcpy(vcpu->arch.pio_data, val, size * count);
return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: jpc_streamlist_t *jpc_ppmstabtostreams(jpc_ppxstab_t *tab)
{
jpc_streamlist_t *streams;
uchar *dataptr;
uint_fast32_t datacnt;
uint_fast32_t tpcnt;
jpc_ppxstabent_t *ent;
int entno;
jas_stream_t *stream;
int n;
if (!(streams = jpc_streamlist_create())) {
goto error;
}
if (!tab->numents) {
return streams;
}
entno = 0;
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
for (;;) {
/* Get the length of the packet header data for the current
tile-part. */
if (datacnt < 4) {
goto error;
}
if (!(stream = jas_stream_memopen(0, 0))) {
goto error;
}
if (jpc_streamlist_insert(streams, jpc_streamlist_numstreams(streams),
stream)) {
goto error;
}
tpcnt = (dataptr[0] << 24) | (dataptr[1] << 16) | (dataptr[2] << 8)
| dataptr[3];
datacnt -= 4;
dataptr += 4;
/* Get the packet header data for the current tile-part. */
while (tpcnt) {
if (!datacnt) {
if (++entno >= tab->numents) {
goto error;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
n = JAS_MIN(tpcnt, datacnt);
if (jas_stream_write(stream, dataptr, n) != n) {
goto error;
}
tpcnt -= n;
dataptr += n;
datacnt -= n;
}
jas_stream_rewind(stream);
if (!datacnt) {
if (++entno >= tab->numents) {
break;
}
ent = tab->ents[entno];
dataptr = ent->data;
datacnt = ent->len;
}
}
return streams;
error:
if (streams) {
jpc_streamlist_destroy(streams);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void clear() {
key_received_ = key_handled_ = false;
event_flags_ = 0;
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int try_to_reset_cmd_device(struct scsi_cmnd *cmd)
{
int res;
struct Scsi_Host *shost = cmd->device->host;
if (!shost->hostt->eh_device_reset_handler)
goto try_target_reset;
res = shost->hostt->eh_device_reset_handler(cmd);
if (res == SUCCESS)
return res;
try_target_reset:
if (shost->hostt->eh_target_reset_handler)
return shost->hostt->eh_target_reset_handler(cmd);
return FAILED;
}
Commit Message: scsi: libsas: defer ata device eh commands to libata
When ata device doing EH, some commands still attached with tasks are
not passed to libata when abort failed or recover failed, so libata did
not handle these commands. After these commands done, sas task is freed,
but ata qc is not freed. This will cause ata qc leak and trigger a
warning like below:
WARNING: CPU: 0 PID: 28512 at drivers/ata/libata-eh.c:4037
ata_eh_finish+0xb4/0xcc
CPU: 0 PID: 28512 Comm: kworker/u32:2 Tainted: G W OE 4.14.0#1
......
Call trace:
[<ffff0000088b7bd0>] ata_eh_finish+0xb4/0xcc
[<ffff0000088b8420>] ata_do_eh+0xc4/0xd8
[<ffff0000088b8478>] ata_std_error_handler+0x44/0x8c
[<ffff0000088b8068>] ata_scsi_port_error_handler+0x480/0x694
[<ffff000008875fc4>] async_sas_ata_eh+0x4c/0x80
[<ffff0000080f6be8>] async_run_entry_fn+0x4c/0x170
[<ffff0000080ebd70>] process_one_work+0x144/0x390
[<ffff0000080ec100>] worker_thread+0x144/0x418
[<ffff0000080f2c98>] kthread+0x10c/0x138
[<ffff0000080855dc>] ret_from_fork+0x10/0x18
If ata qc leaked too many, ata tag allocation will fail and io blocked
for ever.
As suggested by Dan Williams, defer ata device commands to libata and
merge sas_eh_finish_cmd() with sas_eh_defer_cmd(). libata will handle
ata qcs correctly after this.
Signed-off-by: Jason Yan <[email protected]>
CC: Xiaofei Tan <[email protected]>
CC: John Garry <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Dan Williams <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: long kvm_arch_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
switch (ioctl) {
case KVM_ARM_VCPU_INIT: {
struct kvm_vcpu_init init;
if (copy_from_user(&init, argp, sizeof(init)))
return -EFAULT;
return kvm_vcpu_set_target(vcpu, &init);
}
case KVM_SET_ONE_REG:
case KVM_GET_ONE_REG: {
struct kvm_one_reg reg;
if (copy_from_user(®, argp, sizeof(reg)))
return -EFAULT;
if (ioctl == KVM_SET_ONE_REG)
return kvm_arm_set_reg(vcpu, ®);
else
return kvm_arm_get_reg(vcpu, ®);
}
case KVM_GET_REG_LIST: {
struct kvm_reg_list __user *user_list = argp;
struct kvm_reg_list reg_list;
unsigned n;
if (copy_from_user(®_list, user_list, sizeof(reg_list)))
return -EFAULT;
n = reg_list.n;
reg_list.n = kvm_arm_num_regs(vcpu);
if (copy_to_user(user_list, ®_list, sizeof(reg_list)))
return -EFAULT;
if (n < reg_list.n)
return -E2BIG;
return kvm_arm_copy_reg_indices(vcpu, user_list->reg);
}
default:
return -EINVAL;
}
}
Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl
Some ARM KVM VCPU ioctls require the vCPU to be properly initialized
with the KVM_ARM_VCPU_INIT ioctl before being used with further
requests. KVM_RUN checks whether this initialization has been
done, but other ioctls do not.
Namely KVM_GET_REG_LIST will dereference an array with index -1
without initialization and thus leads to a kernel oops.
Fix this by adding checks before executing the ioctl handlers.
[ Removed superflous comment from static function - Christoffer ]
Changes from v1:
* moved check into a static function with a meaningful name
Signed-off-by: Andre Przywara <[email protected]>
Signed-off-by: Christoffer Dall <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
u64 reset)
{
struct cpuacct *ca = cgroup_ca(cgrp);
int err = 0;
int i;
if (reset) {
err = -EINVAL;
goto out;
}
for_each_present_cpu(i)
cpuacct_cpuusage_write(ca, i, 0);
out:
return err;
}
Commit Message: Sched: fix skip_clock_update optimization
idle_balance() drops/retakes rq->lock, leaving the previous task
vulnerable to set_tsk_need_resched(). Clear it after we return
from balancing instead, and in setup_thread_stack() as well, so
no successfully descheduled or never scheduled task has it set.
Need resched confused the skip_clock_update logic, which assumes
that the next call to update_rq_clock() will come nearly immediately
after being set. Make the optimization robust against the waking
a sleeper before it sucessfully deschedules case by checking that
the current task has not been dequeued before setting the flag,
since it is that useless clock update we're trying to save, and
clear unconditionally in schedule() proper instead of conditionally
in put_prev_task().
Signed-off-by: Mike Galbraith <[email protected]>
Reported-by: Bjoern B. Brandenburg <[email protected]>
Tested-by: Yong Zhang <[email protected]>
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: [email protected]
LKML-Reference: <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WtsSessionProcessDelegate::Core::OnJobNotification(DWORD message,
DWORD pid) {
DCHECK(main_task_runner_->BelongsToCurrentThread());
switch (message) {
case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO:
CHECK(SetEvent(process_exit_event_));
break;
case JOB_OBJECT_MSG_NEW_PROCESS:
worker_process_.Set(OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid));
break;
}
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintPreviewUI::OnPrintPreviewRequest(int request_id) {
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, request_id);
}
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
Target: 1
Example 2:
Code: __journal_try_to_free_buffer(journal_t *journal, struct buffer_head *bh)
{
struct journal_head *jh;
jh = bh2jh(bh);
if (buffer_locked(bh) || buffer_dirty(bh))
goto out;
if (jh->b_next_transaction != NULL)
goto out;
spin_lock(&journal->j_list_lock);
if (jh->b_cp_transaction != NULL && jh->b_transaction == NULL) {
/* written-back checkpointed metadata buffer */
if (jh->b_jlist == BJ_None) {
JBUFFER_TRACE(jh, "remove from checkpoint list");
__jbd2_journal_remove_checkpoint(jh);
}
}
spin_unlock(&journal->j_list_lock);
out:
return;
}
Commit Message: jbd2: clear BH_Delay & BH_Unwritten in journal_unmap_buffer
journal_unmap_buffer()'s zap_buffer: code clears a lot of buffer head
state ala discard_buffer(), but does not touch _Delay or _Unwritten as
discard_buffer() does.
This can be problematic in some areas of the ext4 code which assume
that if they have found a buffer marked unwritten or delay, then it's
a live one. Perhaps those spots should check whether it is mapped
as well, but if jbd2 is going to tear down a buffer, let's really
tear it down completely.
Without this I get some fsx failures on sub-page-block filesystems
up until v3.2, at which point 4e96b2dbbf1d7e81f22047a50f862555a6cb87cb
and 189e868fa8fdca702eb9db9d8afc46b5cb9144c9 make the failures go
away, because buried within that large change is some more flag
clearing. I still think it's worth doing in jbd2, since
->invalidatepage leads here directly, and it's the right place
to clear away these flags.
Signed-off-by: Eric Sandeen <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: cmsBool AddMLUBlock(cmsMLU* mlu, cmsUInt32Number size, const wchar_t *Block,
cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
{
cmsUInt32Number Offset;
cmsUInt8Number* Ptr;
if (mlu == NULL) return FALSE;
if (mlu ->UsedEntries >= mlu ->AllocatedEntries) {
if (!GrowMLUtable(mlu)) return FALSE;
}
if (SearchMLUEntry(mlu, LanguageCode, CountryCode) >= 0) return FALSE; // Only one is allowed!
while ((mlu ->PoolSize - mlu ->PoolUsed) < size) {
if (!GrowMLUpool(mlu)) return FALSE;
}
Offset = mlu ->PoolUsed;
Ptr = (cmsUInt8Number*) mlu ->MemPool;
if (Ptr == NULL) return FALSE;
memmove(Ptr + Offset, Block, size);
mlu ->PoolUsed += size;
mlu ->Entries[mlu ->UsedEntries].StrW = Offset;
mlu ->Entries[mlu ->UsedEntries].Len = size;
mlu ->Entries[mlu ->UsedEntries].Country = CountryCode;
mlu ->Entries[mlu ->UsedEntries].Language = LanguageCode;
mlu ->UsedEntries++;
return TRUE;
}
Commit Message: Non happy-path fixes
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(mcrypt_module_open)
{
char *cipher, *cipher_dir;
char *mode, *mode_dir;
int cipher_len, cipher_dir_len;
int mode_len, mode_dir_len;
MCRYPT td;
php_mcrypt *pm;
if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss",
&cipher, &cipher_len, &cipher_dir, &cipher_dir_len,
&mode, &mode_len, &mode_dir, &mode_dir_len)) {
return;
}
td = mcrypt_module_open (
cipher,
cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir),
mode,
mode_dir_len > 0 ? mode_dir : MCG(modes_dir)
);
if (td == MCRYPT_FAILED) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module");
RETURN_FALSE;
} else {
pm = emalloc(sizeof(php_mcrypt));
pm->td = td;
pm->init = 0;
ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt);
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: explicit EventTestWindow(bool modal) : TestWindow(modal), mouse_presses_(0) {}
Commit Message: cros: Enable some tests in //ash/wm in ash_unittests --mash
For the ones that fail, disable them via filter file instead of in the
code, per our disablement policy.
Bug: 698085, 695556, 698878, 698888, 698093, 698894
Test: ash_unittests --mash
Change-Id: Ic145ab6a95508968d6884d14fac2a3ca08888d26
Reviewed-on: https://chromium-review.googlesource.com/752423
Commit-Queue: James Cook <[email protected]>
Reviewed-by: Steven Bennetts <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513836}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gplotMakeOutput(GPLOT *gplot)
{
char buf[L_BUF_SIZE];
char *cmdname;
l_int32 ignore;
PROCNAME("gplotMakeOutput");
if (!gplot)
return ERROR_INT("gplot not defined", procName, 1);
gplotGenCommandFile(gplot);
gplotGenDataFiles(gplot);
cmdname = genPathname(gplot->cmdname, NULL);
#ifndef _WIN32
snprintf(buf, L_BUF_SIZE, "gnuplot %s", cmdname);
#else
snprintf(buf, L_BUF_SIZE, "wgnuplot %s", cmdname);
#endif /* _WIN32 */
#ifndef OS_IOS /* iOS 11 does not support system() */
ignore = system(buf); /* gnuplot || wgnuplot */
#endif /* !OS_IOS */
LEPT_FREE(cmdname);
return 0;
}
Commit Message: Security fixes: expect final changes for release 1.75.3.
* Fixed a debian security issue with fscanf() reading a string with
possible buffer overflow.
* There were also a few similar situations with sscanf().
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int rose_parse_ccitt(unsigned char *p, struct rose_facilities_struct *facilities, int len)
{
unsigned char l, n = 0;
char callsign[11];
do {
switch (*p & 0xC0) {
case 0x00:
p += 2;
n += 2;
len -= 2;
break;
case 0x40:
p += 3;
n += 3;
len -= 3;
break;
case 0x80:
p += 4;
n += 4;
len -= 4;
break;
case 0xC0:
l = p[1];
if (*p == FAC_CCITT_DEST_NSAP) {
memcpy(&facilities->source_addr, p + 7, ROSE_ADDR_LEN);
memcpy(callsign, p + 12, l - 10);
callsign[l - 10] = '\0';
asc2ax(&facilities->source_call, callsign);
}
if (*p == FAC_CCITT_SRC_NSAP) {
memcpy(&facilities->dest_addr, p + 7, ROSE_ADDR_LEN);
memcpy(callsign, p + 12, l - 10);
callsign[l - 10] = '\0';
asc2ax(&facilities->dest_call, callsign);
}
p += l + 2;
n += l + 2;
len -= l + 2;
break;
}
} while (*p != 0x00 && len > 0);
return n;
}
Commit Message: ROSE: prevent heap corruption with bad facilities
When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for
a remote host to provide more digipeaters than expected, resulting in
heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and
abort facilities parsing on failure.
Additionally, when parsing the FAC_CCITT_DEST_NSAP and
FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length
of less than 10, resulting in an underflow in a memcpy size, causing a
kernel panic due to massive heap corruption. A length of greater than
20 results in a stack overflow of the callsign array. Abort facilities
parsing on these invalid length values.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int nfs3svc_decode_getaclargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_getaclargs *args)
{
p = nfs3svc_decode_fh(p, &args->fh);
if (!p)
return 0;
args->mask = ntohl(*p); p++;
return xdr_argsize_check(rqstp, p);
}
Commit Message: nfsd: check permissions when setting ACLs
Use set_posix_acl, which includes proper permission checks, instead of
calling ->set_acl directly. Without this anyone may be able to grant
themselves permissions to a file by setting the ACL.
Lock the inode to make the new checks atomic with respect to set_acl.
(Also, nfsd was the only caller of set_acl not locking the inode, so I
suspect this may fix other races.)
This also simplifies the code, and ensures our ACLs are checked by
posix_acl_valid.
The permission checks and the inode locking were lost with commit
4ac7249e, which changed nfsd to use the set_acl inode operation directly
instead of going through xattr handlers.
Reported-by: David Sinquin <[email protected]>
[[email protected]: use set_posix_acl]
Fixes: 4ac7249e
Cc: Christoph Hellwig <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-284
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: matchCurrentInput(
const InString *input, int pos, const widechar *passInstructions, int passIC) {
int k;
int kk = pos;
for (k = passIC + 2; k < passIC + 2 + passInstructions[passIC + 1]; k++)
if (input->chars[kk] == ENDSEGMENT || passInstructions[k] != input->chars[kk++])
return 0;
return 1;
}
Commit Message: Fix a buffer overflow
Fixes #635
Thanks to HongxuChen for reporting it
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int read_uids_guids(long long *table_start)
{
int res, i;
int bytes = SQUASHFS_ID_BYTES(sBlk.s.no_ids);
int indexes = SQUASHFS_ID_BLOCKS(sBlk.s.no_ids);
long long id_index_table[indexes];
TRACE("read_uids_guids: no_ids %d\n", sBlk.s.no_ids);
id_table = malloc(bytes);
if(id_table == NULL) {
ERROR("read_uids_guids: failed to allocate id table\n");
return FALSE;
}
res = read_fs_bytes(fd, sBlk.s.id_table_start,
SQUASHFS_ID_BLOCK_BYTES(sBlk.s.no_ids), id_index_table);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id index table\n");
return FALSE;
}
SQUASHFS_INSWAP_ID_BLOCKS(id_index_table, indexes);
/*
* id_index_table[0] stores the start of the compressed id blocks.
* This by definition is also the end of the previous filesystem
* table - this may be the exports table if it is present, or the
* fragments table if it isn't.
*/
*table_start = id_index_table[0];
for(i = 0; i < indexes; i++) {
int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
bytes & (SQUASHFS_METADATA_SIZE - 1);
res = read_block(fd, id_index_table[i], NULL, expected,
((char *) id_table) + i * SQUASHFS_METADATA_SIZE);
if(res == FALSE) {
ERROR("read_uids_guids: failed to read id table block"
"\n");
return FALSE;
}
}
SQUASHFS_INSWAP_INTS(id_table, sBlk.s.no_ids);
return TRUE;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190
Target: 1
Example 2:
Code: static inline bool cpu_has_vmx_tsc_scaling(void)
{
return vmcs_config.cpu_based_2nd_exec_ctrl &
SECONDARY_EXEC_TSC_SCALING;
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebGL2RenderingContextBase::samplerParameterf(WebGLSampler* sampler,
GLenum pname,
GLfloat param) {
SamplerParameter(sampler, pname, param, 0, true);
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int __gfs2_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
int len;
char *data;
const char *name = gfs2_acl_name(type);
if (acl && acl->a_count > GFS2_ACL_MAX_ENTRIES(GFS2_SB(inode)))
return -E2BIG;
if (type == ACL_TYPE_ACCESS) {
umode_t mode = inode->i_mode;
error = posix_acl_equiv_mode(acl, &mode);
if (error < 0)
return error;
if (error == 0)
acl = NULL;
if (mode != inode->i_mode) {
inode->i_mode = mode;
mark_inode_dirty(inode);
}
}
if (acl) {
len = posix_acl_to_xattr(&init_user_ns, acl, NULL, 0);
if (len == 0)
return 0;
data = kmalloc(len, GFP_NOFS);
if (data == NULL)
return -ENOMEM;
error = posix_acl_to_xattr(&init_user_ns, acl, data, len);
if (error < 0)
goto out;
} else {
data = NULL;
len = 0;
}
error = __gfs2_xattr_set(inode, name, data, len, 0, GFS2_EATYPE_SYS);
if (error)
goto out;
set_cached_acl(inode, type, acl);
out:
kfree(data);
return error;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285
Target: 1
Example 2:
Code: static bool bond_addr_in_mc_list(unsigned char *addr,
struct netdev_hw_addr_list *list,
int addrlen)
{
struct netdev_hw_addr *ha;
netdev_hw_addr_list_for_each(ha, list)
if (!memcmp(ha->addr, addr, addrlen))
return true;
return false;
}
Commit Message: net: Audit drivers to identify those needing IFF_TX_SKB_SHARING cleared
After the last patch, We are left in a state in which only drivers calling
ether_setup have IFF_TX_SKB_SHARING set (we assume that drivers touching real
hardware call ether_setup for their net_devices and don't hold any state in
their skbs. There are a handful of drivers that violate this assumption of
course, and need to be fixed up. This patch identifies those drivers, and marks
them as not being able to support the safe transmission of skbs by clearning the
IFF_TX_SKB_SHARING flag in priv_flags
Signed-off-by: Neil Horman <[email protected]>
CC: Karsten Keil <[email protected]>
CC: "David S. Miller" <[email protected]>
CC: Jay Vosburgh <[email protected]>
CC: Andy Gospodarek <[email protected]>
CC: Patrick McHardy <[email protected]>
CC: Krzysztof Halasa <[email protected]>
CC: "John W. Linville" <[email protected]>
CC: Greg Kroah-Hartman <[email protected]>
CC: Marcel Holtmann <[email protected]>
CC: Johannes Berg <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: on_handler_vanished(GDBusConnection *connection,
const gchar *name,
gpointer user_data)
{
struct tcmur_handler *handler = user_data;
struct dbus_info *info = handler->opaque;
if (info->register_invocation) {
char *reason;
reason = g_strdup_printf("Cannot find handler bus name: "
"org.kernel.TCMUService1.HandlerManager1.%s",
handler->subtype);
g_dbus_method_invocation_return_value(info->register_invocation,
g_variant_new("(bs)", FALSE, reason));
g_free(reason);
}
tcmur_unregister_handler(handler);
dbus_unexport_handler(handler);
}
Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS
Trying to unregister an internal handler ended up in a SEGFAULT, because
the tcmur_handler->opaque was NULL. Way to reproduce:
dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow
we use a newly introduced boolean in struct tcmur_handler for keeping
track of external handlers. As suggested by mikechristie adjusting the
public data structure is acceptable.
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DownloadController::StartAndroidDownload(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
WebContents* web_contents = wc_getter.Run();
if (!web_contents) {
LOG(ERROR) << "Download failed on URL:" << info.url.spec();
return;
}
AcquireFileAccessPermission(
web_contents,
base::Bind(&DownloadController::StartAndroidDownloadInternal,
base::Unretained(this), wc_getter, must_download, info));
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static void trace_packet(struct net *net,
const struct sk_buff *skb,
unsigned int hook,
const struct net_device *in,
const struct net_device *out,
const char *tablename,
const struct xt_table_info *private,
const struct ipt_entry *e)
{
const struct ipt_entry *root;
const char *hookname, *chainname, *comment;
const struct ipt_entry *iter;
unsigned int rulenum = 0;
root = get_entry(private->entries, private->hook_entry[hook]);
hookname = chainname = hooknames[hook];
comment = comments[NF_IP_TRACE_COMMENT_RULE];
xt_entry_foreach(iter, root, private->size - private->hook_entry[hook])
if (get_chainname_rulenum(iter, e, hookname,
&chainname, &comment, &rulenum) != 0)
break;
nf_log_trace(net, AF_INET, hook, skb, in, out, &trace_loginfo,
"TRACE: %s:%s:%s:%u ",
tablename, chainname, comment, rulenum);
}
Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size
Otherwise this function may read data beyond the ruleset blob.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void DBusHelperProxy::stopAction(const QString &action, const QString &helperID)
{
QDBusMessage message;
message = QDBusMessage::createMethodCall(helperID, QLatin1String("/"), QLatin1String("org.kde.kf5auth"), QLatin1String("stopAction"));
QList<QVariant> args;
args << action;
message.setArguments(args);
m_busConnection.asyncCall(message);
}
Commit Message:
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string TemplateURLRef::HandleReplacements(
const SearchTermsArgs& search_terms_args,
const SearchTermsData& search_terms_data,
PostContent* post_content) const {
if (replacements_.empty()) {
if (!post_params_.empty())
EncodeFormData(post_params_, post_content);
return parsed_url_;
}
bool is_in_query = true;
for (Replacements::iterator i = replacements_.begin();
i != replacements_.end(); ++i) {
if (i->type == SEARCH_TERMS) {
base::string16::size_type query_start = parsed_url_.find('?');
is_in_query = query_start != base::string16::npos &&
(static_cast<base::string16::size_type>(i->index) > query_start);
break;
}
}
std::string input_encoding;
base::string16 encoded_terms;
base::string16 encoded_original_query;
owner_->EncodeSearchTerms(search_terms_args, is_in_query, &input_encoding,
&encoded_terms, &encoded_original_query);
std::string url = parsed_url_;
for (Replacements::reverse_iterator i = replacements_.rbegin();
i != replacements_.rend(); ++i) {
switch (i->type) {
case ENCODING:
HandleReplacement(std::string(), input_encoding, *i, &url);
break;
case GOOGLE_ASSISTED_QUERY_STATS:
DCHECK(!i->is_post_param);
if (!search_terms_args.assisted_query_stats.empty()) {
SearchTermsArgs search_terms_args_without_aqs(search_terms_args);
search_terms_args_without_aqs.assisted_query_stats.clear();
GURL base_url(ReplaceSearchTerms(
search_terms_args_without_aqs, search_terms_data, NULL));
if (base_url.SchemeIsCryptographic()) {
HandleReplacement(
"aqs", search_terms_args.assisted_query_stats, *i, &url);
}
}
break;
case GOOGLE_BASE_URL:
DCHECK(!i->is_post_param);
HandleReplacement(
std::string(), search_terms_data.GoogleBaseURLValue(), *i, &url);
break;
case GOOGLE_BASE_SUGGEST_URL:
DCHECK(!i->is_post_param);
HandleReplacement(
std::string(), search_terms_data.GoogleBaseSuggestURLValue(), *i,
&url);
break;
case GOOGLE_CURRENT_PAGE_URL:
DCHECK(!i->is_post_param);
if (!search_terms_args.current_page_url.empty()) {
const std::string& escaped_current_page_url =
net::EscapeQueryParamValue(search_terms_args.current_page_url,
true);
HandleReplacement("url", escaped_current_page_url, *i, &url);
}
break;
case GOOGLE_CURSOR_POSITION:
DCHECK(!i->is_post_param);
if (search_terms_args.cursor_position != base::string16::npos)
HandleReplacement(
"cp",
base::StringPrintf("%" PRIuS, search_terms_args.cursor_position),
*i,
&url);
break;
case GOOGLE_FORCE_INSTANT_RESULTS:
DCHECK(!i->is_post_param);
HandleReplacement(std::string(),
search_terms_data.ForceInstantResultsParam(
search_terms_args.force_instant_results),
*i,
&url);
break;
case GOOGLE_INPUT_TYPE:
DCHECK(!i->is_post_param);
HandleReplacement(
"oit", base::IntToString(search_terms_args.input_type), *i, &url);
break;
case GOOGLE_INSTANT_EXTENDED_ENABLED:
DCHECK(!i->is_post_param);
HandleReplacement(std::string(),
search_terms_data.InstantExtendedEnabledParam(
type_ == SEARCH),
*i,
&url);
break;
case GOOGLE_CONTEXTUAL_SEARCH_VERSION:
if (search_terms_args.contextual_search_params.version >= 0) {
HandleReplacement(
"ctxs",
base::IntToString(
search_terms_args.contextual_search_params.version),
*i,
&url);
}
break;
case GOOGLE_CONTEXTUAL_SEARCH_CONTEXT_DATA: {
DCHECK(!i->is_post_param);
std::string context_data;
const SearchTermsArgs::ContextualSearchParams& params =
search_terms_args.contextual_search_params;
if (params.start != std::string::npos) {
context_data.append("ctxs_start=" +
base::SizeTToString(params.start) + "&");
}
if (params.end != std::string::npos) {
context_data.append("ctxs_end=" +
base::SizeTToString(params.end) + "&");
}
if (!params.selection.empty())
context_data.append("q=" + params.selection + "&");
if (!params.content.empty())
context_data.append("ctxs_content=" + params.content + "&");
if (!params.base_page_url.empty())
context_data.append("ctxsl_url=" + params.base_page_url + "&");
if (!params.encoding.empty()) {
context_data.append("ctxs_encoding=" + params.encoding + "&");
}
context_data.append("ctxsl_coca=" +
base::IntToString(params.now_on_tap_version));
HandleReplacement(std::string(), context_data, *i, &url);
break;
}
case GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION:
DCHECK(!i->is_post_param);
if (search_terms_args.accepted_suggestion >= 0 ||
!search_terms_args.assisted_query_stats.empty()) {
HandleReplacement(
"oq", base::UTF16ToUTF8(encoded_original_query), *i, &url);
}
break;
case GOOGLE_PAGE_CLASSIFICATION:
if (search_terms_args.page_classification !=
metrics::OmniboxEventProto::INVALID_SPEC) {
HandleReplacement(
"pgcl", base::IntToString(search_terms_args.page_classification),
*i, &url);
}
break;
case GOOGLE_PREFETCH_QUERY: {
const std::string& query = search_terms_args.prefetch_query;
const std::string& type = search_terms_args.prefetch_query_type;
if (!query.empty() && !type.empty()) {
HandleReplacement(
std::string(), "pfq=" + query + "&qha=" + type + "&", *i, &url);
}
break;
}
case GOOGLE_RLZ: {
DCHECK(!i->is_post_param);
base::string16 rlz_string = search_terms_data.GetRlzParameterValue(
search_terms_args.from_app_list);
if (!rlz_string.empty()) {
HandleReplacement("rlz", base::UTF16ToUTF8(rlz_string), *i, &url);
}
break;
}
case GOOGLE_SEARCH_CLIENT: {
DCHECK(!i->is_post_param);
std::string client = search_terms_data.GetSearchClient();
if (!client.empty())
HandleReplacement("client", client, *i, &url);
break;
}
case GOOGLE_SEARCH_FIELDTRIAL_GROUP:
break;
case GOOGLE_SEARCH_VERSION:
HandleReplacement("gs_rn", "42", *i, &url);
break;
case GOOGLE_SESSION_TOKEN: {
std::string token = search_terms_args.session_token;
if (!token.empty())
HandleReplacement("psi", token, *i, &url);
break;
}
case GOOGLE_SUGGEST_CLIENT:
HandleReplacement(
std::string(), search_terms_data.GetSuggestClient(), *i, &url);
break;
case GOOGLE_SUGGEST_REQUEST_ID:
HandleReplacement(
std::string(), search_terms_data.GetSuggestRequestIdentifier(), *i,
&url);
break;
case GOOGLE_UNESCAPED_SEARCH_TERMS: {
std::string unescaped_terms;
base::UTF16ToCodepage(search_terms_args.search_terms,
input_encoding.c_str(),
base::OnStringConversionError::SKIP,
&unescaped_terms);
HandleReplacement(std::string(), unescaped_terms, *i, &url);
break;
}
case LANGUAGE:
HandleReplacement(
std::string(), search_terms_data.GetApplicationLocale(), *i, &url);
break;
case SEARCH_TERMS:
HandleReplacement(
std::string(), base::UTF16ToUTF8(encoded_terms), *i, &url);
break;
case GOOGLE_IMAGE_THUMBNAIL:
HandleReplacement(
std::string(), search_terms_args.image_thumbnail_content, *i, &url);
post_params_[i->index].content_type = "image/jpeg";
break;
case GOOGLE_IMAGE_URL:
if (search_terms_args.image_url.is_valid()) {
HandleReplacement(
std::string(), search_terms_args.image_url.spec(), *i, &url);
}
break;
case GOOGLE_IMAGE_ORIGINAL_WIDTH:
if (!search_terms_args.image_original_size.IsEmpty()) {
HandleReplacement(
std::string(),
base::IntToString(search_terms_args.image_original_size.width()),
*i, &url);
}
break;
case GOOGLE_IMAGE_ORIGINAL_HEIGHT:
if (!search_terms_args.image_original_size.IsEmpty()) {
HandleReplacement(
std::string(),
base::IntToString(search_terms_args.image_original_size.height()),
*i, &url);
}
break;
case GOOGLE_IMAGE_SEARCH_SOURCE:
HandleReplacement(
std::string(), search_terms_data.GoogleImageSearchSource(), *i,
&url);
break;
case GOOGLE_IOS_SEARCH_LANGUAGE:
#if defined(OS_IOS)
HandleReplacement("hl", search_terms_data.GetApplicationLocale(), *i,
&url);
#endif
break;
default:
NOTREACHED();
break;
}
}
if (!post_params_.empty())
EncodeFormData(post_params_, post_content);
return url;
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
Target: 1
Example 2:
Code: static int read_download_mem(struct usb_device *dev, int start_address,
int length, __u8 address_type, __u8 *buffer)
{
int status = 0;
__u8 read_length;
u16 be_start_address;
dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, length);
/*
* Read in blocks of 64 bytes
* (TI firmware can't handle more than 64 byte reads)
*/
while (length) {
if (length > 64)
read_length = 64;
else
read_length = (__u8)length;
if (read_length > 1) {
dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, read_length);
}
/*
* NOTE: Must use swab as wIndex is sent in little-endian
* byte order regardless of host byte order.
*/
be_start_address = swab16((u16)start_address);
status = ti_vread_sync(dev, UMPC_MEMORY_READ,
(__u16)address_type,
be_start_address,
buffer, read_length);
if (status) {
dev_dbg(&dev->dev, "%s - ERROR %x\n", __func__, status);
return status;
}
if (read_length > 1)
usb_serial_debug_data(&dev->dev, __func__, read_length, buffer);
/* Update pointers/length */
start_address += read_length;
buffer += read_length;
length -= read_length;
}
return status;
}
Commit Message: USB: serial: io_ti: fix information leak in completion handler
Add missing sanity check to the bulk-in completion handler to avoid an
integer underflow that can be triggered by a malicious device.
This avoids leaking 128 kB of memory content from after the URB transfer
buffer to user space.
Fixes: 8c209e6782ca ("USB: make actual_length in struct urb field u32")
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable <[email protected]> # 2.6.30
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-191
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int parse_index(git_index *index, const char *buffer, size_t buffer_size)
{
int error = 0;
unsigned int i;
struct index_header header = { 0 };
git_oid checksum_calculated, checksum_expected;
const char *last = NULL;
const char *empty = "";
#define seek_forward(_increase) { \
if (_increase >= buffer_size) { \
error = index_error_invalid("ran out of data while parsing"); \
goto done; } \
buffer += _increase; \
buffer_size -= _increase;\
}
if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE)
return index_error_invalid("insufficient buffer space");
/* Precalculate the SHA1 of the files's contents -- we'll match it to
* the provided SHA1 in the footer */
git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE);
/* Parse header */
if ((error = read_header(&header, buffer)) < 0)
return error;
index->version = header.version;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = empty;
seek_forward(INDEX_HEADER_SIZE);
assert(!index->entries.length);
if (index->ignore_case)
git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count);
else
git_idxmap_resize(index->entries_map, header.entry_count);
/* Parse all the entries */
for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) {
git_index_entry *entry = NULL;
size_t entry_size = read_entry(&entry, index, buffer, buffer_size, last);
/* 0 bytes read means an object corruption */
if (entry_size == 0) {
error = index_error_invalid("invalid entry");
goto done;
}
if ((error = git_vector_insert(&index->entries, entry)) < 0) {
index_entry_free(entry);
goto done;
}
INSERT_IN_MAP(index, entry, &error);
if (error < 0) {
index_entry_free(entry);
goto done;
}
error = 0;
if (index->version >= INDEX_VERSION_NUMBER_COMP)
last = entry->path;
seek_forward(entry_size);
}
if (i != header.entry_count) {
error = index_error_invalid("header entries changed while parsing");
goto done;
}
/* There's still space for some extensions! */
while (buffer_size > INDEX_FOOTER_SIZE) {
size_t extension_size;
extension_size = read_extension(index, buffer, buffer_size);
/* see if we have read any bytes from the extension */
if (extension_size == 0) {
error = index_error_invalid("extension is truncated");
goto done;
}
seek_forward(extension_size);
}
if (buffer_size != INDEX_FOOTER_SIZE) {
error = index_error_invalid(
"buffer size does not match index footer size");
goto done;
}
/* 160-bit SHA-1 over the content of the index file before this checksum. */
git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer);
if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) {
error = index_error_invalid(
"calculated checksum does not match expected");
goto done;
}
git_oid_cpy(&index->checksum, &checksum_calculated);
#undef seek_forward
/* Entries are stored case-sensitively on disk, so re-sort now if
* in-memory index is supposed to be case-insensitive
*/
git_vector_set_sorted(&index->entries, !index->ignore_case);
git_vector_sort(&index->entries);
done:
return error;
}
Commit Message: index: convert `read_entry` to return entry size via an out-param
The function `read_entry` does not conform to our usual coding style of
returning stuff via the out parameter and to use the return value for
reporting errors. Due to most of our code conforming to that pattern, it
has become quite natural for us to actually return `-1` in case there is
any error, which has also slipped in with commit 5625d86b9 (index:
support index v4, 2016-05-17). As the function returns an `size_t` only,
though, the return value is wrapped around, causing the caller of
`read_tree` to continue with an invalid index entry. Ultimately, this
can lead to a double-free.
Improve code and fix the bug by converting the function to return the
index entry size via an out parameter and only using the return value to
indicate errors.
Reported-by: Krishna Ram Prakash R <[email protected]>
Reported-by: Vivek Parikh <[email protected]>
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
}
Commit Message: xfs: don't call xfs_da_shrink_inode with NULL bp
xfs_attr3_leaf_create may have errored out before instantiating a buffer,
for example if the blkno is out of range. In that case there is no work
to do to remove it, and in fact xfs_da_shrink_inode will lead to an oops
if we try.
This also seems to fix a flaw where the original error from
xfs_attr3_leaf_create gets overwritten in the cleanup case, and it
removes a pointless assignment to bp which isn't used after this.
Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=199969
Reported-by: Xu, Wen <[email protected]>
Tested-by: Xu, Wen <[email protected]>
Signed-off-by: Eric Sandeen <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
Signed-off-by: Darrick J. Wong <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: void FetchContext::DispatchDidDownloadData(unsigned long, int, int) {}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd)
{
PCIDevice *pci_dev = PCI_DEVICE(s);
PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev);
MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s);
struct mfi_ctrl_info info;
size_t dcmd_size = sizeof(info);
BusChild *kid;
int num_pd_disks = 0;
memset(&info, 0x0, dcmd_size);
if (cmd->iov_size < dcmd_size) {
trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size,
dcmd_size);
return MFI_STAT_INVALID_PARAMETER;
}
info.pci.vendor = cpu_to_le16(pci_class->vendor_id);
info.pci.device = cpu_to_le16(pci_class->device_id);
info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id);
info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id);
/*
* For some reason the firmware supports
* only up to 8 device ports.
* Despite supporting a far larger number
* of devices for the physical devices.
* So just display the first 8 devices
* in the device port list, independent
* of how many logical devices are actually
* present.
*/
info.host.type = MFI_INFO_HOST_PCIE;
info.device.type = MFI_INFO_DEV_SAS3G;
info.device.port_count = 8;
QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) {
SCSIDevice *sdev = SCSI_DEVICE(kid->child);
uint16_t pd_id;
if (num_pd_disks < 8) {
pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF);
info.device.port_addr[num_pd_disks] =
cpu_to_le64(megasas_get_sata_addr(pd_id));
}
num_pd_disks++;
}
memcpy(info.product_name, base_class->product_name, 24);
snprintf(info.serial_number, 32, "%s", s->hba_serial);
snprintf(info.package_version, 0x60, "%s-QEMU", qemu_hw_version());
memcpy(info.image_component[0].name, "APP", 3);
snprintf(info.image_component[0].version, 10, "%s-QEMU",
base_class->product_version);
memcpy(info.image_component[0].build_date, "Apr 1 2014", 11);
memcpy(info.image_component[0].build_time, "12:34:56", 8);
info.image_component_count = 1;
if (pci_dev->has_rom) {
uint8_t biosver[32];
uint8_t *ptr;
ptr = memory_region_get_ram_ptr(&pci_dev->rom);
memcpy(biosver, ptr + 0x41, 31);
memcpy(info.image_component[1].name, "BIOS", 4);
memcpy(info.image_component[1].version, biosver,
strlen((const char *)biosver));
}
info.current_fw_time = cpu_to_le32(megasas_fw_time());
info.max_arms = 32;
info.max_spans = 8;
info.max_arrays = MEGASAS_MAX_ARRAYS;
info.max_lds = MFI_MAX_LD;
info.max_cmds = cpu_to_le16(s->fw_cmds);
info.max_sg_elements = cpu_to_le16(s->fw_sge);
info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS);
if (!megasas_is_jbod(s))
info.lds_present = cpu_to_le16(num_pd_disks);
info.pd_present = cpu_to_le16(num_pd_disks);
info.pd_disks_present = cpu_to_le16(num_pd_disks);
info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM |
MFI_INFO_HW_MEM |
MFI_INFO_HW_FLASH);
info.memory_size = cpu_to_le16(512);
info.nvram_size = cpu_to_le16(32);
info.flash_size = cpu_to_le16(16);
info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0);
info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE |
MFI_INFO_AOPS_SELF_DIAGNOSTIC |
MFI_INFO_AOPS_MIXED_ARRAY);
info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY |
MFI_INFO_LDOPS_ACCESS_POLICY |
MFI_INFO_LDOPS_IO_POLICY |
MFI_INFO_LDOPS_WRITE_POLICY |
MFI_INFO_LDOPS_READ_POLICY);
info.max_strips_per_io = cpu_to_le16(s->fw_sge);
info.stripe_sz_ops.min = 3;
info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1);
info.properties.pred_fail_poll_interval = cpu_to_le16(300);
info.properties.intr_throttle_cnt = cpu_to_le16(16);
info.properties.intr_throttle_timeout = cpu_to_le16(50);
info.properties.rebuild_rate = 30;
info.properties.patrol_read_rate = 30;
info.properties.bgi_rate = 30;
info.properties.cc_rate = 30;
info.properties.recon_rate = 30;
info.properties.cache_flush_interval = 4;
info.properties.spinup_drv_cnt = 2;
info.properties.spinup_delay = 6;
info.properties.ecc_bucket_size = 15;
info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440);
info.properties.expose_encl_devices = 1;
info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD);
info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE |
MFI_INFO_PDOPS_FORCE_OFFLINE);
info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS |
MFI_INFO_PDMIX_SATA |
MFI_INFO_PDMIX_LD);
cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg);
return MFI_STAT_OK;
}
Commit Message:
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: generate_palette(png_colorp palette, png_bytep trans, int bit_depth,
png_const_bytep gamma_table, unsigned int *colors)
{
/*
* 1-bit: entry 0 is transparent-red, entry 1 is opaque-white
* 2-bit: entry 0: transparent-green
* entry 1: 40%-red
* entry 2: 80%-blue
* entry 3: opaque-white
* 4-bit: the 16 combinations of the 2-bit case
* 8-bit: the 256 combinations of the 4-bit case
*/
switch (colors[0])
{
default:
fprintf(stderr, "makepng: --colors=...: invalid count %u\n",
colors[0]);
exit(1);
case 1:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1], 255,
gamma_table);
return 1;
case 2:
set_color(palette+0, trans+0, colors[1], colors[1], colors[1],
colors[2], gamma_table);
return 1;
case 3:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3], 255,
gamma_table);
return 1;
case 4:
set_color(palette+0, trans+0, colors[1], colors[2], colors[3],
colors[4], gamma_table);
return 1;
case 0:
if (bit_depth == 1)
{
set_color(palette+0, trans+0, 255, 0, 0, 0, gamma_table);
set_color(palette+1, trans+1, 255, 255, 255, 255, gamma_table);
return 2;
}
else
{
unsigned int size = 1U << (bit_depth/2); /* 2, 4 or 16 */
unsigned int x, y, ip;
for (x=0; x<size; ++x) for (y=0; y<size; ++y)
{
ip = x + (size * y);
/* size is at most 16, so the scaled value below fits in 16 bits
*/
# define interp(pos, c1, c2) ((pos * c1) + ((size-pos) * c2))
# define xyinterp(x, y, c1, c2, c3, c4) (((size * size / 2) +\
(interp(x, c1, c2) * y + (size-y) * interp(x, c3, c4))) /\
(size*size))
set_color(palette+ip, trans+ip,
/* color: green, red,blue,white */
xyinterp(x, y, 0, 255, 0, 255),
xyinterp(x, y, 255, 0, 0, 255),
xyinterp(x, y, 0, 0, 255, 255),
/* alpha: 0, 102, 204, 255) */
xyinterp(x, y, 0, 102, 204, 255),
gamma_table);
}
return ip+1;
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: void NavigationRequest::CreateNavigationHandle() {
DCHECK_EQ(frame_tree_node_->navigation_request(), this);
FrameTreeNode* frame_tree_node = frame_tree_node_;
std::vector<GURL> redirect_chain;
if (!begin_params_->client_side_redirect_url.is_empty())
redirect_chain.push_back(begin_params_->client_side_redirect_url);
redirect_chain.push_back(common_params_.url);
bool is_external_protocol =
!GetContentClient()->browser()->IsHandledURL(common_params_.url);
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(begin_params_->headers);
std::unique_ptr<NavigationHandleImpl> navigation_handle =
NavigationHandleImpl::Create(
common_params_.url, redirect_chain, frame_tree_node_,
!browser_initiated_,
FrameMsg_Navigate_Type::IsSameDocument(
common_params_.navigation_type),
common_params_.navigation_start, nav_entry_id_,
common_params_.started_from_context_menu,
common_params_.should_check_main_world_csp,
begin_params_->is_form_submission, common_params_.suggested_filename,
std::move(navigation_ui_data_), common_params_.method,
std::move(headers), common_params_.post_data,
Referrer::SanitizeForRequest(common_params_.url,
common_params_.referrer),
common_params_.has_user_gesture, common_params_.transition,
is_external_protocol, begin_params_->request_context_type,
begin_params_->mixed_content_context_type);
if (!frame_tree_node->navigation_request()) {
return;
}
navigation_handle_ = std::move(navigation_handle);
if (!begin_params_->searchable_form_url.is_empty()) {
navigation_handle_->set_searchable_form_url(
begin_params_->searchable_form_url);
navigation_handle_->set_searchable_form_encoding(
begin_params_->searchable_form_encoding);
}
if (common_params_.source_location) {
navigation_handle_->set_source_location(
common_params_.source_location.value());
}
}
Commit Message: Check ancestors when setting an <iframe> navigation's "site for cookies".
Currently, we're setting the "site for cookies" only by looking at the
top-level document. We ought to be verifying that the ancestor frames
are same-site before doing so. We do this correctly in Blink (see
`Document::SiteForCookies`), but didn't do so when navigating in the
browser.
This patch addresses the majority of the problem by walking the ancestor
chain when processing a NavigationRequest. If all the ancestors are
same-site, we set the "site for cookies" to the top-level document's URL.
If they aren't all same-site, we set it to an empty URL to ensure that
we don't send SameSite cookies.
Bug: 833847
Change-Id: Icd77f31fa618fa9f8b59fc3b15e1bed6ee05aabd
Reviewed-on: https://chromium-review.googlesource.com/1025772
Reviewed-by: Alex Moshchuk <[email protected]>
Commit-Queue: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#553942}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: status_t CameraClient::cancelAutoFocus() {
LOG1("cancelAutoFocus (pid %d)", getCallingPid());
Mutex::Autolock lock(mLock);
status_t result = checkPidAndHardware();
if (result != NO_ERROR) return result;
return mHardware->cancelAutoFocus();
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void DevToolsWindow::InspectedContentsClosing() {
web_contents_->GetRenderViewHost()->ClosePage();
}
Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception
This patch fixes the crash which happenes under the following conditions:
1. DevTools window is in undocked state
2. DevTools renderer is unresponsive
3. User attempts to close inspected page
BUG=322380
Review URL: https://codereview.chromium.org/84883002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: PaintLayer* PaintLayerScrollableArea::Layer() const {
return layer_;
}
Commit Message: Always call UpdateCompositedScrollOffset, not just for the root layer
Bug: 927560
Change-Id: I1d5522aae4f11dd3f5b8947bb089bac1bf19bdb4
Reviewed-on: https://chromium-review.googlesource.com/c/1452701
Reviewed-by: Chris Harrelson <[email protected]>
Commit-Queue: Mason Freed <[email protected]>
Cr-Commit-Position: refs/heads/master@{#628942}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int may_delete(struct inode *dir,struct dentry *victim,int isdir)
{
int error;
if (!victim->d_inode)
return -ENOENT;
BUG_ON(victim->d_parent->d_inode != dir);
audit_inode_child(victim->d_name.name, victim, dir);
error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
if (error)
return error;
if (IS_APPEND(dir))
return -EPERM;
if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
return -EPERM;
if (isdir) {
if (!S_ISDIR(victim->d_inode->i_mode))
return -ENOTDIR;
if (IS_ROOT(victim))
return -EBUSY;
} else if (S_ISDIR(victim->d_inode->i_mode))
return -EISDIR;
if (IS_DEADDIR(dir))
return -ENOENT;
if (victim->d_flags & DCACHE_NFSFS_RENAMED)
return -EBUSY;
return 0;
}
Commit Message: fix autofs/afs/etc. magic mountpoint breakage
We end up trying to kfree() nd.last.name on open("/mnt/tmp", O_CREAT)
if /mnt/tmp is an autofs direct mount. The reason is that nd.last_type
is bogus here; we want LAST_BIND for everything of that kind and we
get LAST_NORM left over from finding parent directory.
So make sure that it *is* set properly; set to LAST_BIND before
doing ->follow_link() - for normal symlinks it will be changed
by __vfs_follow_link() and everything else needs it set that way.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
{
char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
char url_address[256], port[6];
int url_len, port_len = 0;
*sockaddr_url = url;
url_begin = strstr(url, "//");
if (!url_begin)
url_begin = url;
else
url_begin += 2;
/* Look for numeric ipv6 entries */
ipv6_begin = strstr(url_begin, "[");
ipv6_end = strstr(url_begin, "]");
if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
url_end = strstr(ipv6_end, ":");
else
url_end = strstr(url_begin, ":");
if (url_end) {
url_len = url_end - url_begin;
port_len = strlen(url_begin) - url_len - 1;
if (port_len < 1)
return false;
port_start = url_end + 1;
} else
url_len = strlen(url_begin);
if (url_len < 1)
return false;
sprintf(url_address, "%.*s", url_len, url_begin);
if (port_len) {
char *slash;
snprintf(port, 6, "%.*s", port_len, port_start);
slash = strchr(port, '/');
if (slash)
*slash = '\0';
} else
strcpy(port, "80");
*sockaddr_port = strdup(port);
*sockaddr_url = strdup(url_address);
return true;
}
Commit Message: Do some random sanity checking for stratum message parsing
CWE ID: CWE-119
Target: 1
Example 2:
Code: DrawingBuffer::GpuMemoryBufferColorBufferParameters() {
#if defined(OS_MACOSX)
ColorBufferParameters parameters;
parameters.target = GC3D_TEXTURE_RECTANGLE_ARB;
if (want_alpha_channel_) {
parameters.allocate_alpha_channel = true;
} else if (ContextProvider()
->GetCapabilities()
.chromium_image_rgb_emulation) {
parameters.allocate_alpha_channel = false;
} else {
parameters.allocate_alpha_channel =
DefaultBufferRequiresAlphaChannelToBePreserved();
}
return parameters;
#else
return TextureColorBufferParameters();
#endif
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data)
{
int j, k;
char dump_array[40];
unsigned char bitset;
if (dumpfile == NULL)
{
TIFFError ("", "Invalid FILE pointer for dump file");
return (1);
}
if (format == DUMP_TEXT)
{
fprintf (dumpfile," %s ", dump_tag);
for (j = 0, k = 31; k >= 0; j++, k--)
{
bitset = data & (((uint32)1 << k)) ? 1 : 0;
sprintf(&dump_array[j], (bitset) ? "1" : "0");
if ((k % 8) == 0)
sprintf(&dump_array[++j], " ");
}
dump_array[35] = '\0';
fprintf (dumpfile," %s\n", dump_array);
}
else
{
if ((fwrite (&data, 4, 1, dumpfile)) != 4)
{
TIFFError ("", "Unable to write binary data to dump file");
return (1);
}
}
return (0);
}
Commit Message: * tools/tiffcrop.c: fix out-of-bound read of up to 3 bytes in
readContigTilesIntoBuffer(). Reported as MSVR 35092 by Axel Souchet
& Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void * calloc(size_t n, size_t lb)
{
if (lb && n > GC_SIZE_MAX / lb)
return NULL;
# if defined(GC_LINUX_THREADS) /* && !defined(USE_PROC_FOR_LIBRARIES) */
/* libpthread allocated some memory that is only pointed to by */
/* mmapped thread stacks. Make sure it's not collectable. */
{
static GC_bool lib_bounds_set = FALSE;
ptr_t caller = (ptr_t)__builtin_return_address(0);
/* This test does not need to ensure memory visibility, since */
/* the bounds will be set when/if we create another thread. */
if (!EXPECT(lib_bounds_set, TRUE)) {
GC_init_lib_bounds();
lib_bounds_set = TRUE;
}
if (((word)caller >= (word)GC_libpthread_start
&& (word)caller < (word)GC_libpthread_end)
|| ((word)caller >= (word)GC_libld_start
&& (word)caller < (word)GC_libld_end))
return GC_malloc_uncollectable(n*lb);
/* The two ranges are actually usually adjacent, so there may */
/* be a way to speed this up. */
}
# endif
return((void *)REDIRECT_MALLOC(n*lb));
}
Commit Message: Speedup calloc size overflow check by preventing division if small values
* malloc.c (GC_SQRT_SIZE_MAX): New macro.
* malloc.c (calloc): Add fast initial size overflow check to avoid
integer division for reasonably small values passed.
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
double MaxVal,ExceptionInfo *exception)
{
double f;
int x;
register Quantum *q;
if (MinVal >= 0)
MinVal = -1;
if (MaxVal <= 0)
MaxVal = 1;
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (Quantum *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelRed(image,q));
if ((f+GetPixelRed(image,q)) < QuantumRange)
SetPixelRed(image,GetPixelRed(image,q)+ClampToQuantum(f),q);
else
SetPixelRed(image,QuantumRange,q);
f/=2.0;
if (f < GetPixelGreen(image,q))
{
SetPixelBlue(image,GetPixelBlue(image,q)-ClampToQuantum(f),q);
SetPixelGreen(image,GetPixelBlue(image,q),q);
}
else
{
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
}
}
if (*p < 0)
{
f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelBlue(image,q));
if ((f+GetPixelBlue(image,q)) < QuantumRange)
SetPixelBlue(image,GetPixelBlue(image,q)+ClampToQuantum(f),q);
else
SetPixelBlue(image,QuantumRange,q);
f/=2.0;
if (f < GetPixelGreen(image,q))
{
SetPixelRed(image,GetPixelRed(image,q)-ClampToQuantum(f),q);
SetPixelGreen(image,GetPixelRed(image,q),q);
}
else
{
SetPixelGreen(image,0,q);
SetPixelRed(image,0,q);
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1554
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps || siz->numcomps > 16384) {
return -1;
}
if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) {
jas_eprintf("all tiles are outside the image area\n");
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
Commit Message: Added some missing sanity checks on the data in a SIZ marker segment.
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct rds_connection *__rds_conn_create(struct net *net,
__be32 laddr, __be32 faddr,
struct rds_transport *trans, gfp_t gfp,
int is_outgoing)
{
struct rds_connection *conn, *parent = NULL;
struct hlist_head *head = rds_conn_bucket(laddr, faddr);
struct rds_transport *loop_trans;
unsigned long flags;
int ret;
rcu_read_lock();
conn = rds_conn_lookup(net, head, laddr, faddr, trans);
if (conn && conn->c_loopback && conn->c_trans != &rds_loop_transport &&
laddr == faddr && !is_outgoing) {
/* This is a looped back IB connection, and we're
* called by the code handling the incoming connect.
* We need a second connection object into which we
* can stick the other QP. */
parent = conn;
conn = parent->c_passive;
}
rcu_read_unlock();
if (conn)
goto out;
conn = kmem_cache_zalloc(rds_conn_slab, gfp);
if (!conn) {
conn = ERR_PTR(-ENOMEM);
goto out;
}
INIT_HLIST_NODE(&conn->c_hash_node);
conn->c_laddr = laddr;
conn->c_faddr = faddr;
spin_lock_init(&conn->c_lock);
conn->c_next_tx_seq = 1;
rds_conn_net_set(conn, net);
init_waitqueue_head(&conn->c_waitq);
INIT_LIST_HEAD(&conn->c_send_queue);
INIT_LIST_HEAD(&conn->c_retrans);
ret = rds_cong_get_maps(conn);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
/*
* This is where a connection becomes loopback. If *any* RDS sockets
* can bind to the destination address then we'd rather the messages
* flow through loopback rather than either transport.
*/
loop_trans = rds_trans_get_preferred(net, faddr);
if (loop_trans) {
rds_trans_put(loop_trans);
conn->c_loopback = 1;
if (is_outgoing && trans->t_prefer_loopback) {
/* "outgoing" connection - and the transport
* says it wants the connection handled by the
* loopback transport. This is what TCP does.
*/
trans = &rds_loop_transport;
}
}
if (trans == NULL) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(-ENODEV);
goto out;
}
conn->c_trans = trans;
ret = trans->conn_alloc(conn, gfp);
if (ret) {
kmem_cache_free(rds_conn_slab, conn);
conn = ERR_PTR(ret);
goto out;
}
atomic_set(&conn->c_state, RDS_CONN_DOWN);
conn->c_send_gen = 0;
conn->c_outgoing = (is_outgoing ? 1 : 0);
conn->c_reconnect_jiffies = 0;
INIT_DELAYED_WORK(&conn->c_send_w, rds_send_worker);
INIT_DELAYED_WORK(&conn->c_recv_w, rds_recv_worker);
INIT_DELAYED_WORK(&conn->c_conn_w, rds_connect_worker);
INIT_WORK(&conn->c_down_w, rds_shutdown_worker);
mutex_init(&conn->c_cm_lock);
conn->c_flags = 0;
rdsdebug("allocated conn %p for %pI4 -> %pI4 over %s %s\n",
conn, &laddr, &faddr,
trans->t_name ? trans->t_name : "[unknown]",
is_outgoing ? "(outgoing)" : "");
/*
* Since we ran without holding the conn lock, someone could
* have created the same conn (either normal or passive) in the
* interim. We check while holding the lock. If we won, we complete
* init and return our conn. If we lost, we rollback and return the
* other one.
*/
spin_lock_irqsave(&rds_conn_lock, flags);
if (parent) {
/* Creating passive conn */
if (parent->c_passive) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = parent->c_passive;
} else {
parent->c_passive = conn;
rds_cong_add_conn(conn);
rds_conn_count++;
}
} else {
/* Creating normal conn */
struct rds_connection *found;
found = rds_conn_lookup(net, head, laddr, faddr, trans);
if (found) {
trans->conn_free(conn->c_transport_data);
kmem_cache_free(rds_conn_slab, conn);
conn = found;
} else {
hlist_add_head_rcu(&conn->c_hash_node, head);
rds_cong_add_conn(conn);
rds_conn_count++;
}
}
spin_unlock_irqrestore(&rds_conn_lock, flags);
out:
return conn;
}
Commit Message: RDS: fix race condition when sending a message on unbound socket
Sasha's found a NULL pointer dereference in the RDS connection code when
sending a message to an apparently unbound socket. The problem is caused
by the code checking if the socket is bound in rds_sendmsg(), which checks
the rs_bound_addr field without taking a lock on the socket. This opens a
race where rs_bound_addr is temporarily set but where the transport is not
in rds_bind(), leading to a NULL pointer dereference when trying to
dereference 'trans' in __rds_conn_create().
Vegard wrote a reproducer for this issue, so kindly ask him to share if
you're interested.
I cannot reproduce the NULL pointer dereference using Vegard's reproducer
with this patch, whereas I could without.
Complete earlier incomplete fix to CVE-2015-6937:
74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection")
Cc: David S. Miller <[email protected]>
Cc: [email protected]
Reviewed-by: Vegard Nossum <[email protected]>
Reviewed-by: Sasha Levin <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: Quentin Casasnovas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int cfg_keys(struct cryp_ctx *ctx)
{
int i;
int num_of_regs = ctx->keylen / 8;
u32 swapped_key[CRYP_MAX_KEY_SIZE / 4];
int cryp_error = 0;
dev_dbg(ctx->device->dev, "[%s]", __func__);
if (mode_is_aes(ctx->config.algomode)) {
swap_words_in_key_and_bits_in_byte((u8 *)ctx->key,
(u8 *)swapped_key,
ctx->keylen);
} else {
for (i = 0; i < ctx->keylen / 4; i++)
swapped_key[i] = uint8p_to_uint32_be(ctx->key + i*4);
}
for (i = 0; i < num_of_regs; i++) {
cryp_error = set_key(ctx->device,
*(((u32 *)swapped_key)+i*2),
*(((u32 *)swapped_key)+i*2+1),
(enum cryp_key_reg_index) i);
if (cryp_error != 0) {
dev_err(ctx->device->dev, "[%s]: set_key() failed!",
__func__);
return cryp_error;
}
}
return cryp_error;
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
Commit Message: CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV
In isis_print_is_reach_subtlv() one of the case blocks did not check that
the sub-TLV "V" is actually present and could over-read the input buffer.
Add a length check to fix that and remove a useless boundary check from
a loop because the boundary is tested for the full length of "V" before
the switch block.
Update one of the prior test cases as it turns out it depended on this
previously incorrect code path to make it to its own malformed structure
further down the buffer, the bugfix has changed its output.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
that->colour_type = PNG_COLOR_TYPE_GRAY;
else if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA)
that->colour_type = PNG_COLOR_TYPE_RGB;
that->have_tRNS = 0;
that->alphaf = 1;
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: bool ShouldServiceRequest(ProcessType process_type,
int child_id,
const ResourceHostMsg_Request& request_data) {
if (process_type == PROCESS_TYPE_PLUGIN)
return true;
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
if (!policy->CanRequestURL(child_id, request_data.url)) {
VLOG(1) << "Denied unauthorized request for "
<< request_data.url.possibly_invalid_spec();
return false;
}
if (request_data.upload_data) {
const std::vector<net::UploadData::Element>* uploads =
request_data.upload_data->elements();
std::vector<net::UploadData::Element>::const_iterator iter;
for (iter = uploads->begin(); iter != uploads->end(); ++iter) {
if (iter->type() == net::UploadData::TYPE_FILE &&
!policy->CanReadFile(child_id, iter->file_path())) {
NOTREACHED() << "Denied unauthorized upload of "
<< iter->file_path().value();
return false;
}
}
}
return true;
}
Commit Message: Make chrome.appWindow.create() provide access to the child window at a predictable time.
When you first create a window with chrome.appWindow.create(), it won't have
loaded any resources. So, at create time, you are guaranteed that:
child_window.location.href == 'about:blank'
child_window.document.documentElement.outerHTML ==
'<html><head></head><body></body></html>'
This is in line with the behaviour of window.open().
BUG=131735
TEST=browser_tests:PlatformAppBrowserTest.WindowsApi
Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=144072
Review URL: https://chromiumcodereview.appspot.com/10644006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@144356 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct dst_entry *inet6_csk_route_socket(struct sock *sk,
struct flowi6 *fl6)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *final_p, final;
struct dst_entry *dst;
memset(fl6, 0, sizeof(*fl6));
fl6->flowi6_proto = sk->sk_protocol;
fl6->daddr = sk->sk_v6_daddr;
fl6->saddr = np->saddr;
fl6->flowlabel = np->flow_label;
IP6_ECN_flow_xmit(sk, fl6->flowlabel);
fl6->flowi6_oif = sk->sk_bound_dev_if;
fl6->flowi6_mark = sk->sk_mark;
fl6->fl6_sport = inet->inet_sport;
fl6->fl6_dport = inet->inet_dport;
security_sk_classify_flow(sk, flowi6_to_flowi(fl6));
final_p = fl6_update_dst(fl6, np->opt, &final);
dst = __inet6_csk_dst_check(sk, np->dst_cookie);
if (!dst) {
dst = ip6_dst_lookup_flow(sk, fl6, final_p);
if (!IS_ERR(dst))
__inet6_csk_dst_store(sk, dst, NULL, NULL);
}
return dst;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PluginChannel::PluginChannel()
: renderer_handle_(0),
renderer_id_(-1),
in_send_(0),
incognito_(false),
filter_(new MessageFilter()) {
set_send_unblocking_only_during_unblock_dispatch();
ChildProcess::current()->AddRefProcess();
const CommandLine* command_line = CommandLine::ForCurrentProcess();
log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: const struct Curl_handler *Curl_builtin_scheme(const char *scheme)
{
const struct Curl_handler * const *pp;
const struct Curl_handler *p;
/* Scan protocol handler table and match against 'scheme'. The handler may
be changed later when the protocol specific setup function is called. */
for(pp = protocols; (p = *pp) != NULL; pp++)
if(strcasecompare(p->scheme, scheme))
/* Protocol found in table. Check if allowed */
return p;
return NULL; /* not found */
}
Commit Message: Curl_close: clear data->multi_easy on free to avoid use-after-free
Regression from b46cfbc068 (7.59.0)
CVE-2018-16840
Reported-by: Brian Carpenter (Geeknik Labs)
Bug: https://curl.haxx.se/docs/CVE-2018-16840.html
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(mcrypt_get_block_size)
{
char *cipher;
char *module;
int cipher_len, module_len;
char *cipher_dir_string;
char *module_dir_string;
MCRYPT td;
MCRYPT_GET_INI
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
&cipher, &cipher_len, &module, &module_len) == FAILURE) {
return;
}
td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
if (td != MCRYPT_FAILED) {
RETVAL_LONG(mcrypt_enc_get_block_size(td));
mcrypt_module_close(td);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
const gss_OID desired_object,
gss_buffer_set_t *data_set)
{
krb5_gss_ctx_id_rec *ctx;
size_t i;
if (minor_status == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*minor_status = 0;
if (desired_object == GSS_C_NO_OID)
return GSS_S_CALL_INACCESSIBLE_READ;
if (data_set == NULL)
return GSS_S_CALL_INACCESSIBLE_WRITE;
*data_set = GSS_C_NO_BUFFER_SET;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (!ctx->established)
return GSS_S_NO_CONTEXT;
for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/
sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) {
if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) {
return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status,
context_handle,
desired_object,
data_set);
}
}
*minor_status = EINVAL;
return GSS_S_UNAVAILABLE;
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID:
Target: 1
Example 2:
Code: static void efx_ethtool_get_strings(struct net_device *net_dev,
u32 string_set, u8 *strings)
{
struct efx_nic *efx = netdev_priv(net_dev);
struct ethtool_string *ethtool_strings =
(struct ethtool_string *)strings;
int i;
switch (string_set) {
case ETH_SS_STATS:
for (i = 0; i < EFX_ETHTOOL_NUM_STATS; i++)
strncpy(ethtool_strings[i].name,
efx_ethtool_stats[i].name,
sizeof(ethtool_strings[i].name));
break;
case ETH_SS_TEST:
efx_ethtool_fill_self_tests(efx, NULL,
ethtool_strings, NULL);
break;
default:
/* No other string sets */
break;
}
}
Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size
[ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ]
Currently an skb requiring TSO may not fit within a minimum-size TX
queue. The TX queue selected for the skb may stall and trigger the TX
watchdog repeatedly (since the problem skb will be retried after the
TX reset). This issue is designated as CVE-2012-3412.
Set the maximum number of TSO segments for our devices to 100. This
should make no difference to behaviour unless the actual MSS is less
than about 700. Increase the minimum TX queue size accordingly to
allow for 2 worst-case skbs, so that there will definitely be space
to add an skb after we wake a queue.
To avoid invalidating existing configurations, change
efx_ethtool_set_ringparam() to fix up values that are too small rather
than returning -EINVAL.
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
Signed-off-by: Ben Hutchings <[email protected]>
CWE ID: CWE-189
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: test_bson_new_from_buffer (void)
{
bson_t *b;
uint8_t *buf = bson_malloc0 (5);
size_t len = 5;
uint32_t len_le = BSON_UINT32_TO_LE (5);
memcpy (buf, &len_le, sizeof (len_le));
b = bson_new_from_buffer (&buf, &len, bson_realloc_ctx, NULL);
BSON_ASSERT (b->flags & BSON_FLAG_NO_FREE);
BSON_ASSERT (len == 5);
BSON_ASSERT (b->len == 5);
bson_append_utf8 (b, "hello", -1, "world", -1);
BSON_ASSERT (len == 32);
BSON_ASSERT (b->len == 22);
bson_destroy (b);
bson_free (buf);
buf = NULL;
len = 0;
b = bson_new_from_buffer (&buf, &len, bson_realloc_ctx, NULL);
BSON_ASSERT (b->flags & BSON_FLAG_NO_FREE);
BSON_ASSERT (len == 5);
BSON_ASSERT (b->len == 5);
bson_destroy (b);
bson_free (buf);
}
Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read.
As reported here: https://jira.mongodb.org/browse/CDRIVER-2819,
a heap overread occurs due a failure to correctly verify data
bounds.
In the original check, len - o returns the data left including the
sizeof(l) we just read. Instead, the comparison should check
against the data left NOT including the binary int32, i.e. just
subtype (byte*) instead of int32 subtype (byte*).
Added in test for corrupted BSON example.
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: bool PrintWebViewHelper::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PrintWebViewHelper, message)
#if defined(ENABLE_BASIC_PRINTING)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPages, OnPrintPages)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForSystemDialog, OnPrintForSystemDialog)
#endif // ENABLE_BASIC_PRINTING
IPC_MESSAGE_HANDLER(PrintMsg_InitiatePrintPreview, OnInitiatePrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintPreview, OnPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintForPrintPreview, OnPrintForPrintPreview)
IPC_MESSAGE_HANDLER(PrintMsg_PrintingDone, OnPrintingDone)
IPC_MESSAGE_HANDLER(PrintMsg_SetScriptedPrintingBlocked,
SetScriptedPrintBlocked)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
Commit Message: Crash on nested IPC handlers in PrintWebViewHelper
Class is not designed to handle nested IPC. Regular flows also does not
expect them. Still during printing of plugging them may show message
boxes and start nested message loops.
For now we are going just crash. If stats show us that this case is
frequent we will have to do something more complicated.
BUG=502562
Review URL: https://codereview.chromium.org/1228693002
Cr-Commit-Position: refs/heads/master@{#338100}
CWE ID:
Target: 1
Example 2:
Code: static void ib_uverbs_remove_one(struct ib_device *device, void *client_data)
{
struct ib_uverbs_device *uverbs_dev = client_data;
int wait_clients = 1;
if (!uverbs_dev)
return;
cdev_device_del(&uverbs_dev->cdev, &uverbs_dev->dev);
ida_free(&uverbs_ida, uverbs_dev->devnum);
if (device->ops.disassociate_ucontext) {
/* We disassociate HW resources and immediately return.
* Userspace will see a EIO errno for all future access.
* Upon returning, ib_device may be freed internally and is not
* valid any more.
* uverbs_device is still available until all clients close
* their files, then the uverbs device ref count will be zero
* and its resources will be freed.
* Note: At this point no more files can be opened since the
* cdev was deleted, however active clients can still issue
* commands and close their open files.
*/
ib_uverbs_free_hw_resources(uverbs_dev, device);
wait_clients = 0;
}
if (atomic_dec_and_test(&uverbs_dev->refcount))
ib_uverbs_comp_dev(uverbs_dev);
if (wait_clients)
wait_for_completion(&uverbs_dev->comp);
put_device(&uverbs_dev->dev);
}
Commit Message: coredump: fix race condition between mmget_not_zero()/get_task_mm() and core dumping
The core dumping code has always run without holding the mmap_sem for
writing, despite that is the only way to ensure that the entire vma
layout will not change from under it. Only using some signal
serialization on the processes belonging to the mm is not nearly enough.
This was pointed out earlier. For example in Hugh's post from Jul 2017:
https://lkml.kernel.org/r/[email protected]
"Not strictly relevant here, but a related note: I was very surprised
to discover, only quite recently, how handle_mm_fault() may be called
without down_read(mmap_sem) - when core dumping. That seems a
misguided optimization to me, which would also be nice to correct"
In particular because the growsdown and growsup can move the
vm_start/vm_end the various loops the core dump does around the vma will
not be consistent if page faults can happen concurrently.
Pretty much all users calling mmget_not_zero()/get_task_mm() and then
taking the mmap_sem had the potential to introduce unexpected side
effects in the core dumping code.
Adding mmap_sem for writing around the ->core_dump invocation is a
viable long term fix, but it requires removing all copy user and page
faults and to replace them with get_dump_page() for all binary formats
which is not suitable as a short term fix.
For the time being this solution manually covers the places that can
confuse the core dump either by altering the vma layout or the vma flags
while it runs. Once ->core_dump runs under mmap_sem for writing the
function mmget_still_valid() can be dropped.
Allowing mmap_sem protected sections to run in parallel with the
coredump provides some minor parallelism advantage to the swapoff code
(which seems to be safe enough by never mangling any vma field and can
keep doing swapins in parallel to the core dumping) and to some other
corner case.
In order to facilitate the backporting I added "Fixes: 86039bd3b4e6"
however the side effect of this same race condition in /proc/pid/mem
should be reproducible since before 2.6.12-rc2 so I couldn't add any
other "Fixes:" because there's no hash beyond the git genesis commit.
Because find_extend_vma() is the only location outside of the process
context that could modify the "mm" structures under mmap_sem for
reading, by adding the mmget_still_valid() check to it, all other cases
that take the mmap_sem for reading don't need the new check after
mmget_not_zero()/get_task_mm(). The expand_stack() in page fault
context also doesn't need the new check, because all tasks under core
dumping are frozen.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: 86039bd3b4e6 ("userfaultfd: add new syscall to provide memory externalization")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reported-by: Jann Horn <[email protected]>
Suggested-by: Oleg Nesterov <[email protected]>
Acked-by: Peter Xu <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Oleg Nesterov <[email protected]>
Reviewed-by: Jann Horn <[email protected]>
Acked-by: Jason Gunthorpe <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out)
{
mp4object *mp4 = (mp4object *)handle;
if (mp4 == NULL) return 0.0;
uint32_t key, insamples;
uint32_t repeat, outsamples;
GPMF_stream find_stream;
if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0;
key = GPMF_Key(gs);
repeat = GPMF_Repeat(gs);
if (rate == 0.0)
rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST);
if (rate == 0.0)
{
*in = *out = 0.0;
return 0.0;
}
GPMF_CopyState(gs, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL))
{
outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream));
insamples = outsamples - repeat;
*in = ((double)insamples / (double)rate);
*out = ((double)outsamples / (double)rate);
}
else
{
*in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
*out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon);
}
return rate;
}
Commit Message: fixed many security issues with the too crude mp4 reader
CWE ID: CWE-787
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void Document::InitContentSecurityPolicy(
ContentSecurityPolicy* csp,
const ContentSecurityPolicy* policy_to_inherit,
const ContentSecurityPolicy* previous_document_csp) {
SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create());
GetContentSecurityPolicy()->BindToExecutionContext(this);
if (policy_to_inherit) {
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
} else {
if (frame_) {
Frame* inherit_from = frame_->Tree().Parent()
? frame_->Tree().Parent()
: frame_->Client()->Opener();
if (inherit_from && frame_ != inherit_from) {
DCHECK(inherit_from->GetSecurityContext() &&
inherit_from->GetSecurityContext()->GetContentSecurityPolicy());
policy_to_inherit =
inherit_from->GetSecurityContext()->GetContentSecurityPolicy();
}
}
if (!policy_to_inherit)
policy_to_inherit = previous_document_csp;
if (policy_to_inherit &&
(url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() ||
url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")))
GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit);
}
if (policy_to_inherit && IsPluginDocument())
GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit);
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20
Target: 1
Example 2:
Code: exsltDateWeekInMonth (const xmlChar *dateTime)
{
exsltDateValPtr dt;
long fdiy, fdiw, ret;
if (dateTime == NULL) {
#ifdef WITH_TIME
dt = exsltDateCurrent();
if (dt == NULL)
#endif
return xmlXPathNAN;
} else {
dt = exsltDateParse(dateTime);
if (dt == NULL)
return xmlXPathNAN;
if ((dt->type != XS_DATETIME) && (dt->type != XS_DATE)) {
exsltDateFreeDate(dt);
return xmlXPathNAN;
}
}
fdiy = DAY_IN_YEAR(1, dt->value.date.mon, dt->value.date.year);
/*
* Determine day-in-week (0=Sun, 1=Mon, etc.) then adjust so Monday
* is the first day-in-week
*/
fdiw = (_exsltDateDayInWeek(fdiy, dt->value.date.year) + 6) % 7;
ret = ((dt->value.date.day + fdiw - 1) / 7) + 1;
exsltDateFreeDate(dt);
return (double) ret;
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void decode_cpe(NeAACDecStruct *hDecoder, NeAACDecFrameInfo *hInfo, bitfile *ld,
uint8_t id_syn_ele)
{
uint8_t channels = hDecoder->fr_channels;
uint8_t tag = 0;
if (channels+2 > MAX_CHANNELS)
{
hInfo->error = 12;
return;
}
if (hDecoder->fr_ch_ele+1 > MAX_SYNTAX_ELEMENTS)
{
hInfo->error = 13;
return;
}
/* for CPE the number of output channels is always 2 */
if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] == 0)
{
/* element_output_channels not set yet */
hDecoder->element_output_channels[hDecoder->fr_ch_ele] = 2;
} else if (hDecoder->element_output_channels[hDecoder->fr_ch_ele] != 2) {
/* element inconsistency */
hInfo->error = 21;
return;
}
if (hDecoder->frame && hDecoder->element_id[hDecoder->fr_ch_ele] != id_syn_ele) {
/* element inconsistency */
hInfo->error = 21;
return;
}
/* save the syntax element id */
hDecoder->element_id[hDecoder->fr_ch_ele] = id_syn_ele;
/* decode the element */
hInfo->error = channel_pair_element(hDecoder, ld, channels, &tag);
/* map output channel position to internal data channels */
if (hDecoder->pce_set)
{
hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]] = channels;
hDecoder->internal_channel[hDecoder->pce.cpe_channel[tag]+1] = channels+1;
} else {
hDecoder->internal_channel[channels] = channels;
hDecoder->internal_channel[channels+1] = channels+1;
}
hDecoder->fr_channels += 2;
hDecoder->fr_ch_ele++;
}
Commit Message: Fix a couple buffer overflows
https://hackerone.com/reports/502816
https://hackerone.com/reports/507858
https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void AppCacheUpdateJob::OnManifestDataWriteComplete(int result) {
if (result > 0) {
AppCacheEntry entry(AppCacheEntry::MANIFEST,
manifest_response_writer_->response_id(),
manifest_response_writer_->amount_written());
if (!inprogress_cache_->AddOrModifyEntry(manifest_url_, entry))
duplicate_response_ids_.push_back(entry.response_id());
StoreGroupAndCache();
} else {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
"Failed to write the manifest data to storage",
blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(),
0, false /*is_cross_origin*/),
DISKCACHE_ERROR, GURL());
}
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void catc_tx_done(struct urb *urb)
{
struct catc *catc = urb->context;
unsigned long flags;
int r, status = urb->status;
if (status == -ECONNRESET) {
dev_dbg(&urb->dev->dev, "Tx Reset.\n");
urb->status = 0;
netif_trans_update(catc->netdev);
catc->netdev->stats.tx_errors++;
clear_bit(TX_RUNNING, &catc->flags);
netif_wake_queue(catc->netdev);
return;
}
if (status) {
dev_dbg(&urb->dev->dev, "tx_done, status %d, length %d\n",
status, urb->actual_length);
return;
}
spin_lock_irqsave(&catc->tx_lock, flags);
if (catc->tx_ptr) {
r = catc_tx_run(catc);
if (unlikely(r < 0))
clear_bit(TX_RUNNING, &catc->flags);
} else {
clear_bit(TX_RUNNING, &catc->flags);
}
netif_wake_queue(catc->netdev);
spin_unlock_irqrestore(&catc->tx_lock, flags);
}
Commit Message: catc: Use heap buffer for memory size test
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState)
{
FileSystemFlags flags(options);
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return static_cast<FileEntrySync*>(helper->getResult(exceptionState));
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PHP_FUNCTION(locale_compose)
{
smart_str loc_name_s = {0};
smart_str *loc_name = &loc_name_s;
zval* arr = NULL;
HashTable* hash_arr = NULL;
int result = 0;
intl_error_reset( NULL TSRMLS_CC );
if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a",
&arr) == FAILURE)
{
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: unable to parse input params", 0 TSRMLS_CC );
RETURN_FALSE;
}
hash_arr = HASH_OF( arr );
if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 )
RETURN_FALSE;
/* Check for grandfathered first */
result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG);
if( result == SUCCESS){
RETURN_SMART_STR(loc_name);
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Not grandfathered */
result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG);
if( result == LOC_NOT_FOUND ){
intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
"locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC );
smart_str_free(loc_name);
RETURN_FALSE;
}
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Extlang */
result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Script */
result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Region */
result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Variant */
result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
/* Private */
result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC);
if( !handleAppendResult( result, loc_name TSRMLS_CC)){
RETURN_FALSE;
}
RETURN_SMART_STR(loc_name);
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125
Target: 1
Example 2:
Code: static inline struct hlist_head *bsg_dev_idx_hash(int index)
{
return &bsg_device_list[index & (BSG_LIST_ARRAY_SIZE - 1)];
}
Commit Message: sg_write()/bsg_write() is not fit to be called under KERNEL_DS
Both damn things interpret userland pointers embedded into the payload;
worse, they are actually traversing those. Leaving aside the bad
API design, this is very much _not_ safe to call with KERNEL_DS.
Bail out early if that happens.
Cc: [email protected]
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: const QList<Smb4KHost *> &Smb4KGlobal::hostsList()
{
return p->hostsList;
}
Commit Message:
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum,
const ImageInfo *image_info,ExceptionInfo *exception)
{
ddjvu_page_type_t
type;
ddjvu_pageinfo_t info;
ddjvu_message_t *message;
Image *image;
int logging;
int tag;
/* so, we know that the page is there! Get its dimension, and */
/* Read one DJVU image */
image = lc->image;
/* register PixelPacket *q; */
logging=LogMagickEvent(CoderEvent,GetMagickModule(), " enter ReadOneDJVUImage()");
(void) logging;
#if DEBUG
printf("==== Loading the page %d\n", pagenum);
#endif
lc->page = ddjvu_page_create_by_pageno(lc->document, pagenum); /* 0? */
/* pump data untill the page is ready for rendering. */
tag=(-1);
do {
while ((message = ddjvu_message_peek(lc->context)))
{
tag=process_message(message);
if (tag == 0) break;
ddjvu_message_pop(lc->context);
}
/* fixme: maybe exit? */
/* if (lc->error) break; */
message = pump_data_until_message(lc,image);
if (message)
do {
tag=process_message(message);
if (tag == 0) break;
ddjvu_message_pop(lc->context);
} while ((message = ddjvu_message_peek(lc->context)));
} while (!ddjvu_page_decoding_done(lc->page));
ddjvu_document_get_pageinfo(lc->document, pagenum, &info);
image->x_resolution = (float) info.dpi;
image->y_resolution =(float) info.dpi;
if (image_info->density != (char *) NULL)
{
int
flags;
GeometryInfo
geometry_info;
/*
Set rendering resolution.
*/
flags=ParseGeometry(image_info->density,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
info.width=(int) (info.width*image->x_resolution/info.dpi);
info.height=(int) (info.height*image->y_resolution/info.dpi);
info.dpi=(int) MagickMax(image->x_resolution,image->y_resolution);
}
type = ddjvu_page_get_type(lc->page);
/* double -> float! */
/* image->gamma = (float)ddjvu_page_get_gamma(lc->page); */
/* mmc: set image->depth */
/* mmc: This from the type */
image->columns=(size_t) info.width;
image->rows=(size_t) info.height;
/* mmc: bitonal should be palettized, and compressed! */
if (type == DDJVU_PAGETYPE_BITONAL){
image->colorspace = GRAYColorspace;
image->storage_class = PseudoClass;
image->depth = 8UL; /* i only support that? */
image->colors= 2;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
} else {
image->colorspace = RGBColorspace;
image->storage_class = DirectClass;
/* fixme: MAGICKCORE_QUANTUM_DEPTH ?*/
image->depth = 8UL; /* i only support that? */
image->matte = MagickTrue;
/* is this useful? */
}
#if DEBUG
printf("now filling %.20g x %.20g\n",(double) image->columns,(double)
image->rows);
#endif
#if 1 /* per_line */
/* q = QueueAuthenticPixels(image,0,0,image->columns,image->rows); */
get_page_image(lc, lc->page, 0, 0, info.width, info.height, image_info);
#else
int i;
for (i = 0;i< image->rows; i++)
{
printf("%d\n",i);
q = QueueAuthenticPixels(image,0,i,image->columns,1);
get_page_line(lc, i, quantum_info);
SyncAuthenticPixels(image);
}
#endif /* per_line */
#if DEBUG
printf("END: finished filling %.20g x %.20g\n",(double) image->columns,
(double) image->rows);
#endif
if (!image->ping)
SyncImage(image);
/* indexes=GetAuthenticIndexQueue(image); */
/* mmc: ??? Convert PNM pixels to runlength-encoded MIFF packets. */
/* image->colors = */
/* how is the line padding / stride? */
if (lc->page) {
ddjvu_page_release(lc->page);
lc->page = NULL;
}
/* image->page.y=mng_info->y_off[mng_info->object_id]; */
if (tag == 0)
image=DestroyImage(image);
return image;
/* end of reading one DJVU page/image */
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void camellia_setup256(const unsigned char *key, u32 *subkey)
{
u32 kll, klr, krl, krr; /* left half of key */
u32 krll, krlr, krrl, krrr; /* right half of key */
u32 il, ir, t0, t1, w0, w1; /* temporary variables */
u32 subL[34];
u32 subR[34];
/**
* key = (kll || klr || krl || krr || krll || krlr || krrl || krrr)
* (|| is concatenation)
*/
kll = get_unaligned_be32(key);
klr = get_unaligned_be32(key + 4);
krl = get_unaligned_be32(key + 8);
krr = get_unaligned_be32(key + 12);
krll = get_unaligned_be32(key + 16);
krlr = get_unaligned_be32(key + 20);
krrl = get_unaligned_be32(key + 24);
krrr = get_unaligned_be32(key + 28);
/* generate KL dependent subkeys */
/* kw1 */
subL[0] = kll; subR[0] = klr;
/* kw2 */
subL[1] = krl; subR[1] = krr;
ROLDQo32(kll, klr, krl, krr, w0, w1, 45);
/* k9 */
subL[12] = kll; subR[12] = klr;
/* k10 */
subL[13] = krl; subR[13] = krr;
ROLDQ(kll, klr, krl, krr, w0, w1, 15);
/* kl3 */
subL[16] = kll; subR[16] = klr;
/* kl4 */
subL[17] = krl; subR[17] = krr;
ROLDQ(kll, klr, krl, krr, w0, w1, 17);
/* k17 */
subL[22] = kll; subR[22] = klr;
/* k18 */
subL[23] = krl; subR[23] = krr;
ROLDQo32(kll, klr, krl, krr, w0, w1, 34);
/* k23 */
subL[30] = kll; subR[30] = klr;
/* k24 */
subL[31] = krl; subR[31] = krr;
/* generate KR dependent subkeys */
ROLDQ(krll, krlr, krrl, krrr, w0, w1, 15);
/* k3 */
subL[4] = krll; subR[4] = krlr;
/* k4 */
subL[5] = krrl; subR[5] = krrr;
ROLDQ(krll, krlr, krrl, krrr, w0, w1, 15);
/* kl1 */
subL[8] = krll; subR[8] = krlr;
/* kl2 */
subL[9] = krrl; subR[9] = krrr;
ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
/* k13 */
subL[18] = krll; subR[18] = krlr;
/* k14 */
subL[19] = krrl; subR[19] = krrr;
ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 34);
/* k19 */
subL[26] = krll; subR[26] = krlr;
/* k20 */
subL[27] = krrl; subR[27] = krrr;
ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 34);
/* generate KA */
kll = subL[0] ^ krll; klr = subR[0] ^ krlr;
krl = subL[1] ^ krrl; krr = subR[1] ^ krrr;
CAMELLIA_F(kll, klr,
CAMELLIA_SIGMA1L, CAMELLIA_SIGMA1R,
w0, w1, il, ir, t0, t1);
krl ^= w0; krr ^= w1;
CAMELLIA_F(krl, krr,
CAMELLIA_SIGMA2L, CAMELLIA_SIGMA2R,
kll, klr, il, ir, t0, t1);
kll ^= krll; klr ^= krlr;
CAMELLIA_F(kll, klr,
CAMELLIA_SIGMA3L, CAMELLIA_SIGMA3R,
krl, krr, il, ir, t0, t1);
krl ^= w0 ^ krrl; krr ^= w1 ^ krrr;
CAMELLIA_F(krl, krr,
CAMELLIA_SIGMA4L, CAMELLIA_SIGMA4R,
w0, w1, il, ir, t0, t1);
kll ^= w0; klr ^= w1;
/* generate KB */
krll ^= kll; krlr ^= klr;
krrl ^= krl; krrr ^= krr;
CAMELLIA_F(krll, krlr,
CAMELLIA_SIGMA5L, CAMELLIA_SIGMA5R,
w0, w1, il, ir, t0, t1);
krrl ^= w0; krrr ^= w1;
CAMELLIA_F(krrl, krrr,
CAMELLIA_SIGMA6L, CAMELLIA_SIGMA6R,
w0, w1, il, ir, t0, t1);
krll ^= w0; krlr ^= w1;
/* generate KA dependent subkeys */
ROLDQ(kll, klr, krl, krr, w0, w1, 15);
/* k5 */
subL[6] = kll; subR[6] = klr;
/* k6 */
subL[7] = krl; subR[7] = krr;
ROLDQ(kll, klr, krl, krr, w0, w1, 30);
/* k11 */
subL[14] = kll; subR[14] = klr;
/* k12 */
subL[15] = krl; subR[15] = krr;
/* rotation left shift 32bit */
/* kl5 */
subL[24] = klr; subR[24] = krl;
/* kl6 */
subL[25] = krr; subR[25] = kll;
/* rotation left shift 49 from k11,k12 -> k21,k22 */
ROLDQo32(kll, klr, krl, krr, w0, w1, 49);
/* k21 */
subL[28] = kll; subR[28] = klr;
/* k22 */
subL[29] = krl; subR[29] = krr;
/* generate KB dependent subkeys */
/* k1 */
subL[2] = krll; subR[2] = krlr;
/* k2 */
subL[3] = krrl; subR[3] = krrr;
ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
/* k7 */
subL[10] = krll; subR[10] = krlr;
/* k8 */
subL[11] = krrl; subR[11] = krrr;
ROLDQ(krll, krlr, krrl, krrr, w0, w1, 30);
/* k15 */
subL[20] = krll; subR[20] = krlr;
/* k16 */
subL[21] = krrl; subR[21] = krrr;
ROLDQo32(krll, krlr, krrl, krrr, w0, w1, 51);
/* kw3 */
subL[32] = krll; subR[32] = krlr;
/* kw4 */
subL[33] = krrl; subR[33] = krrr;
camellia_setup_tail(subkey, subL, subR, 32);
}
Commit Message: crypto: prefix module autoloading with "crypto-"
This prefixes all crypto module loading with "crypto-" so we never run
the risk of exposing module auto-loading to userspace via a crypto API,
as demonstrated by Mathias Krause:
https://lkml.org/lkml/2013/3/4/70
Signed-off-by: Kees Cook <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static struct dentry *__d_instantiate_unique(struct dentry *entry,
struct inode *inode)
{
struct dentry *alias;
int len = entry->d_name.len;
const char *name = entry->d_name.name;
unsigned int hash = entry->d_name.hash;
if (!inode) {
__d_instantiate(entry, NULL);
return NULL;
}
hlist_for_each_entry(alias, &inode->i_dentry, d_u.d_alias) {
/*
* Don't need alias->d_lock here, because aliases with
* d_parent == entry->d_parent are not subject to name or
* parent changes, because the parent inode i_mutex is held.
*/
if (alias->d_name.hash != hash)
continue;
if (alias->d_parent != entry->d_parent)
continue;
if (alias->d_name.len != len)
continue;
if (dentry_cmp(alias, name, len))
continue;
__dget(alias);
return alias;
}
__d_instantiate(entry, inode);
return NULL;
}
Commit Message: dcache: Handle escaped paths in prepend_path
A rename can result in a dentry that by walking up d_parent
will never reach it's mnt_root. For lack of a better term
I call this an escaped path.
prepend_path is called by four different functions __d_path,
d_absolute_path, d_path, and getcwd.
__d_path only wants to see paths are connected to the root it passes
in. So __d_path needs prepend_path to return an error.
d_absolute_path similarly wants to see paths that are connected to
some root. Escaped paths are not connected to any mnt_root so
d_absolute_path needs prepend_path to return an error greater
than 1. So escaped paths will be treated like paths on lazily
unmounted mounts.
getcwd needs to prepend "(unreachable)" so getcwd also needs
prepend_path to return an error.
d_path is the interesting hold out. d_path just wants to print
something, and does not care about the weird cases. Which raises
the question what should be printed?
Given that <escaped_path>/<anything> should result in -ENOENT I
believe it is desirable for escaped paths to be printed as empty
paths. As there are not really any meaninful path components when
considered from the perspective of a mount tree.
So tweak prepend_path to return an empty path with an new error
code of 3 when it encounters an escaped path.
Signed-off-by: "Eric W. Biederman" <[email protected]>
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-254
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
first = mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: bool is_guest_view_hack() { return is_guest_view_hack_; }
Commit Message: Start rendering timer after first navigation
Currently the new content rendering timer in the browser process,
which clears an old page's contents 4 seconds after a navigation if the
new page doesn't draw in that time, is not set on the first navigation
for a top-level frame.
This is problematic because content can exist before the first
navigation, for instance if it was created by a javascript: URL.
This CL removes the code that skips the timer activation on the first
navigation.
Bug: 844881
Change-Id: I19b3ad1ff62c69ded3a5f7b1c0afde191aaf4584
Reviewed-on: https://chromium-review.googlesource.com/1188589
Reviewed-by: Fady Samuel <[email protected]>
Reviewed-by: ccameron <[email protected]>
Commit-Queue: Ken Buchanan <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586913}
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
comp = &pi->comps[pi->compno];
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
comp = &pi->comps[pi->compno];
for (pi->resno = pi->poc.resno0;
pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] To avoid divisions by zero / undefined behaviour on shift
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-369
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static Maybe<bool> IncludesValueImpl(Isolate* isolate,
Handle<JSObject> receiver,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver));
bool search_for_hole = value->IsUndefined(isolate);
if (!search_for_hole) {
Maybe<bool> result = Nothing<bool>();
if (DictionaryElementsAccessor::IncludesValueFastPath(
isolate, receiver, value, start_from, length, &result)) {
return result;
}
}
Handle<SeededNumberDictionary> dictionary(
SeededNumberDictionary::cast(receiver->elements()), isolate);
for (uint32_t k = start_from; k < length; ++k) {
int entry = dictionary->FindEntry(isolate, k);
if (entry == SeededNumberDictionary::kNotFound) {
if (search_for_hole) return Just(true);
continue;
}
PropertyDetails details = GetDetailsImpl(*dictionary, entry);
switch (details.kind()) {
case kData: {
Object* element_k = dictionary->ValueAt(entry);
if (value->SameValueZero(element_k)) return Just(true);
break;
}
case kAccessor: {
LookupIterator it(isolate, receiver, k,
LookupIterator::OWN_SKIP_INTERCEPTOR);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
Handle<Object> element_k;
ASSIGN_RETURN_ON_EXCEPTION_VALUE(
isolate, element_k, JSObject::GetPropertyWithAccessor(&it),
Nothing<bool>());
if (value->SameValueZero(*element_k)) return Just(true);
if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) {
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
if (*dictionary == receiver->elements()) continue;
if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) {
if (receiver->map()->GetInitialElements() == receiver->elements()) {
return Just(search_for_hole);
}
return IncludesValueSlowPath(isolate, receiver, value, k + 1,
length);
}
dictionary = handle(
SeededNumberDictionary::cast(receiver->elements()), isolate);
break;
}
}
}
return Just(false);
}
Commit Message: Backport: Fix Object.entries/values with changing elements
Bug: 111274046
Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \
/data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest
Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb
(cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99)
CWE ID: CWE-704
Target: 1
Example 2:
Code: void AXNodeObject::increment() {
UserGestureIndicator gestureIndicator(DocumentUserGestureToken::create(
getDocument(), UserGestureToken::NewGesture));
alterSliderValue(true);
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void BrowserContextDestroyer::DestroyContext(BrowserContext* context) {
CHECK(context->IsOffTheRecord() || !context->HasOffTheRecordContext());
content::BrowserContext::NotifyWillBeDestroyed(context);
std::set<content::RenderProcessHost*> hosts;
for (content::RenderProcessHost::iterator it =
content::RenderProcessHost::AllHostsIterator();
!it.IsAtEnd(); it.Advance()) {
content::RenderProcessHost* host = it.GetCurrentValue();
if (host->GetBrowserContext() != context) {
continue;
}
hosts.insert(host);
//// static
}
if (hosts.empty()) {
delete context;
} else {
new BrowserContextDestroyer(context, hosts);
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: scoped_refptr<StaticBitmapImage> WebGLRenderingContextBase::GetImage(
AccelerationHint hint,
SnapshotReason reason) const {
if (!GetDrawingBuffer())
return nullptr;
if (IsMainThread()) {
GetDrawingBuffer()->ResolveAndBindForReadAndDraw();
IntSize size = ClampedCanvasSize();
std::unique_ptr<AcceleratedImageBufferSurface> surface =
std::make_unique<AcceleratedImageBufferSurface>(size, ColorParams());
if (!surface->IsValid())
return nullptr;
std::unique_ptr<ImageBuffer> buffer =
ImageBuffer::Create(std::move(surface));
if (!buffer->CopyRenderingResultsFromDrawingBuffer(GetDrawingBuffer(),
kBackBuffer)) {
NOTREACHED();
return nullptr;
}
return buffer->NewImageSnapshot(hint, reason);
}
int width = GetDrawingBuffer()->Size().Width();
int height = GetDrawingBuffer()->Size().Height();
SkImageInfo image_info = SkImageInfo::Make(
width, height, kRGBA_8888_SkColorType,
CreationAttributes().alpha() ? kPremul_SkAlphaType : kOpaque_SkAlphaType);
return this->MakeImageSnapshot(image_info);
}
Commit Message: Tighten about IntRect use in WebGL with overflow detection
BUG=784183
TEST=test case in the bug in ASAN build
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f
Reviewed-on: https://chromium-review.googlesource.com/811826
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522213}
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int check_mtab(const char *progname, const char *devname,
const char *dir)
{
if (check_newline(progname, devname) == -1 ||
check_newline(progname, dir) == -1)
return EX_USAGE;
return 0;
}
Commit Message:
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void testInspectorDefault(InspectorTest* test, gconstpointer)
{
test->showInWindowAndWaitUntilMapped(GTK_WINDOW_TOPLEVEL);
test->resizeView(200, 200);
test->loadHtml("<html><body><p>WebKitGTK+ Inspector test</p></body></html>", 0);
test->waitUntilLoadFinished();
test->showAndWaitUntilFinished(false);
GRefPtr<WebKitWebViewBase> inspectorView = webkit_web_inspector_get_web_view(test->m_inspector);
g_assert(inspectorView.get());
test->assertObjectIsDeletedWhenTestFinishes(G_OBJECT(inspectorView.get()));
g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
g_assert_cmpuint(webkit_web_inspector_get_attached_height(test->m_inspector), ==, 0);
Vector<InspectorTest::InspectorEvents>& events = test->m_events;
g_assert_cmpint(events.size(), ==, 2);
g_assert_cmpint(events[0], ==, InspectorTest::BringToFront);
g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
test->m_events.clear();
test->showAndWaitUntilFinished(true);
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::BringToFront);
test->m_events.clear();
test->resizeViewAndAttach();
g_assert(webkit_web_inspector_is_attached(test->m_inspector));
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::Attach);
test->m_events.clear();
test->detachAndWaitUntilWindowOpened();
g_assert(!webkit_web_inspector_is_attached(test->m_inspector));
events = test->m_events;
g_assert_cmpint(events.size(), ==, 2);
g_assert_cmpint(events[0], ==, InspectorTest::Detach);
g_assert_cmpint(events[1], ==, InspectorTest::OpenWindow);
test->m_events.clear();
test->closeAndWaitUntilClosed();
events = test->m_events;
g_assert_cmpint(events.size(), ==, 1);
g_assert_cmpint(events[0], ==, InspectorTest::Closed);
test->m_events.clear();
}
Commit Message: [GTK] Inspector should set a default attached height before being attached
https://bugs.webkit.org/show_bug.cgi?id=90767
Reviewed by Xan Lopez.
We are currently using the minimum attached height in
WebKitWebViewBase as the default height for the inspector when
attached. It would be easier for WebKitWebViewBase and embedders
implementing attach() if the inspector already had an attached
height set when it's being attached.
* UIProcess/API/gtk/WebKitWebViewBase.cpp:
(webkitWebViewBaseContainerAdd): Don't initialize
inspectorViewHeight.
(webkitWebViewBaseSetInspectorViewHeight): Allow to set the
inspector view height before having an inpector view, but only
queue a resize when the view already has an inspector view.
* UIProcess/API/gtk/tests/TestInspector.cpp:
(testInspectorDefault):
(testInspectorManualAttachDetach):
* UIProcess/gtk/WebInspectorProxyGtk.cpp:
(WebKit::WebInspectorProxy::platformAttach): Set the default
attached height before attach the inspector view.
git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int _nfs4_proc_getattr(struct nfs_server *server, struct nfs_fh *fhandle,
struct nfs_fattr *fattr, struct nfs4_label *label)
{
struct nfs4_getattr_arg args = {
.fh = fhandle,
.bitmask = server->attr_bitmask,
};
struct nfs4_getattr_res res = {
.fattr = fattr,
.label = label,
.server = server,
};
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETATTR],
.rpc_argp = &args,
.rpc_resp = &res,
};
args.bitmask = nfs4_bitmask(server, label);
nfs_fattr_init(fattr);
return nfs4_call_sync(server->client, server, &msg, &args.seq_args, &res.seq_res, 0);
}
Commit Message: NFS: Fix a NULL pointer dereference of migration recovery ops for v4.2 client
---Steps to Reproduce--
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
<nfs-client>
# mount -t nfs nfs-server:/nfs/ /mnt/
# ll /mnt/*/
<nfs-server>
# cat /etc/exports
/nfs/referal *(rw,insecure,no_subtree_check,no_root_squash,crossmnt,refer=/nfs/old/@nfs-server)
/nfs/old *(ro,insecure,subtree_check,root_squash,crossmnt)
# service nfs restart
<nfs-client>
# ll /mnt/*/ --->>>>> oops here
[ 5123.102925] BUG: unable to handle kernel NULL pointer dereference at (null)
[ 5123.103363] IP: [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.103752] PGD 587b9067 PUD 3cbf5067 PMD 0
[ 5123.104131] Oops: 0000 [#1]
[ 5123.104529] Modules linked in: nfsv4(OE) nfs(OE) fscache(E) nfsd(OE) xfs libcrc32c iscsi_tcp libiscsi_tcp libiscsi scsi_transport_iscsi coretemp crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel ppdev vmw_balloon parport_pc parport i2c_piix4 shpchp auth_rpcgss nfs_acl vmw_vmci lockd grace sunrpc vmwgfx drm_kms_helper ttm drm mptspi serio_raw scsi_transport_spi e1000 mptscsih mptbase ata_generic pata_acpi [last unloaded: nfsd]
[ 5123.105887] CPU: 0 PID: 15853 Comm: ::1-manager Tainted: G OE 4.2.0-rc6+ #214
[ 5123.106358] Hardware name: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 05/20/2014
[ 5123.106860] task: ffff88007620f300 ti: ffff88005877c000 task.ti: ffff88005877c000
[ 5123.107363] RIP: 0010:[<ffffffffa03ed38b>] [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.107909] RSP: 0018:ffff88005877fdb8 EFLAGS: 00010246
[ 5123.108435] RAX: ffff880053f3bc00 RBX: ffff88006ce6c908 RCX: ffff880053a0d240
[ 5123.108968] RDX: ffffea0000e6d940 RSI: ffff8800399a0000 RDI: ffff88006ce6c908
[ 5123.109503] RBP: ffff88005877fe28 R08: ffffffff81c708a0 R09: 0000000000000000
[ 5123.110045] R10: 00000000000001a2 R11: ffff88003ba7f5c8 R12: ffff880054c55800
[ 5123.110618] R13: 0000000000000000 R14: ffff880053a0d240 R15: ffff880053a0d240
[ 5123.111169] FS: 0000000000000000(0000) GS:ffffffff81c27000(0000) knlGS:0000000000000000
[ 5123.111726] CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
[ 5123.112286] CR2: 0000000000000000 CR3: 0000000054cac000 CR4: 00000000001406f0
[ 5123.112888] Stack:
[ 5123.113458] ffffea0000e6d940 ffff8800399a0000 00000000000167d0 0000000000000000
[ 5123.114049] 0000000000000000 0000000000000000 0000000000000000 00000000a7ec82c6
[ 5123.114662] ffff88005877fe18 ffffea0000e6d940 ffff8800399a0000 ffff880054c55800
[ 5123.115264] Call Trace:
[ 5123.115868] [<ffffffffa03fb44b>] nfs4_try_migration+0xbb/0x220 [nfsv4]
[ 5123.116487] [<ffffffffa03fcb3b>] nfs4_run_state_manager+0x4ab/0x7b0 [nfsv4]
[ 5123.117104] [<ffffffffa03fc690>] ? nfs4_do_reclaim+0x510/0x510 [nfsv4]
[ 5123.117813] [<ffffffff810a4527>] kthread+0xd7/0xf0
[ 5123.118456] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.119108] [<ffffffff816d9cdf>] ret_from_fork+0x3f/0x70
[ 5123.119723] [<ffffffff810a4450>] ? kthread_worker_fn+0x160/0x160
[ 5123.120329] Code: 4c 8b 6a 58 74 17 eb 52 48 8d 55 a8 89 c6 4c 89 e7 e8 4a b5 ff ff 8b 45 b0 85 c0 74 1c 4c 89 f9 48 8b 55 90 48 8b 75 98 48 89 df <41> ff 55 00 3d e8 d8 ff ff 41 89 c6 74 cf 48 8b 4d c8 65 48 33
[ 5123.121643] RIP [<ffffffffa03ed38b>] nfs4_proc_get_locations+0x9b/0x120 [nfsv4]
[ 5123.122308] RSP <ffff88005877fdb8>
[ 5123.122942] CR2: 0000000000000000
Fixes: ec011fe847 ("NFS: Introduce a vector of migration recovery ops")
Cc: [email protected] # v3.13+
Signed-off-by: Kinglong Mee <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: _gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
if (rc)
return rc;
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_addm (sum, hash, dr, skey->E.n); /* sum = hash + (d*r) mod n */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
}
Commit Message:
CWE ID: CWE-200
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: initpyfribidi (void)
{
PyObject *module;
/* XXX What should be done if we fail here? */
module = Py_InitModule3 ("pyfribidi", PyfribidiMethods,
_pyfribidi__doc__);
PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL);
PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR);
PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON);
PyModule_AddStringConstant (module, "__author__",
"Yaacov Zamir and Nir Soffer");
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119
Target: 1
Example 2:
Code: scoped_refptr<SiteInstance> SiteInstanceImpl::GetRelatedSiteInstance(
const GURL& url) {
return browsing_instance_->GetSiteInstanceForURL(url);
}
Commit Message: Use unique processes for data URLs on restore.
Data URLs are usually put into the process that created them, but this
info is not tracked after a tab restore. Ensure that they do not end up
in the parent frame's process (or each other's process), in case they
are malicious.
BUG=863069
Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b
Reviewed-on: https://chromium-review.googlesource.com/1150767
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Commit-Queue: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#581023}
CWE ID: CWE-285
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Tracks::ParseTrackEntry(long long track_start, long long track_size,
long long element_start, long long element_size,
Track*& pResult) const {
if (pResult)
return -1;
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = track_start;
const long long track_stop = track_start + track_size;
Track::Info info;
info.type = 0;
info.number = 0;
info.uid = 0;
info.defaultDuration = 0;
Track::Settings v;
v.start = -1;
v.size = -1;
Track::Settings a;
a.start = -1;
a.size = -1;
Track::Settings e; // content_encodings_settings;
e.start = -1;
e.size = -1;
long long lacing = 1; // default is true
while (pos < track_stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, track_stop, id, size);
if (status < 0) // error
return status;
if (size < 0)
return E_FILE_FORMAT_INVALID;
const long long start = pos;
if (id == 0x60) { // VideoSettings ID
v.start = start;
v.size = size;
} else if (id == 0x61) { // AudioSettings ID
a.start = start;
a.size = size;
} else if (id == 0x2D80) { // ContentEncodings ID
e.start = start;
e.size = size;
} else if (id == 0x33C5) { // Track UID
if (size > 8)
return E_FILE_FORMAT_INVALID;
info.uid = 0;
long long pos_ = start;
const long long pos_end = start + size;
while (pos_ != pos_end) {
unsigned char b;
const int status = pReader->Read(pos_, 1, &b);
if (status)
return status;
info.uid <<= 8;
info.uid |= b;
++pos_;
}
} else if (id == 0x57) { // Track Number
const long long num = UnserializeUInt(pReader, pos, size);
if ((num <= 0) || (num > 127))
return E_FILE_FORMAT_INVALID;
info.number = static_cast<long>(num);
} else if (id == 0x03) { // Track Type
const long long type = UnserializeUInt(pReader, pos, size);
if ((type <= 0) || (type > 254))
return E_FILE_FORMAT_INVALID;
info.type = static_cast<long>(type);
} else if (id == 0x136E) { // Track Name
const long status =
UnserializeString(pReader, pos, size, info.nameAsUTF8);
if (status)
return status;
} else if (id == 0x02B59C) { // Track Language
const long status = UnserializeString(pReader, pos, size, info.language);
if (status)
return status;
} else if (id == 0x03E383) { // Default Duration
const long long duration = UnserializeUInt(pReader, pos, size);
if (duration < 0)
return E_FILE_FORMAT_INVALID;
info.defaultDuration = static_cast<unsigned long long>(duration);
} else if (id == 0x06) { // CodecID
const long status = UnserializeString(pReader, pos, size, info.codecId);
if (status)
return status;
} else if (id == 0x1C) { // lacing
lacing = UnserializeUInt(pReader, pos, size);
if ((lacing < 0) || (lacing > 1))
return E_FILE_FORMAT_INVALID;
} else if (id == 0x23A2) { // Codec Private
delete[] info.codecPrivate;
info.codecPrivate = NULL;
info.codecPrivateSize = 0;
const size_t buflen = static_cast<size_t>(size);
if (buflen) {
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int status = pReader->Read(pos, static_cast<long>(buflen), buf);
if (status) {
delete[] buf;
return status;
}
info.codecPrivate = buf;
info.codecPrivateSize = buflen;
}
} else if (id == 0x058688) { // Codec Name
const long status =
UnserializeString(pReader, pos, size, info.codecNameAsUTF8);
if (status)
return status;
} else if (id == 0x16AA) { // Codec Delay
info.codecDelay = UnserializeUInt(pReader, pos, size);
} else if (id == 0x16BB) { // Seek Pre Roll
info.seekPreRoll = UnserializeUInt(pReader, pos, size);
}
pos += size; // consume payload
assert(pos <= track_stop);
}
assert(pos == track_stop);
if (info.number <= 0) // not specified
return E_FILE_FORMAT_INVALID;
if (GetTrackByNumber(info.number))
return E_FILE_FORMAT_INVALID;
if (info.type <= 0) // not specified
return E_FILE_FORMAT_INVALID;
info.lacing = (lacing > 0) ? true : false;
if (info.type == Track::kVideo) {
if (v.start < 0)
return E_FILE_FORMAT_INVALID;
if (a.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings = v;
VideoTrack* pTrack = NULL;
const long status = VideoTrack::Parse(m_pSegment, info, element_start,
element_size, pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
if (e.start >= 0)
pResult->ParseContentEncodingsEntry(e.start, e.size);
} else if (info.type == Track::kAudio) {
if (a.start < 0)
return E_FILE_FORMAT_INVALID;
if (v.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings = a;
AudioTrack* pTrack = NULL;
const long status = AudioTrack::Parse(m_pSegment, info, element_start,
element_size, pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
if (e.start >= 0)
pResult->ParseContentEncodingsEntry(e.start, e.size);
} else {
if (a.start >= 0)
return E_FILE_FORMAT_INVALID;
if (v.start >= 0)
return E_FILE_FORMAT_INVALID;
if (info.type == Track::kMetadata && e.start >= 0)
return E_FILE_FORMAT_INVALID;
info.settings.start = -1;
info.settings.size = 0;
Track* pTrack = NULL;
const long status =
Track::Create(m_pSegment, info, element_start, element_size, pTrack);
if (status)
return status;
pResult = pTrack;
assert(pResult);
}
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: OMX_ERRORTYPE omx_video::allocate_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("allocate_output_buffer()for %u bytes", (unsigned int)bytes);
if (!m_out_mem_ptr) {
int nBufHdrSize = 0;
DEBUG_PRINT_HIGH("%s: size = %u, actual cnt %u", __FUNCTION__,
(unsigned int)m_sOutPortDef.nBufferSize, (unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem = (struct pmem *) calloc(sizeof(struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
if (m_out_mem_ptr && m_pOutput_pmem) {
bufHdr = m_out_mem_ptr;
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pOutputPortPrivate = (OMX_PTR)&m_pOutput_pmem[i];
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: calloc() failed for m_out_mem_ptr/m_pOutput_pmem");
eRet = OMX_ErrorInsufficientResources;
}
}
DEBUG_PRINT_HIGH("actual cnt = %u", (unsigned int)m_sOutPortDef.nBufferCountActual);
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
DEBUG_PRINT_LOW("Found a Free Output Buffer %d",i);
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = ((m_sOutPortDef.nBufferSize + 4095)/4096) * 4096;
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data, ION_FLAG_CACHED);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: MMAP_FAILED in o/p alloc buffer");
close (m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
else {
m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*));
native_handle_t *handle = native_handle_create(1, 0);
handle->data[0] = m_pOutput_pmem[i].fd;
char *data = (char*) m_pOutput_pmem[i].buffer;
OMX_U32 type = 1;
memcpy(data, &type, sizeof(OMX_U32));
memcpy(data + sizeof(OMX_U32), &handle, sizeof(native_handle_t*));
}
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)m_pOutput_pmem[i].buffer;
(*bufferHdr)->pAppPrivate = appData;
BITMASK_SET(&m_out_bm_count,i);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf FAILED for o/p buf");
return OMX_ErrorInsufficientResources;
}
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p buffers are allocated, invalid allocate buf call"
"for index [%d] actual: %u", i, (unsigned int)m_sOutPortDef.nBufferCountActual);
}
}
return eRet;
}
Commit Message: DO NOT MERGE Fix wrong nAllocLen
Set nAllocLen to the size of the opaque handle itself.
Bug: 28816964
Bug: 28816827
Change-Id: Id410e324bee291d4a0018dddb97eda9bbcded099
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderViewHostImpl::WasSwappedOut() {
StopHangMonitorTimeout();
bool hung = has_timed_out_on_unload_;
SetSwappedOut(true);
if (hung) {
base::ProcessHandle process_handle = GetProcess()->GetHandle();
int views = 0;
RenderProcessHost::RenderWidgetHostsIterator iter(
GetProcess()->GetRenderWidgetHostsIterator());
for (; !iter.IsAtEnd(); iter.Advance())
++views;
if (!RenderProcessHost::run_renderer_in_process() &&
process_handle && views <= 1) {
if (SuddenTerminationAllowed()) {
UMA_HISTOGRAM_PERCENTAGE(
"BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
}
}
}
Send(new ViewMsg_WasSwappedOut(GetRoutingID()));
}
Commit Message: Filter more incoming URLs in the CreateWindow path.
BUG=170532
Review URL: https://chromiumcodereview.appspot.com/12036002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@178728 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: lha_crc16(uint16_t crc, const void *pp, size_t len)
{
const unsigned char *p = (const unsigned char *)pp;
const uint16_t *buff;
const union {
uint32_t i;
char c[4];
} u = { 0x01020304 };
if (len == 0)
return crc;
/* Process unaligned address. */
if (((uintptr_t)p) & (uintptr_t)0x1) {
crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff];
len--;
}
buff = (const uint16_t *)p;
/*
* Modern C compiler such as GCC does not unroll automatically yet
* without unrolling pragma, and Clang is so. So we should
* unroll this loop for its performance.
*/
for (;len >= 8; len -= 8) {
/* This if statement expects compiler optimization will
* remove the statement which will not be executed. */
#undef bswap16
#if defined(_MSC_VER) && _MSC_VER >= 1400 /* Visual Studio */
# define bswap16(x) _byteswap_ushort(x)
#elif defined(__GNUC__) && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 8) || __GNUC__ > 4)
/* GCC 4.8 and later has __builtin_bswap16() */
# define bswap16(x) __builtin_bswap16(x)
#elif defined(__clang__)
/* All clang versions have __builtin_bswap16() */
# define bswap16(x) __builtin_bswap16(x)
#else
# define bswap16(x) ((((x) >> 8) & 0xff) | ((x) << 8))
#endif
#define CRC16W do { \
if(u.c[0] == 1) { /* Big endian */ \
crc ^= bswap16(*buff); buff++; \
} else \
crc ^= *buff++; \
crc = crc16tbl[1][crc & 0xff] ^ crc16tbl[0][crc >> 8];\
} while (0)
CRC16W;
CRC16W;
CRC16W;
CRC16W;
#undef CRC16W
#undef bswap16
}
p = (const unsigned char *)buff;
for (;len; len--) {
crc = (crc >> 8) ^ crc16tbl[0][(crc ^ *p++) & 0xff];
}
return crc;
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int mif_process_cmpt(mif_hdr_t *hdr, char *buf)
{
jas_tvparser_t *tvp;
mif_cmpt_t *cmpt;
int id;
cmpt = 0;
tvp = 0;
if (!(cmpt = mif_cmpt_create())) {
goto error;
}
cmpt->tlx = 0;
cmpt->tly = 0;
cmpt->sampperx = 0;
cmpt->samppery = 0;
cmpt->width = 0;
cmpt->height = 0;
cmpt->prec = 0;
cmpt->sgnd = -1;
cmpt->data = 0;
if (!(tvp = jas_tvparser_create(buf))) {
goto error;
}
while (!(id = jas_tvparser_next(tvp))) {
switch (jas_taginfo_nonull(jas_taginfos_lookup(mif_tags,
jas_tvparser_gettag(tvp)))->id) {
case MIF_TLX:
cmpt->tlx = atoi(jas_tvparser_getval(tvp));
break;
case MIF_TLY:
cmpt->tly = atoi(jas_tvparser_getval(tvp));
break;
case MIF_WIDTH:
cmpt->width = atoi(jas_tvparser_getval(tvp));
break;
case MIF_HEIGHT:
cmpt->height = atoi(jas_tvparser_getval(tvp));
break;
case MIF_HSAMP:
cmpt->sampperx = atoi(jas_tvparser_getval(tvp));
break;
case MIF_VSAMP:
cmpt->samppery = atoi(jas_tvparser_getval(tvp));
break;
case MIF_PREC:
cmpt->prec = atoi(jas_tvparser_getval(tvp));
break;
case MIF_SGND:
cmpt->sgnd = atoi(jas_tvparser_getval(tvp));
break;
case MIF_DATA:
if (!(cmpt->data = jas_strdup(jas_tvparser_getval(tvp)))) {
return -1;
}
break;
}
}
jas_tvparser_destroy(tvp);
if (!cmpt->sampperx || !cmpt->samppery) {
goto error;
}
if (mif_hdr_addcmpt(hdr, hdr->numcmpts, cmpt)) {
goto error;
}
return 0;
error:
if (cmpt) {
mif_cmpt_destroy(cmpt);
}
if (tvp) {
jas_tvparser_destroy(tvp);
}
return -1;
}
Commit Message: CVE-2015-5221
CWE ID: CWE-416
Target: 1
Example 2:
Code: ModuleExport size_t RegisterCMYKImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CMYK");
entry->decoder=(DecodeImageHandler *) ReadCMYKImage;
entry->encoder=(EncodeImageHandler *) WriteCMYKImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw cyan, magenta, yellow, and black "
"samples");
entry->module=ConstantString("CMYK");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("CMYKA");
entry->decoder=(DecodeImageHandler *) ReadCMYKImage;
entry->encoder=(EncodeImageHandler *) WriteCMYKImage;
entry->raw=MagickTrue;
entry->endian_support=MagickTrue;
entry->description=ConstantString("Raw cyan, magenta, yellow, black, and "
"alpha samples");
entry->module=ConstantString("CMYK");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message:
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int nbd_receive_negotiate(QIOChannel *ioc, const char *name, uint16_t *flags,
QCryptoTLSCreds *tlscreds, const char *hostname,
QIOChannel **outioc,
off_t *size, Error **errp)
{
char buf[256];
uint64_t magic, s;
int rc;
bool zeroes = true;
TRACE("Receiving negotiation tlscreds=%p hostname=%s.",
tlscreds, hostname ? hostname : "<null>");
rc = -EINVAL;
if (outioc) {
*outioc = NULL;
}
if (tlscreds && !outioc) {
error_setg(errp, "Output I/O channel required for TLS");
goto fail;
}
if (read_sync(ioc, buf, 8) != 8) {
error_setg(errp, "Failed to read data");
goto fail;
}
buf[8] = '\0';
if (strlen(buf) == 0) {
error_setg(errp, "Server connection closed unexpectedly");
goto fail;
}
TRACE("Magic is %c%c%c%c%c%c%c%c",
qemu_isprint(buf[0]) ? buf[0] : '.',
qemu_isprint(buf[1]) ? buf[1] : '.',
qemu_isprint(buf[2]) ? buf[2] : '.',
qemu_isprint(buf[3]) ? buf[3] : '.',
qemu_isprint(buf[4]) ? buf[4] : '.',
qemu_isprint(buf[5]) ? buf[5] : '.',
qemu_isprint(buf[6]) ? buf[6] : '.',
qemu_isprint(buf[7]) ? buf[7] : '.');
if (memcmp(buf, "NBDMAGIC", 8) != 0) {
error_setg(errp, "Invalid magic received");
goto fail;
}
if (read_sync(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
error_setg(errp, "Failed to read magic");
goto fail;
}
magic = be64_to_cpu(magic);
TRACE("Magic is 0x%" PRIx64, magic);
if (magic == NBD_OPTS_MAGIC) {
uint32_t clientflags = 0;
uint16_t globalflags;
bool fixedNewStyle = false;
if (read_sync(ioc, &globalflags, sizeof(globalflags)) !=
sizeof(globalflags)) {
error_setg(errp, "Failed to read server flags");
goto fail;
}
globalflags = be16_to_cpu(globalflags);
TRACE("Global flags are %" PRIx32, globalflags);
if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
fixedNewStyle = true;
TRACE("Server supports fixed new style");
clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
}
if (globalflags & NBD_FLAG_NO_ZEROES) {
zeroes = false;
TRACE("Server supports no zeroes");
clientflags |= NBD_FLAG_C_NO_ZEROES;
}
/* client requested flags */
clientflags = cpu_to_be32(clientflags);
if (write_sync(ioc, &clientflags, sizeof(clientflags)) !=
sizeof(clientflags)) {
error_setg(errp, "Failed to send clientflags field");
goto fail;
}
if (tlscreds) {
if (fixedNewStyle) {
*outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
if (!*outioc) {
goto fail;
}
ioc = *outioc;
} else {
error_setg(errp, "Server does not support STARTTLS");
goto fail;
}
}
if (!name) {
TRACE("Using default NBD export name \"\"");
name = "";
}
if (fixedNewStyle) {
/* Check our desired export is present in the
* server export list. Since NBD_OPT_EXPORT_NAME
* cannot return an error message, running this
* query gives us good error reporting if the
* server required TLS
*/
if (nbd_receive_query_exports(ioc, name, errp) < 0) {
goto fail;
}
}
/* write the export name request */
if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
errp) < 0) {
goto fail;
}
/* Read the response */
if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {
error_setg(errp, "Failed to read export length");
goto fail;
}
*size = be64_to_cpu(s);
if (read_sync(ioc, flags, sizeof(*flags)) != sizeof(*flags)) {
error_setg(errp, "Failed to read export flags");
goto fail;
}
be16_to_cpus(flags);
} else if (magic == NBD_CLIENT_MAGIC) {
uint32_t oldflags;
if (name) {
error_setg(errp, "Server does not support export names");
goto fail;
}
if (tlscreds) {
error_setg(errp, "Server does not support STARTTLS");
goto fail;
}
if (read_sync(ioc, &s, sizeof(s)) != sizeof(s)) {
error_setg(errp, "Failed to read export length");
goto fail;
}
*size = be64_to_cpu(s);
TRACE("Size is %" PRIu64, *size);
if (read_sync(ioc, &oldflags, sizeof(oldflags)) != sizeof(oldflags)) {
error_setg(errp, "Failed to read export flags");
goto fail;
}
be32_to_cpus(&oldflags);
if (oldflags & ~0xffff) {
error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
goto fail;
}
*flags = oldflags;
} else {
error_setg(errp, "Bad magic received");
goto fail;
}
TRACE("Size is %" PRIu64 ", export flags %" PRIx16, *size, *flags);
if (zeroes && drop_sync(ioc, 124) != 124) {
error_setg(errp, "Failed to read reserved block");
goto fail;
}
rc = 0;
fail:
return rc;
}
Commit Message:
CWE ID: CWE-20
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderViewImpl::NavigateBackForwardSoon(int offset) {
history_navigation_virtual_time_pauser_ =
RenderThreadImpl::current()
->GetWebMainThreadScheduler()
->CreateWebScopedVirtualTimePauser(
"NavigateBackForwardSoon",
blink::WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant);
history_navigation_virtual_time_pauser_.PauseVirtualTime();
Send(new ViewHostMsg_GoToEntryAtOffset(GetRoutingID(), offset));
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
Target: 1
Example 2:
Code: void LocalFrameClientImpl::FrameFocused() const {
if (web_frame_->Client())
web_frame_->Client()->FrameFocused();
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: UINT CSoundFile::ReadSample(MODINSTRUMENT *pIns, UINT nFlags, LPCSTR lpMemFile, DWORD dwMemLength)
{
UINT len = 0, mem = pIns->nLength+6;
if ((!pIns) || (pIns->nLength < 4) || (!lpMemFile)) return 0;
if (pIns->nLength > MAX_SAMPLE_LENGTH) pIns->nLength = MAX_SAMPLE_LENGTH;
pIns->uFlags &= ~(CHN_16BIT|CHN_STEREO);
if (nFlags & RSF_16BIT)
{
mem *= 2;
pIns->uFlags |= CHN_16BIT;
}
if (nFlags & RSF_STEREO)
{
mem *= 2;
pIns->uFlags |= CHN_STEREO;
}
if ((pIns->pSample = AllocateSample(mem)) == NULL)
{
pIns->nLength = 0;
return 0;
}
switch(nFlags)
{
case RS_PCM8U:
{
len = pIns->nLength;
if (len > dwMemLength) len = pIns->nLength = dwMemLength;
signed char *pSample = pIns->pSample;
for (UINT j=0; j<len; j++) pSample[j] = (signed char)(lpMemFile[j] - 0x80);
}
break;
case RS_PCM8D:
{
len = pIns->nLength;
if (len > dwMemLength) break;
signed char *pSample = pIns->pSample;
const signed char *p = (const signed char *)lpMemFile;
int delta = 0;
for (UINT j=0; j<len; j++)
{
delta += p[j];
*pSample++ = (signed char)delta;
}
}
break;
case RS_ADPCM4:
{
len = (pIns->nLength + 1) / 2;
if (len > dwMemLength - 16) break;
memcpy(CompressionTable, lpMemFile, 16);
lpMemFile += 16;
signed char *pSample = pIns->pSample;
signed char delta = 0;
for (UINT j=0; j<len; j++)
{
BYTE b0 = (BYTE)lpMemFile[j];
BYTE b1 = (BYTE)(lpMemFile[j] >> 4);
delta = (signed char)GetDeltaValue((int)delta, b0);
pSample[0] = delta;
delta = (signed char)GetDeltaValue((int)delta, b1);
pSample[1] = delta;
pSample += 2;
}
len += 16;
}
break;
case RS_PCM16D:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
short int *pSample = (short int *)pIns->pSample;
short int *p = (short int *)lpMemFile;
int delta16 = 0;
for (UINT j=0; j<len; j+=2)
{
delta16 += bswapLE16(*p++);
*pSample++ = (short int)delta16;
}
}
break;
case RS_PCM16S:
{
len = pIns->nLength * 2;
if (len <= dwMemLength) memcpy(pIns->pSample, lpMemFile, len);
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j+=2)
{
short int s = bswapLE16(*pSample);
*pSample++ = s;
}
}
break;
case RS_PCM16M:
len = pIns->nLength * 2;
if (len > dwMemLength) len = dwMemLength & ~1;
if (len > 1)
{
signed char *pSample = (signed char *)pIns->pSample;
signed char *pSrc = (signed char *)lpMemFile;
for (UINT j=0; j<len; j+=2)
{
*((unsigned short *)(pSample+j)) = bswapBE16(*((unsigned short *)(pSrc+j)));
}
}
break;
case RS_PCM16U:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
short int *pSample = (short int *)pIns->pSample;
short int *pSrc = (short int *)lpMemFile;
for (UINT j=0; j<len; j+=2) *pSample++ = bswapLE16(*(pSrc++)) - 0x8000;
}
break;
case RS_STPCM16M:
len = pIns->nLength * 2;
if (len*2 <= dwMemLength)
{
signed char *pSample = (signed char *)pIns->pSample;
signed char *pSrc = (signed char *)lpMemFile;
for (UINT j=0; j<len; j+=2)
{
*((unsigned short *)(pSample+j*2)) = bswapBE16(*((unsigned short *)(pSrc+j)));
*((unsigned short *)(pSample+j*2+2)) = bswapBE16(*((unsigned short *)(pSrc+j+len)));
}
len *= 2;
}
break;
case RS_STPCM8S:
case RS_STPCM8U:
case RS_STPCM8D:
{
int iadd_l = 0, iadd_r = 0;
if (nFlags == RS_STPCM8U) { iadd_l = iadd_r = -128; }
len = pIns->nLength;
signed char *psrc = (signed char *)lpMemFile;
signed char *pSample = (signed char *)pIns->pSample;
if (len*2 > dwMemLength) break;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed char)(psrc[0] + iadd_l);
pSample[j*2+1] = (signed char)(psrc[len] + iadd_r);
psrc++;
if (nFlags == RS_STPCM8D)
{
iadd_l = pSample[j*2];
iadd_r = pSample[j*2+1];
}
}
len *= 2;
}
break;
case RS_STPCM16S:
case RS_STPCM16U:
case RS_STPCM16D:
{
int iadd_l = 0, iadd_r = 0;
if (nFlags == RS_STPCM16U) { iadd_l = iadd_r = -0x8000; }
len = pIns->nLength;
short int *psrc = (short int *)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
if (len*4 > dwMemLength) break;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (short int) (bswapLE16(psrc[0]) + iadd_l);
pSample[j*2+1] = (short int) (bswapLE16(psrc[len]) + iadd_r);
psrc++;
if (nFlags == RS_STPCM16D)
{
iadd_l = pSample[j*2];
iadd_r = pSample[j*2+1];
}
}
len *= 4;
}
break;
case RS_IT2148:
case RS_IT21416:
case RS_IT2158:
case RS_IT21516:
len = dwMemLength;
if (len < 4) break;
if ((nFlags == RS_IT2148) || (nFlags == RS_IT2158))
ITUnpack8Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT2158));
else
ITUnpack16Bit(pIns->pSample, pIns->nLength, (LPBYTE)lpMemFile, dwMemLength, (nFlags == RS_IT21516));
break;
#ifndef MODPLUG_BASIC_SUPPORT
#ifndef FASTSOUNDLIB
case RS_STIPCM8S:
case RS_STIPCM8U:
{
int iadd = 0;
if (nFlags == RS_STIPCM8U) { iadd = -0x80; }
len = pIns->nLength;
if (len*2 > dwMemLength) len = dwMemLength >> 1;
LPBYTE psrc = (LPBYTE)lpMemFile;
LPBYTE pSample = (LPBYTE)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed char)(psrc[0] + iadd);
pSample[j*2+1] = (signed char)(psrc[1] + iadd);
psrc+=2;
}
len *= 2;
}
break;
case RS_STIPCM16S:
case RS_STIPCM16U:
{
int iadd = 0;
if (nFlags == RS_STIPCM16U) iadd = -32768;
len = pIns->nLength;
if (len*4 > dwMemLength) len = dwMemLength >> 2;
short int *psrc = (short int *)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (short int)(bswapLE16(psrc[0]) + iadd);
pSample[j*2+1] = (short int)(bswapLE16(psrc[1]) + iadd);
psrc += 2;
}
len *= 4;
}
break;
case RS_AMS8:
case RS_AMS16:
len = 9;
if (dwMemLength > 9)
{
const char *psrc = lpMemFile;
char packcharacter = lpMemFile[8], *pdest = (char *)pIns->pSample;
len += bswapLE32(*((LPDWORD)(lpMemFile+4)));
if (len > dwMemLength) len = dwMemLength;
UINT dmax = pIns->nLength;
if (pIns->uFlags & CHN_16BIT) dmax <<= 1;
AMSUnpack(psrc+9, len-9, pdest, dmax, packcharacter);
}
break;
case RS_PTM8DTO16:
{
len = pIns->nLength * 2;
if (len > dwMemLength) break;
signed char *pSample = (signed char *)pIns->pSample;
signed char delta8 = 0;
for (UINT j=0; j<len; j++)
{
delta8 += lpMemFile[j];
*pSample++ = delta8;
}
WORD *pSampleW = (WORD *)pIns->pSample;
for (UINT j=0; j<len; j+=2) // swaparoni!
{
WORD s = bswapLE16(*pSampleW);
*pSampleW++ = s;
}
}
break;
case RS_MDL8:
case RS_MDL16:
len = dwMemLength;
if (len >= 4)
{
LPBYTE pSample = (LPBYTE)pIns->pSample;
LPBYTE ibuf = (LPBYTE)lpMemFile;
DWORD bitbuf = bswapLE32(*((DWORD *)ibuf));
UINT bitnum = 32;
BYTE dlt = 0, lowbyte = 0;
ibuf += 4;
for (UINT j=0; j<pIns->nLength; j++)
{
BYTE hibyte;
BYTE sign;
if (nFlags == RS_MDL16) lowbyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 8);
sign = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 1);
if (MDLReadBits(bitbuf, bitnum, ibuf, 1))
{
hibyte = (BYTE)MDLReadBits(bitbuf, bitnum, ibuf, 3);
} else
{
hibyte = 8;
while (!MDLReadBits(bitbuf, bitnum, ibuf, 1)) hibyte += 0x10;
hibyte += MDLReadBits(bitbuf, bitnum, ibuf, 4);
}
if (sign) hibyte = ~hibyte;
dlt += hibyte;
if (nFlags != RS_MDL16)
pSample[j] = dlt;
else
{
pSample[j<<1] = lowbyte;
pSample[(j<<1)+1] = dlt;
}
}
}
break;
case RS_DMF8:
case RS_DMF16:
len = dwMemLength;
if (len >= 4)
{
UINT maxlen = pIns->nLength;
if (pIns->uFlags & CHN_16BIT) maxlen <<= 1;
LPBYTE ibuf = (LPBYTE)lpMemFile, ibufmax = (LPBYTE)(lpMemFile+dwMemLength);
len = DMFUnpack((LPBYTE)pIns->pSample, ibuf, ibufmax, maxlen);
}
break;
#ifdef MODPLUG_TRACKER
case RS_PCM24S:
case RS_PCM32S:
len = pIns->nLength * 3;
if (nFlags == RS_PCM32S) len += pIns->nLength;
if (len > dwMemLength) break;
if (len > 4*8)
{
UINT slsize = (nFlags == RS_PCM32S) ? 4 : 3;
LPBYTE pSrc = (LPBYTE)lpMemFile;
LONG max = 255;
if (nFlags == RS_PCM32S) pSrc++;
for (UINT j=0; j<len; j+=slsize)
{
LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
l /= 256;
if (l > max) max = l;
if (-l > max) max = -l;
}
max = (max / 128) + 1;
signed short *pDest = (signed short *)pIns->pSample;
for (UINT k=0; k<len; k+=slsize)
{
LONG l = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
*pDest++ = (signed short)(l / max);
}
}
break;
case RS_STIPCM24S:
case RS_STIPCM32S:
len = pIns->nLength * 6;
if (nFlags == RS_STIPCM32S) len += pIns->nLength * 2;
if (len > dwMemLength) break;
if (len > 8*8)
{
UINT slsize = (nFlags == RS_STIPCM32S) ? 4 : 3;
LPBYTE pSrc = (LPBYTE)lpMemFile;
LONG max = 255;
if (nFlags == RS_STIPCM32S) pSrc++;
for (UINT j=0; j<len; j+=slsize)
{
LONG l = ((((pSrc[j+2] << 8) + pSrc[j+1]) << 8) + pSrc[j]) << 8;
l /= 256;
if (l > max) max = l;
if (-l > max) max = -l;
}
max = (max / 128) + 1;
signed short *pDest = (signed short *)pIns->pSample;
for (UINT k=0; k<len; k+=slsize)
{
LONG lr = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
k += slsize;
LONG ll = ((((pSrc[k+2] << 8) + pSrc[k+1]) << 8) + pSrc[k]) << 8;
pDest[0] = (signed short)ll;
pDest[1] = (signed short)lr;
pDest += 2;
}
}
break;
case RS_STIPCM16M:
{
len = pIns->nLength;
if (len*4 > dwMemLength) len = dwMemLength >> 2;
LPCBYTE psrc = (LPCBYTE)lpMemFile;
short int *pSample = (short int *)pIns->pSample;
for (UINT j=0; j<len; j++)
{
pSample[j*2] = (signed short)(((UINT)psrc[0] << 8) | (psrc[1]));
pSample[j*2+1] = (signed short)(((UINT)psrc[2] << 8) | (psrc[3]));
psrc += 4;
}
len *= 4;
}
break;
#endif // MODPLUG_TRACKER
#endif // !FASTSOUNDLIB
#endif // !MODPLUG_BASIC_SUPPORT
default:
len = pIns->nLength;
if (len > dwMemLength) len = pIns->nLength = dwMemLength;
memcpy(pIns->pSample, lpMemFile, len);
}
if (len > dwMemLength)
{
if (pIns->pSample)
{
pIns->nLength = 0;
FreeSample(pIns->pSample);
pIns->pSample = NULL;
}
return 0;
}
AdjustSampleLoop(pIns);
return len;
}
Commit Message:
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void* data)
{
usb_conv_info_t *usb_conv_info;
usb_ms_conv_info_t *usb_ms_conv_info;
proto_tree *tree;
proto_item *ti;
guint32 signature=0;
int offset=0;
gboolean is_request;
itl_nexus_t *itl;
itlq_nexus_t *itlq;
/* Reject the packet if data is NULL */
if (data == NULL)
return 0;
usb_conv_info = (usb_conv_info_t *)data;
/* verify that we do have a usb_ms_conv_info */
usb_ms_conv_info=(usb_ms_conv_info_t *)usb_conv_info->class_data;
if(!usb_ms_conv_info){
usb_ms_conv_info=wmem_new(wmem_file_scope(), usb_ms_conv_info_t);
usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope());
usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope());
usb_conv_info->class_data=usb_ms_conv_info;
}
is_request=(pinfo->srcport==NO_ENDPOINT);
col_set_str(pinfo->cinfo, COL_PROTOCOL, "USBMS");
col_clear(pinfo->cinfo, COL_INFO);
ti = proto_tree_add_protocol_format(parent_tree, proto_usb_ms, tvb, 0, -1, "USB Mass Storage");
tree = proto_item_add_subtree(ti, ett_usb_ms);
signature=tvb_get_letohl(tvb, offset);
/*
* SCSI CDB inside CBW
*/
if(is_request&&(signature==0x43425355)&&(tvb_reported_length(tvb)==31)){
tvbuff_t *cdb_tvb;
int cdbrlen, cdblen;
guint8 lun, flags;
guint32 datalen;
/* dCBWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCBWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCBWDataTransferLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWDataTransferLength, tvb, offset, 4, ENC_LITTLE_ENDIAN);
datalen=tvb_get_letohl(tvb, offset);
offset+=4;
/* dCBWFlags */
proto_tree_add_item(tree, hf_usb_ms_dCBWFlags, tvb, offset, 1, ENC_LITTLE_ENDIAN);
flags=tvb_get_guint8(tvb, offset);
offset+=1;
/* dCBWLUN */
proto_tree_add_item(tree, hf_usb_ms_dCBWTarget, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_tree_add_item(tree, hf_usb_ms_dCBWLUN, tvb, offset, 1, ENC_LITTLE_ENDIAN);
lun=tvb_get_guint8(tvb, offset)&0x0f;
offset+=1;
/* make sure we have a ITL structure for this LUN */
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, lun);
if(!itl){
itl=wmem_new(wmem_file_scope(), itl_nexus_t);
itl->cmdset=0xff;
itl->conversation=NULL;
wmem_tree_insert32(usb_ms_conv_info->itl, lun, itl);
}
/* make sure we have an ITLQ structure for this LUN/transaction */
itlq=(itlq_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
itlq=wmem_new(wmem_file_scope(), itlq_nexus_t);
itlq->lun=lun;
itlq->scsi_opcode=0xffff;
itlq->task_flags=0;
if(datalen){
if(flags&0x80){
itlq->task_flags|=SCSI_DATA_READ;
} else {
itlq->task_flags|=SCSI_DATA_WRITE;
}
}
itlq->data_length=datalen;
itlq->bidir_data_length=0;
itlq->fc_time=pinfo->abs_ts;
itlq->first_exchange_frame=pinfo->num;
itlq->last_exchange_frame=0;
itlq->flags=0;
itlq->alloc_len=0;
itlq->extra_data=NULL;
wmem_tree_insert32(usb_ms_conv_info->itlq, pinfo->num, itlq);
}
/* dCBWCBLength */
proto_tree_add_item(tree, hf_usb_ms_dCBWCBLength, tvb, offset, 1, ENC_LITTLE_ENDIAN);
cdbrlen=tvb_get_guint8(tvb, offset)&0x1f;
offset+=1;
cdblen=cdbrlen;
if(cdblen>tvb_captured_length_remaining(tvb, offset)){
cdblen=tvb_captured_length_remaining(tvb, offset);
}
if(cdblen){
cdb_tvb=tvb_new_subset(tvb, offset, cdblen, cdbrlen);
dissect_scsi_cdb(cdb_tvb, pinfo, parent_tree, SCSI_DEV_UNKNOWN, itlq, itl);
}
return tvb_captured_length(tvb);
}
/*
* SCSI RESPONSE inside CSW
*/
if((!is_request)&&(signature==0x53425355)&&(tvb_reported_length(tvb)==13)){
guint8 status;
/* dCSWSignature */
proto_tree_add_item(tree, hf_usb_ms_dCSWSignature, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWTag */
proto_tree_add_item(tree, hf_usb_ms_dCBWTag, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWDataResidue */
proto_tree_add_item(tree, hf_usb_ms_dCSWDataResidue, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset+=4;
/* dCSWStatus */
proto_tree_add_item(tree, hf_usb_ms_dCSWStatus, tvb, offset, 1, ENC_LITTLE_ENDIAN);
status=tvb_get_guint8(tvb, offset);
/*offset+=1;*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itlq->last_exchange_frame=pinfo->num;
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
if(!status){
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0);
} else {
/* just send "check condition" */
dissect_scsi_rsp(tvb, pinfo, parent_tree, itlq, itl, 0x02);
}
return tvb_captured_length(tvb);
}
/*
* Ok it was neither CDB not STATUS so just assume it is either data in/out
*/
itlq=(itlq_nexus_t *)wmem_tree_lookup32_le(usb_ms_conv_info->itlq, pinfo->num);
if(!itlq){
return tvb_captured_length(tvb);
}
itl=(itl_nexus_t *)wmem_tree_lookup32(usb_ms_conv_info->itl, itlq->lun);
if(!itl){
return tvb_captured_length(tvb);
}
dissect_scsi_payload(tvb, pinfo, parent_tree, is_request, itlq, itl, 0);
return tvb_captured_length(tvb);
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: lacks_mount (NautilusFile *file)
{
return (!file->details->mount_is_up_to_date &&
(
/* Unix mountpoint, could be a GMount */
file->details->is_mountpoint ||
/* The toplevel directory of something */
(file->details->type == G_FILE_TYPE_DIRECTORY &&
nautilus_file_is_self_owned (file)) ||
/* Mountable, could be a mountpoint */
(file->details->type == G_FILE_TYPE_MOUNTABLE)
)
);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xmlParsePI(xmlParserCtxtPtr ctxt) {
xmlChar *buf = NULL;
int len = 0;
int size = XML_PARSER_BUFFER_SIZE;
int cur, l;
const xmlChar *target;
xmlParserInputState state;
int count = 0;
if ((RAW == '<') && (NXT(1) == '?')) {
xmlParserInputPtr input = ctxt->input;
state = ctxt->instate;
ctxt->instate = XML_PARSER_PI;
/*
* this is a Processing Instruction.
*/
SKIP(2);
SHRINK;
/*
* Parse the target name and check for special support like
* namespace.
*/
target = xmlParsePITarget(ctxt);
if (target != NULL) {
if ((RAW == '?') && (NXT(1) == '>')) {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, NULL);
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
return;
}
buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar));
if (buf == NULL) {
xmlErrMemory(ctxt, NULL);
ctxt->instate = state;
return;
}
cur = CUR;
if (!IS_BLANK(cur)) {
xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED,
"ParsePI: PI %s space expected\n", target);
}
SKIP_BLANKS;
cur = CUR_CHAR(l);
while (IS_CHAR(cur) && /* checked */
((cur != '?') || (NXT(1) != '>'))) {
if (len + 5 >= size) {
xmlChar *tmp;
size *= 2;
tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar));
if (tmp == NULL) {
xmlErrMemory(ctxt, NULL);
xmlFree(buf);
ctxt->instate = state;
return;
}
buf = tmp;
}
count++;
if (count > 50) {
GROW;
count = 0;
}
COPY_BUF(l,buf,len,cur);
NEXTL(l);
cur = CUR_CHAR(l);
if (cur == 0) {
SHRINK;
GROW;
cur = CUR_CHAR(l);
}
}
buf[len] = 0;
if (cur != '?') {
xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED,
"ParsePI: PI %s never end ...\n", target);
} else {
if (input != ctxt->input) {
xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED,
"PI declaration doesn't start and stop in the same entity\n");
}
SKIP(2);
#ifdef LIBXML_CATALOG_ENABLED
if (((state == XML_PARSER_MISC) ||
(state == XML_PARSER_START)) &&
(xmlStrEqual(target, XML_CATALOG_PI))) {
xmlCatalogAllow allow = xmlCatalogGetDefaults();
if ((allow == XML_CATA_ALLOW_DOCUMENT) ||
(allow == XML_CATA_ALLOW_ALL))
xmlParseCatalogPI(ctxt, buf);
}
#endif
/*
* SAX: PI detected.
*/
if ((ctxt->sax) && (!ctxt->disableSAX) &&
(ctxt->sax->processingInstruction != NULL))
ctxt->sax->processingInstruction(ctxt->userData,
target, buf);
}
xmlFree(buf);
} else {
xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL);
}
if (ctxt->instate != XML_PARSER_EOF)
ctxt->instate = state;
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
if (npages && !old.npages) {
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(&new, npages))
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
if (!npages) {
struct kvm_memory_slot *slot;
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
update_memslots(slots, NULL);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map/unmap the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
} else
kvm_iommu_unmap_pages(kvm, &old);
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
update_memslots(slots, &new);
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
/*
* If the new memory slot is created, we need to clear all
* mmio sptes.
*/
if (npages && old.base_gfn != mem->guest_phys_addr >> PAGE_SHIFT)
kvm_arch_flush_shadow_all(kvm);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
Commit Message: KVM: perform an invalid memslot step for gpa base change
PPC must flush all translations before the new memory slot
is visible.
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: FreeExpr(ExprDef *expr)
{
if (!expr)
return;
switch (expr->expr.op) {
case EXPR_ACTION_LIST:
case EXPR_NEGATE:
case EXPR_UNARY_PLUS:
case EXPR_NOT:
case EXPR_INVERT:
FreeStmt((ParseCommon *) expr->unary.child);
break;
case EXPR_DIVIDE:
case EXPR_ADD:
case EXPR_SUBTRACT:
case EXPR_MULTIPLY:
case EXPR_ASSIGN:
FreeStmt((ParseCommon *) expr->binary.left);
FreeStmt((ParseCommon *) expr->binary.right);
break;
case EXPR_ACTION_DECL:
FreeStmt((ParseCommon *) expr->action.args);
break;
case EXPR_ARRAY_REF:
FreeStmt((ParseCommon *) expr->array_ref.entry);
break;
case EXPR_KEYSYM_LIST:
darray_free(expr->keysym_list.syms);
darray_free(expr->keysym_list.symsMapIndex);
darray_free(expr->keysym_list.symsNumEntries);
break;
default:
break;
}
}
Commit Message: xkbcomp: fix pointer value for FreeStmt
Signed-off-by: Peter Hutterer <[email protected]>
CWE ID: CWE-416
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: long Chapters::Edition::ParseAtom(
IMkvReader* pReader,
long long pos,
long long size)
{
if (!ExpandAtomsArray())
return -1;
Atom& a = m_atoms[m_atoms_count++];
a.Init();
return a.Parse(pReader, pos, size);
}
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
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int NsGetParameter(preproc_effect_t *effect,
void *pParam,
uint32_t *pValueSize,
void *pValue)
{
int status = 0;
return status;
}
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebContentsImpl::MediaStoppedPlaying(
const WebContentsObserver::MediaPlayerInfo& media_info,
const WebContentsObserver::MediaPlayerId& id,
WebContentsObserver::MediaStoppedReason reason) {
if (media_info.has_video)
currently_playing_video_count_--;
for (auto& observer : observers_)
observer.MediaStoppedPlaying(media_info, id, reason);
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: sequential_row(standard_display *dp, png_structp pp, png_infop pi,
PNG_CONST int iImage, PNG_CONST int iDisplay)
{
PNG_CONST int npasses = dp->npasses;
PNG_CONST int do_interlace = dp->do_interlace &&
dp->interlace_type == PNG_INTERLACE_ADAM7;
PNG_CONST png_uint_32 height = standard_height(pp, dp->id);
PNG_CONST png_uint_32 width = standard_width(pp, dp->id);
PNG_CONST png_store* ps = dp->ps;
int pass;
for (pass=0; pass<npasses; ++pass)
{
png_uint_32 y;
png_uint_32 wPass = PNG_PASS_COLS(width, pass);
for (y=0; y<height; ++y)
{
if (do_interlace)
{
/* wPass may be zero or this row may not be in this pass.
* png_read_row must not be called in either case.
*/
if (wPass > 0 && PNG_ROW_IN_INTERLACE_PASS(y, pass))
{
/* Read the row into a pair of temporary buffers, then do the
* merge here into the output rows.
*/
png_byte row[STANDARD_ROWMAX], display[STANDARD_ROWMAX];
/* The following aids (to some extent) error detection - we can
* see where png_read_row wrote. Use opposite values in row and
* display to make this easier. Don't use 0xff (which is used in
* the image write code to fill unused bits) or 0 (which is a
* likely value to overwrite unused bits with).
*/
memset(row, 0xc5, sizeof row);
memset(display, 0x5c, sizeof display);
png_read_row(pp, row, display);
if (iImage >= 0)
deinterlace_row(store_image_row(ps, pp, iImage, y), row,
dp->pixel_size, dp->w, pass);
if (iDisplay >= 0)
deinterlace_row(store_image_row(ps, pp, iDisplay, y), display,
dp->pixel_size, dp->w, pass);
}
}
else
png_read_row(pp,
iImage >= 0 ? store_image_row(ps, pp, iImage, y) : NULL,
iDisplay >= 0 ? store_image_row(ps, pp, iDisplay, y) : NULL);
}
}
/* And finish the read operation (only really necessary if the caller wants
* to find additional data in png_info from chunks after the last IDAT.)
*/
png_read_end(pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: PassRefPtr<RTCSessionDescriptionRequestImpl> RTCSessionDescriptionRequestImpl::create(ScriptExecutionContext* context, PassRefPtr<RTCSessionDescriptionCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback)
{
RefPtr<RTCSessionDescriptionRequestImpl> request = adoptRef(new RTCSessionDescriptionRequestImpl(context, successCallback, errorCallback));
request->suspendIfNeeded();
return request.release();
}
Commit Message: Unreviewed, rolling out r127612, r127660, and r127664.
http://trac.webkit.org/changeset/127612
http://trac.webkit.org/changeset/127660
http://trac.webkit.org/changeset/127664
https://bugs.webkit.org/show_bug.cgi?id=95920
Source/Platform:
* Platform.gypi:
* chromium/public/WebRTCPeerConnectionHandler.h:
(WebKit):
(WebRTCPeerConnectionHandler):
* chromium/public/WebRTCVoidRequest.h: Removed.
Source/WebCore:
* CMakeLists.txt:
* GNUmakefile.list.am:
* Modules/mediastream/RTCErrorCallback.h:
(WebCore):
(RTCErrorCallback):
* Modules/mediastream/RTCErrorCallback.idl:
* Modules/mediastream/RTCPeerConnection.cpp:
(WebCore::RTCPeerConnection::createOffer):
* Modules/mediastream/RTCPeerConnection.h:
(WebCore):
(RTCPeerConnection):
* Modules/mediastream/RTCPeerConnection.idl:
* Modules/mediastream/RTCSessionDescriptionCallback.h:
(WebCore):
(RTCSessionDescriptionCallback):
* Modules/mediastream/RTCSessionDescriptionCallback.idl:
* Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp:
(WebCore::RTCSessionDescriptionRequestImpl::create):
(WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl):
(WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded):
(WebCore::RTCSessionDescriptionRequestImpl::requestFailed):
(WebCore::RTCSessionDescriptionRequestImpl::clear):
* Modules/mediastream/RTCSessionDescriptionRequestImpl.h:
(RTCSessionDescriptionRequestImpl):
* Modules/mediastream/RTCVoidRequestImpl.cpp: Removed.
* Modules/mediastream/RTCVoidRequestImpl.h: Removed.
* WebCore.gypi:
* platform/chromium/support/WebRTCVoidRequest.cpp: Removed.
* platform/mediastream/RTCPeerConnectionHandler.cpp:
(RTCPeerConnectionHandlerDummy):
(WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy):
* platform/mediastream/RTCPeerConnectionHandler.h:
(WebCore):
(WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler):
(RTCPeerConnectionHandler):
(WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler):
* platform/mediastream/RTCVoidRequest.h: Removed.
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp:
* platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h:
(RTCPeerConnectionHandlerChromium):
Tools:
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp:
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask):
(MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask):
(MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid):
(MockWebRTCPeerConnectionHandler::createOffer):
* DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h:
(MockWebRTCPeerConnectionHandler):
(SuccessCallbackTask):
(FailureCallbackTask):
LayoutTests:
* fast/mediastream/RTCPeerConnection-createOffer.html:
* fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-localDescription.html: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed.
* fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed.
git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void announce(int mod)
{
struct ifsock *ifs;
logit(LOG_INFO, "Sending SSDP NOTIFY new:%d ...", mod);
LIST_FOREACH(ifs, &il, link) {
size_t i;
if (mod && !ifs->mod)
continue;
ifs->mod = 0;
for (i = 0; supported_types[i]; i++) {
/* UUID sent in SSDP_ST_ALL, first announce */
if (!strcmp(supported_types[i], uuid))
continue;
send_message(ifs, supported_types[i], NULL);
}
}
}
Commit Message: Fix #1: Ensure recv buf is always NUL terminated
Signed-off-by: Joachim Nilsson <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void skb_release_data(struct sk_buff *skb)
{
if (!skb->cloned ||
!atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
&skb_shinfo(skb)->dataref)) {
if (skb_shinfo(skb)->nr_frags) {
int i;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
skb_frag_unref(skb, i);
}
/*
* If skb buf is from userspace, we need to notify the caller
* the lower device DMA has done;
*/
if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
struct ubuf_info *uarg;
uarg = skb_shinfo(skb)->destructor_arg;
if (uarg->callback)
uarg->callback(uarg, true);
}
if (skb_has_frag_list(skb))
skb_drop_fraglist(skb);
skb_free_head(skb);
}
}
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
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static __always_inline ssize_t __mcopy_atomic(struct mm_struct *dst_mm,
unsigned long dst_start,
unsigned long src_start,
unsigned long len,
bool zeropage,
bool *mmap_changing)
{
struct vm_area_struct *dst_vma;
ssize_t err;
pmd_t *dst_pmd;
unsigned long src_addr, dst_addr;
long copied;
struct page *page;
/*
* Sanitize the command parameters:
*/
BUG_ON(dst_start & ~PAGE_MASK);
BUG_ON(len & ~PAGE_MASK);
/* Does the address range wrap, or is the span zero-sized? */
BUG_ON(src_start + len <= src_start);
BUG_ON(dst_start + len <= dst_start);
src_addr = src_start;
dst_addr = dst_start;
copied = 0;
page = NULL;
retry:
down_read(&dst_mm->mmap_sem);
/*
* If memory mappings are changing because of non-cooperative
* operation (e.g. mremap) running in parallel, bail out and
* request the user to retry later
*/
err = -EAGAIN;
if (mmap_changing && READ_ONCE(*mmap_changing))
goto out_unlock;
/*
* Make sure the vma is not shared, that the dst range is
* both valid and fully within a single existing vma.
*/
err = -ENOENT;
dst_vma = find_vma(dst_mm, dst_start);
if (!dst_vma)
goto out_unlock;
/*
* Be strict and only allow __mcopy_atomic on userfaultfd
* registered ranges to prevent userland errors going
* unnoticed. As far as the VM consistency is concerned, it
* would be perfectly safe to remove this check, but there's
* no useful usage for __mcopy_atomic ouside of userfaultfd
* registered ranges. This is after all why these are ioctls
* belonging to the userfaultfd and not syscalls.
*/
if (!dst_vma->vm_userfaultfd_ctx.ctx)
goto out_unlock;
if (dst_start < dst_vma->vm_start ||
dst_start + len > dst_vma->vm_end)
goto out_unlock;
err = -EINVAL;
/*
* shmem_zero_setup is invoked in mmap for MAP_ANONYMOUS|MAP_SHARED but
* it will overwrite vm_ops, so vma_is_anonymous must return false.
*/
if (WARN_ON_ONCE(vma_is_anonymous(dst_vma) &&
dst_vma->vm_flags & VM_SHARED))
goto out_unlock;
/*
* If this is a HUGETLB vma, pass off to appropriate routine
*/
if (is_vm_hugetlb_page(dst_vma))
return __mcopy_atomic_hugetlb(dst_mm, dst_vma, dst_start,
src_start, len, zeropage);
if (!vma_is_anonymous(dst_vma) && !vma_is_shmem(dst_vma))
goto out_unlock;
/*
* Ensure the dst_vma has a anon_vma or this page
* would get a NULL anon_vma when moved in the
* dst_vma.
*/
err = -ENOMEM;
if (!(dst_vma->vm_flags & VM_SHARED) &&
unlikely(anon_vma_prepare(dst_vma)))
goto out_unlock;
while (src_addr < src_start + len) {
pmd_t dst_pmdval;
BUG_ON(dst_addr >= dst_start + len);
dst_pmd = mm_alloc_pmd(dst_mm, dst_addr);
if (unlikely(!dst_pmd)) {
err = -ENOMEM;
break;
}
dst_pmdval = pmd_read_atomic(dst_pmd);
/*
* If the dst_pmd is mapped as THP don't
* override it and just be strict.
*/
if (unlikely(pmd_trans_huge(dst_pmdval))) {
err = -EEXIST;
break;
}
if (unlikely(pmd_none(dst_pmdval)) &&
unlikely(__pte_alloc(dst_mm, dst_pmd, dst_addr))) {
err = -ENOMEM;
break;
}
/* If an huge pmd materialized from under us fail */
if (unlikely(pmd_trans_huge(*dst_pmd))) {
err = -EFAULT;
break;
}
BUG_ON(pmd_none(*dst_pmd));
BUG_ON(pmd_trans_huge(*dst_pmd));
err = mfill_atomic_pte(dst_mm, dst_pmd, dst_vma, dst_addr,
src_addr, &page, zeropage);
cond_resched();
if (unlikely(err == -ENOENT)) {
void *page_kaddr;
up_read(&dst_mm->mmap_sem);
BUG_ON(!page);
page_kaddr = kmap(page);
err = copy_from_user(page_kaddr,
(const void __user *) src_addr,
PAGE_SIZE);
kunmap(page);
if (unlikely(err)) {
err = -EFAULT;
goto out;
}
goto retry;
} else
BUG_ON(page);
if (!err) {
dst_addr += PAGE_SIZE;
src_addr += PAGE_SIZE;
copied += PAGE_SIZE;
if (fatal_signal_pending(current))
err = -EINTR;
}
if (err)
break;
}
out_unlock:
up_read(&dst_mm->mmap_sem);
out:
if (page)
put_page(page);
BUG_ON(copied < 0);
BUG_ON(err > 0);
BUG_ON(!copied && !err);
return copied ? copied : err;
}
Commit Message: userfaultfd: shmem/hugetlbfs: only allow to register VM_MAYWRITE vmas
After the VMA to register the uffd onto is found, check that it has
VM_MAYWRITE set before allowing registration. This way we inherit all
common code checks before allowing to fill file holes in shmem and
hugetlbfs with UFFDIO_COPY.
The userfaultfd memory model is not applicable for readonly files unless
it's a MAP_PRIVATE.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: ff62a3421044 ("hugetlb: implement memfd sealing")
Signed-off-by: Andrea Arcangeli <[email protected]>
Reviewed-by: Mike Rapoport <[email protected]>
Reviewed-by: Hugh Dickins <[email protected]>
Reported-by: Jann Horn <[email protected]>
Fixes: 4c27fe4c4c84 ("userfaultfd: shmem: add shmem_mcopy_atomic_pte for userfaultfd support")
Cc: <[email protected]>
Cc: "Dr. David Alan Gilbert" <[email protected]>
Cc: Mike Kravetz <[email protected]>
Cc: Peter Xu <[email protected]>
Cc: [email protected]
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static int sc_pkcs15emu_sc_hsm_add_prkd(sc_pkcs15_card_t * p15card, u8 keyid) {
sc_card_t *card = p15card->card;
sc_pkcs15_cert_info_t cert_info;
sc_pkcs15_object_t cert_obj;
struct sc_pkcs15_object prkd;
sc_pkcs15_prkey_info_t *key_info;
u8 fid[2];
/* enough to hold a complete certificate */
u8 efbin[4096];
u8 *ptr;
size_t len;
int r;
fid[0] = PRKD_PREFIX;
fid[1] = keyid;
/* Try to select a related EF containing the PKCS#15 description of the key */
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
ptr = efbin;
memset(&prkd, 0, sizeof(prkd));
r = sc_pkcs15_decode_prkdf_entry(p15card, &prkd, (const u8 **)&ptr, &len);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.PRKD");
/* All keys require user PIN authentication */
prkd.auth_id.len = 1;
prkd.auth_id.value[0] = 1;
/*
* Set private key flag as all keys are private anyway
*/
prkd.flags |= SC_PKCS15_CO_FLAG_PRIVATE;
key_info = (sc_pkcs15_prkey_info_t *)prkd.data;
key_info->key_reference = keyid;
key_info->path.aid.len = 0;
if (prkd.type == SC_PKCS15_TYPE_PRKEY_RSA) {
r = sc_pkcs15emu_add_rsa_prkey(p15card, &prkd, key_info);
} else {
r = sc_pkcs15emu_add_ec_prkey(p15card, &prkd, key_info);
}
LOG_TEST_RET(card->ctx, r, "Could not add private key to framework");
/* Check if we also have a certificate for the private key */
fid[0] = EE_CERTIFICATE_PREFIX;
len = sizeof efbin;
r = read_file(p15card, fid, efbin, &len, 0);
LOG_TEST_RET(card->ctx, r, "Could not read EF");
if (efbin[0] == 0x67) { /* Decode CSR and create public key object */
sc_pkcs15emu_sc_hsm_add_pubkey(p15card, efbin, len, key_info, prkd.label);
free(key_info);
return SC_SUCCESS; /* Ignore any errors */
}
if (efbin[0] != 0x30) {
free(key_info);
return SC_SUCCESS;
}
memset(&cert_info, 0, sizeof(cert_info));
memset(&cert_obj, 0, sizeof(cert_obj));
cert_info.id = key_info->id;
sc_path_set(&cert_info.path, SC_PATH_TYPE_FILE_ID, fid, 2, 0, 0);
cert_info.path.count = -1;
if (p15card->opts.use_file_cache) {
/* look this up with our AID, which should already be cached from the
* call to `read_file`. This may have the side effect that OpenSC's
* caching layer re-selects our applet *if the cached file cannot be
* found/used* and we may loose the authentication status. We assume
* that caching works perfectly without this side effect. */
cert_info.path.aid = sc_hsm_aid;
}
strlcpy(cert_obj.label, prkd.label, sizeof(cert_obj.label));
r = sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
free(key_info);
LOG_TEST_RET(card->ctx, r, "Could not add certificate");
return SC_SUCCESS;
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void Document::Trace(blink::Visitor* visitor) {
visitor->Trace(imports_controller_);
visitor->Trace(doc_type_);
visitor->Trace(implementation_);
visitor->Trace(autofocus_element_);
visitor->Trace(focused_element_);
visitor->Trace(sequential_focus_navigation_starting_point_);
visitor->Trace(hover_element_);
visitor->Trace(active_element_);
visitor->Trace(document_element_);
visitor->Trace(root_scroller_controller_);
visitor->Trace(title_element_);
visitor->Trace(ax_object_cache_);
visitor->Trace(markers_);
visitor->Trace(css_target_);
visitor->Trace(current_script_stack_);
visitor->Trace(script_runner_);
visitor->Trace(lists_invalidated_at_document_);
visitor->Trace(node_lists_);
visitor->Trace(top_layer_elements_);
visitor->Trace(elem_sheet_);
visitor->Trace(node_iterators_);
visitor->Trace(ranges_);
visitor->Trace(style_engine_);
visitor->Trace(form_controller_);
visitor->Trace(visited_link_state_);
visitor->Trace(element_computed_style_map_);
visitor->Trace(frame_);
visitor->Trace(dom_window_);
visitor->Trace(fetcher_);
visitor->Trace(parser_);
visitor->Trace(context_features_);
visitor->Trace(style_sheet_list_);
visitor->Trace(document_timing_);
visitor->Trace(media_query_matcher_);
visitor->Trace(scripted_animation_controller_);
visitor->Trace(scripted_idle_task_controller_);
visitor->Trace(text_autosizer_);
visitor->Trace(registration_context_);
visitor->Trace(custom_element_microtask_run_queue_);
visitor->Trace(element_data_cache_);
visitor->Trace(use_elements_needing_update_);
visitor->Trace(timers_);
visitor->Trace(template_document_);
visitor->Trace(template_document_host_);
visitor->Trace(user_action_elements_);
visitor->Trace(svg_extensions_);
visitor->Trace(timeline_);
visitor->Trace(pending_animations_);
visitor->Trace(worklet_animation_controller_);
visitor->Trace(context_document_);
visitor->Trace(canvas_font_cache_);
visitor->Trace(intersection_observer_controller_);
visitor->Trace(snap_coordinator_);
visitor->Trace(resize_observer_controller_);
visitor->Trace(property_registry_);
visitor->Trace(network_state_observer_);
visitor->Trace(policy_);
visitor->Trace(slot_assignment_engine_);
visitor->Trace(viewport_data_);
visitor->Trace(lazy_load_image_observer_);
Supplementable<Document>::Trace(visitor);
TreeScope::Trace(visitor);
ContainerNode::Trace(visitor);
ExecutionContext::Trace(visitor);
SecurityContext::Trace(visitor);
DocumentShutdownNotifier::Trace(visitor);
SynchronousMutationNotifier::Trace(visitor);
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void VideoCaptureImpl::OnBufferCreated(int32_t buffer_id,
mojo::ScopedSharedBufferHandle handle) {
DVLOG(1) << __func__ << " buffer_id: " << buffer_id;
DCHECK(io_thread_checker_.CalledOnValidThread());
DCHECK(handle.is_valid());
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
bool read_only_flag = false;
const MojoResult result = mojo::UnwrapSharedMemoryHandle(
std::move(handle), &memory_handle, &memory_size, &read_only_flag);
DCHECK_EQ(MOJO_RESULT_OK, result);
DCHECK_GT(memory_size, 0u);
std::unique_ptr<base::SharedMemory> shm(
new base::SharedMemory(memory_handle, true /* read_only */));
if (!shm->Map(memory_size)) {
DLOG(ERROR) << "OnBufferCreated: Map failed.";
return;
}
const bool inserted =
client_buffers_
.insert(std::make_pair(buffer_id,
new ClientBuffer(std::move(shm), memory_size)))
.second;
DCHECK(inserted);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Target: 1
Example 2:
Code: __attribute__((weak)) const char *arch_vma_name(struct vm_area_struct *vma)
{
return NULL;
}
Commit Message: kernel/signal.c: stop info leak via the tkill and the tgkill syscalls
This fixes a kernel memory contents leak via the tkill and tgkill syscalls
for compat processes.
This is visible in the siginfo_t->_sifields._rt.si_sigval.sival_ptr field
when handling signals delivered from tkill.
The place of the infoleak:
int copy_siginfo_to_user32(compat_siginfo_t __user *to, siginfo_t *from)
{
...
put_user_ex(ptr_to_compat(from->si_ptr), &to->si_ptr);
...
}
Signed-off-by: Emese Revfy <[email protected]>
Reviewed-by: PaX Team <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool check_underflow(const struct arpt_entry *e)
{
const struct xt_entry_target *t;
unsigned int verdict;
if (!unconditional(e))
return false;
t = arpt_get_target_c(e);
if (strcmp(t->u.user.name, XT_STANDARD_TARGET) != 0)
return false;
verdict = ((struct xt_standard_target *)t)->verdict;
verdict = -verdict - 1;
return verdict == NF_DROP || verdict == NF_ACCEPT;
}
Commit Message: netfilter: x_tables: check for bogus target offset
We're currently asserting that targetoff + targetsize <= nextoff.
Extend it to also check that targetoff is >= sizeof(xt_entry).
Since this is generic code, add an argument pointing to the start of the
match/target, we can then derive the base structure size from the delta.
We also need the e->elems pointer in a followup change to validate matches.
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void __detach_mounts(struct dentry *dentry)
{
struct mountpoint *mp;
struct mount *mnt;
namespace_lock();
mp = lookup_mountpoint(dentry);
if (!mp)
goto out_unlock;
lock_mount_hash();
while (!hlist_empty(&mp->m_list)) {
mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list);
umount_tree(mnt, 0);
}
unlock_mount_hash();
put_mountpoint(mp);
out_unlock:
namespace_unlock();
}
Commit Message: mnt: Honor MNT_LOCKED when detaching mounts
Modify umount(MNT_DETACH) to keep mounts in the hash table that are
locked to their parent mounts, when the parent is lazily unmounted.
In mntput_no_expire detach the children from the hash table, depending
on mnt_pin_kill in cleanup_mnt to decrement the mnt_count of the children.
In __detach_mounts if there are any mounts that have been unmounted
but still are on the list of mounts of a mountpoint, remove their
children from the mount hash table and those children to the unmounted
list so they won't linger potentially indefinitely waiting for their
final mntput, now that the mounts serve no purpose.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-284
Target: 1
Example 2:
Code: static void OverloadedPerWorldBindingsMethodMethodForMainWorld(const v8::FunctionCallbackInfo<v8::Value>& info) {
scheduler::CooperativeSchedulingManager::Instance()->Safepoint();
bool is_arity_error = false;
switch (std::min(1, info.Length())) {
case 0:
if (true) {
OverloadedPerWorldBindingsMethod1MethodForMainWorld(info);
return;
}
break;
case 1:
if (true) {
OverloadedPerWorldBindingsMethod2MethodForMainWorld(info);
return;
}
break;
default:
is_arity_error = true;
}
ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "TestObject", "overloadedPerWorldBindingsMethod");
if (is_arity_error) {
}
exception_state.ThrowTypeError("No function was found that matched the signature provided.");
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: SPICE_GNUC_VISIBLE void spice_server_set_uuid(SpiceServer *s, const uint8_t uuid[16])
{
memcpy(spice_uuid, uuid, sizeof(spice_uuid));
spice_uuid_is_set = TRUE;
}
Commit Message:
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid)
{
struct hlist_head *hashent = ucounts_hashentry(ns, uid);
struct ucounts *ucounts, *new;
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (!ucounts) {
spin_unlock_irq(&ucounts_lock);
new = kzalloc(sizeof(*new), GFP_KERNEL);
if (!new)
return NULL;
new->ns = ns;
new->uid = uid;
atomic_set(&new->count, 0);
spin_lock_irq(&ucounts_lock);
ucounts = find_ucounts(ns, uid, hashent);
if (ucounts) {
kfree(new);
} else {
hlist_add_head(&new->node, hashent);
ucounts = new;
}
}
if (!atomic_add_unless(&ucounts->count, 1, INT_MAX))
ucounts = NULL;
spin_unlock_irq(&ucounts_lock);
return ucounts;
}
Commit Message: ucount: Remove the atomicity from ucount->count
Always increment/decrement ucount->count under the ucounts_lock. The
increments are there already and moving the decrements there means the
locking logic of the code is simpler. This simplification in the
locking logic fixes a race between put_ucounts and get_ucounts that
could result in a use-after-free because the count could go zero then
be found by get_ucounts and then be freed by put_ucounts.
A bug presumably this one was found by a combination of syzkaller and
KASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov
spotted the race in the code.
Cc: [email protected]
Fixes: f6b2db1a3e8d ("userns: Make the count of user namespaces per user")
Reported-by: JongHwan Kim <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Reviewed-by: Andrei Vagin <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: HTMLIFrameElement::ConstructContainerPolicy(Vector<String>* messages,
bool* old_syntax) const {
scoped_refptr<SecurityOrigin> src_origin = GetOriginForFeaturePolicy();
scoped_refptr<SecurityOrigin> self_origin = GetDocument().GetSecurityOrigin();
Vector<WebParsedFeaturePolicyDeclaration> container_policy =
ParseFeaturePolicyAttribute(allow_, self_origin, src_origin, messages,
old_syntax);
if (AllowFullscreen()) {
bool has_fullscreen_policy = false;
for (const auto& declaration : container_policy) {
if (declaration.feature == WebFeaturePolicyFeature::kFullscreen) {
has_fullscreen_policy = true;
if (messages) {
messages->push_back(
"allow attribute is overriding 'allowfullscreen'.");
}
break;
}
}
if (!has_fullscreen_policy) {
WebParsedFeaturePolicyDeclaration whitelist;
whitelist.feature = WebFeaturePolicyFeature::kFullscreen;
whitelist.matches_all_origins = true;
whitelist.origins = Vector<WebSecurityOrigin>(0UL);
container_policy.push_back(whitelist);
}
}
if (AllowPaymentRequest()) {
bool has_payment_policy = false;
for (const auto& declaration : container_policy) {
if (declaration.feature == WebFeaturePolicyFeature::kPayment) {
has_payment_policy = true;
if (messages) {
messages->push_back(
"allow attribute is overriding 'allowpaymentrequest'.");
}
break;
}
}
if (!has_payment_policy) {
WebParsedFeaturePolicyDeclaration whitelist;
whitelist.feature = WebFeaturePolicyFeature::kPayment;
whitelist.matches_all_origins = true;
whitelist.origins = Vector<WebSecurityOrigin>(0UL);
container_policy.push_back(whitelist);
}
}
return container_policy;
}
Commit Message: Resource Timing: Do not report subsequent navigations within subframes
We only want to record resource timing for the load that was initiated
by parent document. We filter out subsequent navigations for <iframe>,
but we should do it for other types of subframes too.
Bug: 780312
Change-Id: I3a7b9e1a365c99e24bb8dac190e88c7099fc3da5
Reviewed-on: https://chromium-review.googlesource.com/750487
Reviewed-by: Nate Chapin <[email protected]>
Commit-Queue: Kunihiko Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#513665}
CWE ID: CWE-601
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: xmlXPathCompOpEvalPositionalPredicate(xmlXPathParserContextPtr ctxt,
xmlXPathStepOpPtr op,
xmlNodeSetPtr set,
int contextSize,
int minPos,
int maxPos,
int hasNsNodes)
{
if (op->ch1 != -1) {
xmlXPathCompExprPtr comp = ctxt->comp;
if (comp->steps[op->ch1].op != XPATH_OP_PREDICATE) {
/*
* TODO: raise an internal error.
*/
}
contextSize = xmlXPathCompOpEvalPredicate(ctxt,
&comp->steps[op->ch1], set, contextSize, hasNsNodes);
CHECK_ERROR0;
if (contextSize <= 0)
return(0);
}
/*
* Check if the node set contains a sufficient number of nodes for
* the requested range.
*/
if (contextSize < minPos) {
xmlXPathNodeSetClear(set, hasNsNodes);
return(0);
}
if (op->ch2 == -1) {
/*
* TODO: Can this ever happen?
*/
return (contextSize);
} else {
xmlDocPtr oldContextDoc;
int i, pos = 0, newContextSize = 0, contextPos = 0, res;
xmlXPathStepOpPtr exprOp;
xmlXPathObjectPtr contextObj = NULL, exprRes = NULL;
xmlNodePtr oldContextNode, contextNode = NULL;
xmlXPathContextPtr xpctxt = ctxt->context;
#ifdef LIBXML_XPTR_ENABLED
/*
* URGENT TODO: Check the following:
* We don't expect location sets if evaluating prediates, right?
* Only filters should expect location sets, right?
*/
#endif /* LIBXML_XPTR_ENABLED */
/*
* Save old context.
*/
oldContextNode = xpctxt->node;
oldContextDoc = xpctxt->doc;
/*
* Get the expression of this predicate.
*/
exprOp = &ctxt->comp->steps[op->ch2];
for (i = 0; i < set->nodeNr; i++) {
if (set->nodeTab[i] == NULL)
continue;
contextNode = set->nodeTab[i];
xpctxt->node = contextNode;
xpctxt->contextSize = contextSize;
xpctxt->proximityPosition = ++contextPos;
/*
* Initialize the new set.
* Also set the xpath document in case things like
* key() evaluation are attempted on the predicate
*/
if ((contextNode->type != XML_NAMESPACE_DECL) &&
(contextNode->doc != NULL))
xpctxt->doc = contextNode->doc;
/*
* Evaluate the predicate expression with 1 context node
* at a time; this node is packaged into a node set; this
* node set is handed over to the evaluation mechanism.
*/
if (contextObj == NULL)
contextObj = xmlXPathCacheNewNodeSet(xpctxt, contextNode);
else
xmlXPathNodeSetAddUnique(contextObj->nodesetval,
contextNode);
valuePush(ctxt, contextObj);
res = xmlXPathCompOpEvalToBoolean(ctxt, exprOp, 1);
if ((ctxt->error != XPATH_EXPRESSION_OK) || (res == -1)) {
xmlXPathObjectPtr tmp;
/* pop the result if any */
tmp = valuePop(ctxt);
if (tmp != contextObj)
/*
* Free up the result
* then pop off contextObj, which will be freed later
*/
xmlXPathReleaseObject(xpctxt, tmp);
valuePop(ctxt);
goto evaluation_error;
}
if (res)
pos++;
if (res && (pos >= minPos) && (pos <= maxPos)) {
/*
* Fits in the requested range.
*/
newContextSize++;
if (minPos == maxPos) {
/*
* Only 1 node was requested.
*/
if (contextNode->type == XML_NAMESPACE_DECL) {
/*
* As always: take care of those nasty
* namespace nodes.
*/
set->nodeTab[i] = NULL;
}
xmlXPathNodeSetClear(set, hasNsNodes);
set->nodeNr = 1;
set->nodeTab[0] = contextNode;
goto evaluation_exit;
}
if (pos == maxPos) {
/*
* We are done.
*/
xmlXPathNodeSetClearFromPos(set, i +1, hasNsNodes);
goto evaluation_exit;
}
} else {
/*
* Remove the entry from the initial node set.
*/
set->nodeTab[i] = NULL;
if (contextNode->type == XML_NAMESPACE_DECL)
xmlXPathNodeSetFreeNs((xmlNsPtr) contextNode);
}
if (exprRes != NULL) {
xmlXPathReleaseObject(ctxt->context, exprRes);
exprRes = NULL;
}
if (ctxt->value == contextObj) {
/*
* Don't free the temporary XPath object holding the
* context node, in order to avoid massive recreation
* inside this loop.
*/
valuePop(ctxt);
xmlXPathNodeSetClear(contextObj->nodesetval, hasNsNodes);
} else {
/*
* The object was lost in the evaluation machinery.
* Can this happen? Maybe in case of internal-errors.
*/
contextObj = NULL;
}
}
goto evaluation_exit;
evaluation_error:
xmlXPathNodeSetClear(set, hasNsNodes);
newContextSize = 0;
evaluation_exit:
if (contextObj != NULL) {
if (ctxt->value == contextObj)
valuePop(ctxt);
xmlXPathReleaseObject(xpctxt, contextObj);
}
if (exprRes != NULL)
xmlXPathReleaseObject(ctxt->context, exprRes);
/*
* Reset/invalidate the context.
*/
xpctxt->node = oldContextNode;
xpctxt->doc = oldContextDoc;
xpctxt->contextSize = -1;
xpctxt->proximityPosition = -1;
return(newContextSize);
}
return(contextSize);
}
Commit Message: Fix libxml XPath bug.
BUG=89402
Review URL: http://codereview.chromium.org/7508039
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95382 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) {
EXPECT_TRUE(fb != NULL);
ExternalFrameBuffer *const ext_fb =
reinterpret_cast<ExternalFrameBuffer*>(fb->priv);
EXPECT_TRUE(ext_fb != NULL);
EXPECT_EQ(1, ext_fb->in_use);
ext_fb->in_use = 0;
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
Target: 1
Example 2:
Code: void SetFrameBuffer(int idx, vpx_codec_frame_buffer_t *fb) {
ASSERT_TRUE(fb != NULL);
fb->data = ext_fb_list_[idx].data;
fb->size = ext_fb_list_[idx].size;
ASSERT_EQ(0, ext_fb_list_[idx].in_use);
ext_fb_list_[idx].in_use = 1;
fb->priv = &ext_fb_list_[idx];
}
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
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void ImageLoader::timerFired(Timer<ImageLoader>*)
{
m_element->deref();
}
Commit Message: Error event was fired synchronously blowing away the input element from underneath. Remove the FIXME and fire it asynchronously using errorEventSender().
BUG=240124
Review URL: https://chromiumcodereview.appspot.com/14741011
git-svn-id: svn://svn.chromium.org/blink/trunk@150232 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
list_move_tail(&slave->open_list, &master->slave_list_head);
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock_irq(&slave_active_lock);
}
}
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: test_one_file(struct display *dp, const char *filename)
{
/* First cache the file and update the display original file
* information for the new file.
*/
dp->operation = "cache file";
dp->transforms = 0;
display_cache_file(dp, filename);
update_display(dp);
/* First test: if there are options that should be ignored for this file
* verify that they really are ignored.
*/
if (dp->ignored_transforms != 0)
{
read_png(dp, &dp->original_file, "ignored transforms",
dp->ignored_transforms);
/* The result should be identical to the original_rows */
if (!compare_read(dp, 0/*transforms applied*/))
return; /* no point testing more */
}
#ifdef PNG_WRITE_SUPPORTED
/* Second test: write the original PNG data out to a new file (to test the
* write side) then read the result back in and make sure that it hasn't
* changed.
*/
dp->operation = "write";
write_png(dp, dp->original_ip, 0/*transforms*/);
read_png(dp, &dp->written_file, NULL, 0/*transforms*/);
if (!compare_read(dp, 0/*transforms applied*/))
return;
#endif
/* Third test: the active options. Test each in turn, or, with the
* EXHAUSTIVE option, test all possible combinations.
*/
{
/* Use unsigned int here because the code below to increment through all
* the possibilities exhaustively has to use a compare and that must be
* unsigned, because some transforms are negative on a 16-bit system.
*/
unsigned int active = dp->active_transforms;
const int exhaustive = (dp->options & EXHAUSTIVE) != 0;
unsigned int current = first_transform(active);
unsigned int bad_transforms = 0;
unsigned int bad_combo = ~0U; /* bitwise AND of failing transforms */
unsigned int bad_combo_list = 0; /* bitwise OR of failures */
for (;;)
{
read_png(dp, &dp->original_file, "active transforms", current);
/* If this involved any irreversible transformations then if we write
* it out with just the reversible transformations and read it in again
* with the same transforms we should get the same thing. At present
* this isn't done - it just seems like a waste of time and it would
* require two sets of read png_struct/png_info.
*
* If there were no irreversible transformations then if we write it
* out and read it back in again (without the reversible transforms)
* we should get back to the place where we started.
*/
#ifdef PNG_WRITE_SUPPORTED
if ((current & write_transforms) == current)
{
/* All transforms reversible: write the PNG with the transformations
* reversed, then read it back in with no transformations. The
* result should be the same as the original apart from the loss of
* low order bits because of the SHIFT/sBIT transform.
*/
dp->operation = "reversible transforms";
write_png(dp, dp->read_ip, current);
/* And if this is read back in, because all the transformations were
* reversible, the result should be the same.
*/
read_png(dp, &dp->written_file, NULL, 0);
if (!compare_read(dp, current/*for the SHIFT/sBIT transform*/))
{
/* This set of transforms failed. If a single bit is set - if
* there is just one transform - don't include this in further
* 'exhaustive' tests. Notice that each transform is tested on
* its own before testing combos in the exhaustive case.
*/
if (is_combo(current))
{
bad_combo &= current;
bad_combo_list |= current;
}
else
bad_transforms |= current;
}
}
#endif
/* Now move to the next transform */
if (exhaustive) /* all combinations */
{
unsigned int next = current;
do
{
if (next == read_transforms) /* Everything tested */
goto combo;
++next;
} /* skip known bad combos if the relevant option is set; skip
* combos involving known bad single transforms in all cases.
*/
while ( (next & read_transforms) <= current
|| (next & active) == 0 /* skip cases that do nothing */
|| (next & bad_transforms) != 0
|| skip_transform(dp, next));
assert((next & read_transforms) == next);
current = next;
}
else /* one at a time */
{
active &= ~current;
if (active == 0)
goto combo;
current = first_transform(active);
}
}
combo:
if (dp->options & FIND_BAD_COMBOS)
{
/* bad_combos identifies the combos that occur in all failing cases;
* bad_combo_list identifies transforms that do not prevent the
* failure.
*/
if (bad_combo != ~0U)
printf("%s[0x%x]: PROBLEM: 0x%x[0x%x] ANTIDOTE: 0x%x\n",
dp->filename, active, bad_combo, bad_combo_list,
rw_transforms & ~bad_combo_list);
else
printf("%s: no %sbad combos found\n", dp->filename,
(dp->options & SKIP_BUGS) ? "additional " : "");
}
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: gss_inquire_context(
OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
gss_name_t *src_name,
gss_name_t *targ_name,
OM_uint32 *lifetime_rec,
gss_OID *mech_type,
OM_uint32 *ctx_flags,
int *locally_initiated,
int *opened)
{
gss_union_ctx_id_t ctx;
gss_mechanism mech;
OM_uint32 status, temp_minor;
gss_OID actual_mech;
gss_name_t localTargName = NULL, localSourceName = NULL;
status = val_inq_ctx_args(minor_status,
context_handle,
src_name, targ_name,
lifetime_rec,
mech_type, ctx_flags,
locally_initiated, opened);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t) context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech || !mech->gss_inquire_context || !mech->gss_display_name ||
!mech->gss_release_name) {
return (GSS_S_UNAVAILABLE);
}
status = mech->gss_inquire_context(
minor_status,
ctx->internal_ctx_id,
(src_name ? &localSourceName : NULL),
(targ_name ? &localTargName : NULL),
lifetime_rec,
&actual_mech,
ctx_flags,
locally_initiated,
opened);
if (status != GSS_S_COMPLETE) {
map_error(minor_status, mech);
return status;
}
/* need to convert names */
if (src_name) {
if (localSourceName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localSourceName, src_name);
if (status != GSS_S_COMPLETE) {
if (localTargName)
mech->gss_release_name(&temp_minor, &localTargName);
return (status);
}
} else {
*src_name = GSS_C_NO_NAME;
}
}
if (targ_name) {
if (localTargName) {
status = gssint_convert_name_to_union_name(minor_status, mech,
localTargName, targ_name);
if (status != GSS_S_COMPLETE) {
if (src_name)
(void) gss_release_name(&temp_minor, src_name);
return (status);
}
}
else {
*targ_name = GSS_C_NO_NAME;
}
}
if (mech_type)
*mech_type = gssint_get_public_oid(actual_mech);
return(GSS_S_COMPLETE);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool CheckMov(const uint8* buffer, int buffer_size) {
RCHECK(buffer_size > 8);
int offset = 0;
while (offset + 8 < buffer_size) {
int atomsize = Read32(buffer + offset);
uint32 atomtype = Read32(buffer + offset + 4);
switch (atomtype) {
case TAG('f','t','y','p'):
case TAG('p','d','i','n'):
case TAG('m','o','o','v'):
case TAG('m','o','o','f'):
case TAG('m','f','r','a'):
case TAG('m','d','a','t'):
case TAG('f','r','e','e'):
case TAG('s','k','i','p'):
case TAG('m','e','t','a'):
case TAG('m','e','c','o'):
case TAG('s','t','y','p'):
case TAG('s','i','d','x'):
case TAG('s','s','i','x'):
case TAG('p','r','f','t'):
case TAG('b','l','o','c'):
break;
default:
return false;
}
if (atomsize == 1) {
if (offset + 16 > buffer_size)
break;
if (Read32(buffer + offset + 8) != 0)
break; // Offset is way past buffer size.
atomsize = Read32(buffer + offset + 12);
}
if (atomsize <= 0)
break; // Indicates the last atom or length too big.
offset += atomsize;
}
return true;
}
Commit Message: Add extra checks to avoid integer overflow.
BUG=425980
TEST=no crash with ASAN
Review URL: https://codereview.chromium.org/659743004
Cr-Commit-Position: refs/heads/master@{#301249}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static void arcmsr_hbaA_message_isr(struct AdapterControlBlock *acb)
{
struct MessageUnit_A __iomem *reg = acb->pmuA;
/*clear interrupt and message state*/
writel(ARCMSR_MU_OUTBOUND_MESSAGE0_INT, ®->outbound_intstatus);
schedule_work(&acb->arcmsr_do_message_isr_bh);
}
Commit Message: scsi: arcmsr: Buffer overflow in arcmsr_iop_message_xfer()
We need to put an upper bound on "user_len" so the memcpy() doesn't
overflow.
Cc: <[email protected]>
Reported-by: Marco Grassi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Tomas Henzl <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PaymentRequest::CanMakePayment() {
if (observer_for_testing_)
observer_for_testing_->OnCanMakePaymentCalled();
if (!delegate_->GetPrefService()->GetBoolean(kCanMakePaymentEnabled) ||
!state_) {
CanMakePaymentCallback(/*can_make_payment=*/false);
} else {
state_->CanMakePayment(
base::BindOnce(&PaymentRequest::CanMakePaymentCallback,
weak_ptr_factory_.GetWeakPtr()));
}
}
Commit Message: [Payment Request][Desktop] Prevent use after free.
Before this patch, a compromised renderer on desktop could make IPC
methods into Payment Request in an unexpected ordering and cause use
after free in the browser.
This patch will disconnect the IPC pipes if:
- Init() is called more than once.
- Any other method is called before Init().
- Show() is called more than once.
- Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or
Complete() are called before Show().
This patch re-orders the IPC methods in payment_request.cc to match the
order in payment_request.h, which eases verifying correctness of their
error handling.
This patch prints more errors to the developer console, if available, to
improve debuggability by web developers, who rarely check where LOG
prints.
After this patch, unexpected ordering of calls into the Payment Request
IPC from the renderer to the browser on desktop will print an error in
the developer console and disconnect the IPC pipes. The binary might
increase slightly in size because more logs are included in the release
version instead of being stripped at compile time.
Bug: 912947
Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a
Reviewed-on: https://chromium-review.googlesource.com/c/1370198
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616822}
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_exception_intercept(svm, AC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
Commit Message: KVM: svm: unconditionally intercept #DB
This is needed to avoid the possibility that the guest triggers
an infinite stream of #DB exceptions (CVE-2015-8104).
VMX is not affected: because it does not save DR6 in the VMCS,
it already intercepts #DB unconditionally.
Reported-by: Jan Beulich <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int is_shadow_present_pte(u64 pte)
{
return pte & PT_PRESENT_MASK && !is_mmio_spte(pte);
}
Commit Message: nEPT: Nested INVEPT
If we let L1 use EPT, we should probably also support the INVEPT instruction.
In our current nested EPT implementation, when L1 changes its EPT table
for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in
the course of this modification already calls INVEPT. But if last level
of shadow page is unsync not all L1's changes to EPT12 are intercepted,
which means roots need to be synced when L1 calls INVEPT. Global INVEPT
should not be different since roots are synced by kvm_mmu_load() each
time EPTP02 changes.
Reviewed-by: Xiao Guangrong <[email protected]>
Signed-off-by: Nadav Har'El <[email protected]>
Signed-off-by: Jun Nakajima <[email protected]>
Signed-off-by: Xinhao Xu <[email protected]>
Signed-off-by: Yang Zhang <[email protected]>
Signed-off-by: Gleb Natapov <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int nfs4_xdr_enc_read(struct rpc_rqst *req, __be32 *p, struct nfs_readargs *args)
{
struct rpc_auth *auth = req->rq_task->tk_msg.rpc_cred->cr_auth;
struct xdr_stream xdr;
struct compound_hdr hdr = {
.nops = 2,
};
int replen, status;
xdr_init_encode(&xdr, &req->rq_snd_buf, p);
encode_compound_hdr(&xdr, &hdr);
status = encode_putfh(&xdr, args->fh);
if (status)
goto out;
status = encode_read(&xdr, args);
if (status)
goto out;
/* set up reply kvec
* toplevel status + taglen=0 + rescount + OP_PUTFH + status
* + OP_READ + status + eof + datalen = 9
*/
replen = (RPC_REPHDRSIZE + auth->au_rslack + NFS4_dec_read_sz) << 2;
xdr_inline_pages(&req->rq_rcv_buf, replen,
args->pages, args->pgbase, args->count);
req->rq_rcv_buf.flags |= XDRBUF_READ;
out:
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID:
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl1", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_mp_opengl1_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
#ifdef ZONE_DEBUG
ri.Z_MallocDebug = CL_RefMallocDebug;
#else
ri.Z_Malloc = CL_RefMalloc;
#endif
ri.Free = Z_Free;
ri.Tag_Free = CL_RefTagFree;
ri.Hunk_Clear = Hunk_ClearToMark;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
if ( !ret ) {
Com_Error( ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Com_Printf( "---- Renderer Initialization Complete ----\n" );
Cvar_Set( "cl_paused", "0" );
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 1
Example 2:
Code: channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
{
u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
if (c->istate == CHAN_INPUT_OPEN &&
limit > 0 &&
buffer_len(&c->input) < limit &&
buffer_check_alloc(&c->input, CHAN_RBUF))
FD_SET(c->rfd, readset);
if (c->ostate == CHAN_OUTPUT_OPEN ||
c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
if (buffer_len(&c->output) > 0) {
FD_SET(c->wfd, writeset);
} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
debug2("channel %d: obuf_empty delayed efd %d/(%d)",
c->self, c->efd, buffer_len(&c->extended));
else
chan_obuf_empty(c);
}
}
/** XXX check close conditions, too */
if (compat20 && c->efd != -1 &&
!(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
if (c->extended_usage == CHAN_EXTENDED_WRITE &&
buffer_len(&c->extended) > 0)
FD_SET(c->efd, writeset);
else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
(c->extended_usage == CHAN_EXTENDED_READ ||
c->extended_usage == CHAN_EXTENDED_IGNORE) &&
buffer_len(&c->extended) < c->remote_window)
FD_SET(c->efd, readset);
}
/* XXX: What about efd? races? */
}
Commit Message:
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: TabContents* Browser::AddTab(TabContentsWrapper* tab_contents,
PageTransition::Type type) {
tab_handler_->GetTabStripModel()->AddTabContents(
tab_contents, -1, type, TabStripModel::ADD_ACTIVE);
return tab_contents->tab_contents();
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void PrintJobWorker::GetSettingsWithUI(
int document_page_count,
bool has_selection,
bool is_scripted) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
#if defined(OS_ANDROID)
if (is_scripted) {
PrintingContextDelegate* printing_context_delegate =
static_cast<PrintingContextDelegate*>(printing_context_delegate_.get());
content::WebContents* web_contents =
printing_context_delegate->GetWebContents();
TabAndroid* tab =
web_contents ? TabAndroid::FromWebContents(web_contents) : nullptr;
if (tab)
tab->SetPendingPrint();
}
#endif
printing_context_->AskUserForSettings(
document_page_count, has_selection, is_scripted,
base::Bind(&PostOnOwnerThread, make_scoped_refptr(owner_),
base::Bind(&PrintJobWorker::GetSettingsDone,
weak_factory_.GetWeakPtr())));
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20
Target: 1
Example 2:
Code: int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){
uint16 proc=0;
void* q;
uint32 q_length=0;
void* dc;
uint32 dc_length=0;
void* ac;
uint32 ac_length=0;
uint16* lp;
uint16* pt;
uint16 h_samp=1;
uint16 v_samp=1;
unsigned char* ojpegdata;
uint16 table_count;
uint32 offset_table;
uint32 offset_ms_l;
uint32 code_count;
uint32 i=0;
uint32 dest=0;
uint16 ri=0;
uint32 rows=0;
if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGProc field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(q_length < (64U * t2p->tiff_samplesperpixel)){
TIFFError(TIFF2PDF_MODULE,
"Bad JPEGQTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGDCTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(proc==JPEGPROC_BASELINE){
if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGACTables field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
} else {
if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGLosslessPredictors field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){
TIFFError(TIFF2PDF_MODULE,
"Missing JPEGPointTransform field in OJPEG image %s",
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
}
if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){
h_samp=1;
v_samp=1;
}
if(t2p->pdf_ojpegdata != NULL){
_TIFFfree(t2p->pdf_ojpegdata);
t2p->pdf_ojpegdata=NULL;
}
t2p->pdf_ojpegdata = _TIFFmalloc(2048);
if(t2p->pdf_ojpegdata == NULL){
TIFFError(TIFF2PDF_MODULE,
"Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s",
2048,
TIFFFileName(input));
t2p->t2p_error = T2P_ERR_ERROR;
return(0);
}
_TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048);
t2p->pdf_ojpegdatalength = 0;
table_count=t2p->tiff_samplesperpixel;
if(proc==JPEGPROC_BASELINE){
if(table_count>2) table_count=2;
}
ojpegdata=(unsigned char*)t2p->pdf_ojpegdata;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff);
if(TIFFIsTiled(input)){
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_length ) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width >> 8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=
(t2p->tiff_width ) & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff);
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
if(i==0){
ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;;
ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=i;
}
for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x43;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]),
&(((unsigned char*)q)[64*dest]), 64);
t2p->pdf_ojpegdatalength+=64;
}
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)dc)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
if(proc==JPEGPROC_BASELINE){
offset_table=0;
for(dest=0;dest<table_count;dest++){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4;
offset_ms_l=t2p->pdf_ojpegdatalength;
t2p->pdf_ojpegdatalength+=2;
ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10;
ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), 16);
code_count=0;
offset_table+=16;
for(i=0;i<16;i++){
code_count+=ojpegdata[t2p->pdf_ojpegdatalength++];
}
ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff;
ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff;
_TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]),
&(((unsigned char*)ac)[offset_table]), code_count);
offset_table+=code_count;
t2p->pdf_ojpegdatalength+=code_count;
}
}
if(TIFFNumberOfStrips(input)>1){
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x04;
h_samp*=8;
v_samp*=8;
ri=(t2p->tiff_width+h_samp-1) / h_samp;
TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows);
ri*=(rows+v_samp-1)/v_samp;
ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff;
}
ojpegdata[t2p->pdf_ojpegdatalength++]=0xff;
ojpegdata[t2p->pdf_ojpegdatalength++]=0xda;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x00;
ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel);
ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff;
for(i=0;i<t2p->tiff_samplesperpixel;i++){
ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff;
if(proc==JPEGPROC_BASELINE){
ojpegdata[t2p->pdf_ojpegdatalength] |=
( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0;
ojpegdata[t2p->pdf_ojpegdatalength++] |=
( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0;
}
}
if(proc==JPEGPROC_BASELINE){
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f;
t2p->pdf_ojpegdatalength++;
} else {
ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff);
t2p->pdf_ojpegdatalength++;
ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f);
}
return(1);
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void BlobURLRequestJob::CountSize() {
error_ = false;
pending_get_file_info_count_ = 0;
total_size_ = 0;
item_length_list_.resize(blob_data_->items().size());
for (size_t i = 0; i < blob_data_->items().size(); ++i) {
const BlobData::Item& item = blob_data_->items().at(i);
if (IsFileType(item.type())) {
++pending_get_file_info_count_;
GetFileStreamReader(i)->GetLength(
base::Bind(&BlobURLRequestJob::DidGetFileItemLength,
weak_factory_.GetWeakPtr(), i));
continue;
}
int64 item_length = static_cast<int64>(item.length());
item_length_list_[i] = item_length;
total_size_ += item_length;
}
if (pending_get_file_info_count_ == 0)
DidCountSize(net::OK);
}
Commit Message: Avoid integer overflows in BlobURLRequestJob.
BUG=169685
Review URL: https://chromiumcodereview.appspot.com/12047012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void btif_config_save(void) {
assert(alarm_timer != NULL);
assert(config != NULL);
alarm_set(alarm_timer, CONFIG_SETTLE_PERIOD_MS, timer_config_save, NULL);
}
Commit Message: Fix crashes with lots of discovered LE devices
When loads of devices are discovered a config file which is too large
can be written out, which causes the BT daemon to crash on startup.
This limits the number of config entries for unpaired devices which
are initialized, and prevents a large number from being saved to the
filesystem.
Bug: 26071376
Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184
CWE ID: CWE-119
Target: 1
Example 2:
Code: GF_Err AVC_HEVC_UpdateESD(GF_MPEGVisualSampleEntryBox *avc, GF_ESD *esd)
{
GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)avc, GF_TRUE);
if (avc->descr) gf_isom_box_del((GF_Box *) avc->descr);
avc->descr = NULL;
btrt->avgBitrate = esd->decoderConfig->avgBitrate;
btrt->maxBitrate = esd->decoderConfig->maxBitrate;
btrt->bufferSizeDB = esd->decoderConfig->bufferSizeDB;
if (gf_list_count(esd->IPIDataSet)
|| gf_list_count(esd->IPMPDescriptorPointers)
|| esd->langDesc
|| gf_list_count(esd->extensionDescriptors)
|| esd->ipiPtr || esd->qos || esd->RegDescriptor) {
avc->descr = (GF_MPEG4ExtensionDescriptorsBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_M4DS);
if (esd->RegDescriptor) {
gf_list_add(avc->descr->descriptors, esd->RegDescriptor);
esd->RegDescriptor = NULL;
}
if (esd->qos) {
gf_list_add(avc->descr->descriptors, esd->qos);
esd->qos = NULL;
}
if (esd->ipiPtr) {
gf_list_add(avc->descr->descriptors, esd->ipiPtr);
esd->ipiPtr= NULL;
}
while (gf_list_count(esd->IPIDataSet)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->IPIDataSet, 0);
gf_list_rem(esd->IPIDataSet, 0);
gf_list_add(avc->descr->descriptors, desc);
}
while (gf_list_count(esd->IPMPDescriptorPointers)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->IPMPDescriptorPointers, 0);
gf_list_rem(esd->IPMPDescriptorPointers, 0);
gf_list_add(avc->descr->descriptors, desc);
}
if (esd->langDesc) {
gf_list_add(avc->descr->descriptors, esd->langDesc);
esd->langDesc = NULL;
}
while (gf_list_count(esd->extensionDescriptors)) {
GF_Descriptor *desc = (GF_Descriptor *)gf_list_get(esd->extensionDescriptors, 0);
gf_list_rem(esd->extensionDescriptors, 0);
gf_list_add(avc->descr->descriptors, desc);
}
}
if (!avc->lhvc_config && (esd->decoderConfig->objectTypeIndication==GPAC_OTI_VIDEO_HEVC)) {
if (!avc->hevc_config) avc->hevc_config = (GF_HEVCConfigurationBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_HVCC);
if (esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {
if (avc->hevc_config->config) gf_odf_hevc_cfg_del(avc->hevc_config->config);
avc->hevc_config->config = gf_odf_hevc_cfg_read(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength, GF_FALSE);
}
}
else if (!avc->svc_config && !avc->mvc_config && (esd->decoderConfig->objectTypeIndication==GPAC_OTI_VIDEO_AVC)) {
if (!avc->avc_config) avc->avc_config = (GF_AVCConfigurationBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_AVCC);
if (esd->decoderConfig->decoderSpecificInfo && esd->decoderConfig->decoderSpecificInfo->data) {
if (avc->avc_config->config) gf_odf_avc_cfg_del(avc->avc_config->config);
avc->avc_config->config = gf_odf_avc_cfg_read(esd->decoderConfig->decoderSpecificInfo->data, esd->decoderConfig->decoderSpecificInfo->dataLength);
}
}
gf_odf_desc_del((GF_Descriptor *)esd);
if (avc->hevc_config) {
HEVC_RewriteESDescriptor(avc);
} else {
AVC_RewriteESDescriptor(avc);
}
return GF_OK;
}
Commit Message: fix some exploitable overflows (#994, #997)
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: error::Error GLES2DecoderPassthroughImpl::DoIsFramebuffer(GLuint framebuffer,
uint32_t* result) {
*result = api()->glIsFramebufferEXTFn(
GetFramebufferServiceID(api(), framebuffer, &framebuffer_id_map_, false));
return error::kNoError;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void pin_remove(struct fs_pin *pin)
{
spin_lock(&pin_lock);
hlist_del(&pin->m_list);
hlist_del(&pin->s_list);
spin_unlock(&pin_lock);
spin_lock_irq(&pin->wait.lock);
pin->done = 1;
wake_up_locked(&pin->wait);
spin_unlock_irq(&pin->wait.lock);
}
Commit Message: fs_pin: Allow for the possibility that m_list or s_list go unused.
This is needed to support lazily umounting locked mounts. Because the
entire unmounted subtree needs to stay together until there are no
users with references to any part of the subtree.
To support this guarantee that the fs_pin m_list and s_list nodes
are initialized by initializing them in init_fs_pin allowing
for the possibility that pin_insert_group does not touch them.
Further use hlist_del_init in pin_remove so that there is
a hlist_unhashed test before the list we attempt to update
the previous list item.
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: qreal OxideQQuickWebView::zoomFactor() const {
Q_D(const OxideQQuickWebView);
if (!d->proxy_) {
return 1.0;
}
return d->proxy_->zoomFactor();
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool PrintRenderFrameHelper::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;
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: atm_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t llchdr;
u_int hdrlen = 0;
if (caplen < 1 || length < 1) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/* Cisco Style NLPID ? */
if (*p == LLC_UI) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "CNLPID "));
isoclns_print(ndo, p + 1, length - 1, caplen - 1);
return hdrlen;
}
/*
* Must have at least a DSAP, an SSAP, and the first byte of the
* control field.
*/
if (caplen < 3 || length < 3) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
/*
* Extract the presumed LLC header into a variable, for quick
* testing.
* Then check for a header that's neither a header for a SNAP
* packet nor an RFC 2684 routed NLPID-formatted PDU nor
* an 802.2-but-no-SNAP IP packet.
*/
llchdr = EXTRACT_24BITS(p);
if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) &&
llchdr != LLC_UI_HDR(LLCSAP_ISONS) &&
llchdr != LLC_UI_HDR(LLCSAP_IP)) {
/*
* XXX - assume 802.6 MAC header from Fore driver.
*
* Unfortunately, the above list doesn't check for
* all known SAPs, doesn't check for headers where
* the source and destination SAP aren't the same,
* and doesn't check for non-UI frames. It also
* runs the risk of an 802.6 MAC header that happens
* to begin with one of those values being
* incorrectly treated as an 802.2 header.
*
* So is that Fore driver still around? And, if so,
* is it still putting 802.6 MAC headers on ATM
* packets? If so, could it be changed to use a
* new DLT_IEEE802_6 value if we added it?
*/
if (caplen < 20 || length < 20) {
ND_PRINT((ndo, "%s", tstr));
return (caplen);
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%08x%08x %08x%08x ",
EXTRACT_32BITS(p),
EXTRACT_32BITS(p+4),
EXTRACT_32BITS(p+8),
EXTRACT_32BITS(p+12)));
p += 20;
length -= 20;
caplen -= 20;
hdrlen += 20;
}
hdrlen += atm_llc_print(ndo, p, length, caplen);
return (hdrlen);
}
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
Target: 1
Example 2:
Code: void testParseInvalid_Bug16() {
UriParserStateA stateA;
UriUriA uriA;
stateA.uri = &uriA;
const char * const input = "A>B";
const int res = uriParseUriA(&stateA, input);
TEST_ASSERT(res == URI_ERROR_SYNTAX);
TEST_ASSERT(stateA.errorPos == input + 1);
TEST_ASSERT(stateA.errorCode == URI_ERROR_SYNTAX); /* failed previously */
uriFreeUriMembersA(&uriA);
}
Commit Message: UriQuery.c: Fix out-of-bounds-write in ComposeQuery and ...Ex
Reported by Google Autofuzz team
CWE ID: CWE-787
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished(
base::WeakPtr<RenderWidgetHostViewAura> render_widget_host_view,
const base::Callback<void(bool)>& callback,
bool result) {
callback.Run(result);
if (!render_widget_host_view.get())
return;
--render_widget_host_view->pending_thumbnail_tasks_;
render_widget_host_view->AdjustSurfaceProtection();
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void fanout_release(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f;
f = po->fanout;
if (!f)
return;
mutex_lock(&fanout_mutex);
po->fanout = NULL;
if (atomic_dec_and_test(&f->sk_ref)) {
list_del(&f->list);
dev_remove_pack(&f->prot_hook);
fanout_release_data(f);
kfree(f);
}
mutex_unlock(&fanout_mutex);
if (po->rollover)
kfree_rcu(po->rollover, rcu);
}
Commit Message: packet: fix races in fanout_add()
Multiple threads can call fanout_add() at the same time.
We need to grab fanout_mutex earlier to avoid races that could
lead to one thread freeing po->rollover that was set by another thread.
Do the same in fanout_release(), for peace of mind, and to help us
finding lockdep issues earlier.
Fixes: dc99f600698d ("packet: Add fanout support.")
Fixes: 0648ab70afe6 ("packet: rollover prepare: per-socket state")
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Willem de Bruijn <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: bool is_main_frame() { return is_main_frame_; }
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void OMX::binderDied(const wp<IBinder> &the_late_who) {
OMXNodeInstance *instance;
{
Mutex::Autolock autoLock(mLock);
ssize_t index = mLiveNodes.indexOfKey(the_late_who);
CHECK(index >= 0);
instance = mLiveNodes.editValueAt(index);
mLiveNodes.removeItemsAt(index);
index = mDispatchers.indexOfKey(instance->nodeID());
CHECK(index >= 0);
mDispatchers.removeItemsAt(index);
invalidateNodeID_l(instance->nodeID());
}
instance->onObserverDied(mMaster);
}
Commit Message: Add VPX output buffer size check
and handle dead observers more gracefully
Bug: 27597103
Change-Id: Id7acb25d5ef69b197da15ec200a9e4f9e7b03518
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void HTMLStyleElement::DidNotifySubtreeInsertionsToDocument() {
if (StyleElement::ProcessStyleSheet(GetDocument(), *this) ==
StyleElement::kProcessingFatalError)
NotifyLoadedSheetAndAllCriticalSubresources(
kErrorOccurredLoadingSubresource);
}
Commit Message: Do not crash while reentrantly appending to style element.
When a node is inserted into a container, it is notified via
::InsertedInto. However, a node may request a second notification via
DidNotifySubtreeInsertionsToDocument, which occurs after all the children
have been notified as well. *StyleElement is currently using this
second notification.
This causes a problem, because *ScriptElement is using the same mechanism,
which in turn means that scripts can execute before the state of
*StyleElements are properly updated.
This patch avoids ::DidNotifySubtreeInsertionsToDocument, and instead
processes the stylesheet in ::InsertedInto. The original reason for using
::DidNotifySubtreeInsertionsToDocument in the first place appears to be
invalid now, as the test case is still passing.
[email protected], [email protected]
Bug: 853709, 847570
Cq-Include-Trybots: luci.chromium.try:linux_layout_tests_slimming_paint_v2;master.tryserver.blink:linux_trusty_blink_rel
Change-Id: Ic0b5fa611044c78c5745cf26870a747f88920a14
Reviewed-on: https://chromium-review.googlesource.com/1104347
Commit-Queue: Anders Ruud <[email protected]>
Reviewed-by: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#568368}
CWE ID: CWE-416
Target: 1
Example 2:
Code: void reportCallWithDefaultArgument(ConsoleAPIType type, const String16& message)
{
std::vector<v8::Local<v8::Value>> arguments;
for (int i = 0; i < m_info.Length(); ++i)
arguments.push_back(m_info[i]);
if (!m_info.Length())
arguments.push_back(toV8String(m_isolate, message));
reportCall(type, arguments);
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: struct sock *vsock_find_connected_socket(struct sockaddr_vm *src,
struct sockaddr_vm *dst)
{
struct sock *sk;
spin_lock_bh(&vsock_table_lock);
sk = __vsock_find_connected_socket(src, dst);
if (sk)
sock_hold(sk);
spin_unlock_bh(&vsock_table_lock);
return sk;
}
Commit Message: VSOCK: Fix missing msg_namelen update in vsock_stream_recvmsg()
The code misses to update the msg_namelen member to 0 and therefore
makes net/socket.c leak the local, uninitialized sockaddr_storage
variable to userland -- 128 bytes of kernel stack memory.
Cc: Andy King <[email protected]>
Cc: Dmitry Torokhov <[email protected]>
Cc: George Zhang <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void ext2_put_super (struct super_block * sb)
{
int db_count;
int i;
struct ext2_sb_info *sbi = EXT2_SB(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
ext2_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
struct ext2_super_block *es = sbi->s_es;
spin_lock(&sbi->s_lock);
es->s_state = cpu_to_le16(sbi->s_mount_state);
spin_unlock(&sbi->s_lock);
ext2_sync_super(sb, es, 1);
}
db_count = sbi->s_gdb_count;
for (i = 0; i < db_count; i++)
if (sbi->s_group_desc[i])
brelse (sbi->s_group_desc[i]);
kfree(sbi->s_group_desc);
kfree(sbi->s_debts);
percpu_counter_destroy(&sbi->s_freeblocks_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
brelse (sbi->s_sbh);
sb->s_fs_info = NULL;
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
Target: 1
Example 2:
Code: METHODDEF(JDIMENSION)
get_scaled_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[UCH(*bufferptr++)];
}
return 1;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static const char *register_output_filter(cmd_parms *cmd, void *_cfg,
const char* filter, const char *file, const char *function)
{
const char *err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES|
NOT_IN_HTACCESS);
if (err) {
return err;
}
if (!function) function = "handle";
return register_filter_function_hook(filter, cmd, _cfg, file,
function, AP_LUA_FILTER_OUTPUT);
}
Commit Message: Merge r1642499 from trunk:
*) SECURITY: CVE-2014-8109 (cve.mitre.org)
mod_lua: Fix handling of the Require line when a LuaAuthzProvider is
used in multiple Require directives with different arguments.
PR57204 [Edward Lu <Chaosed0 gmail.com>]
Submitted By: Edward Lu
Committed By: covener
Submitted by: covener
Reviewed/backported by: jim
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/branches/2.4.x@1642861 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-264
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int sfgets(void)
{
struct pollfd pfd;
int pollret;
ssize_t readnb;
signed char seen_r = 0;
static size_t scanned;
static size_t readnbd;
if (scanned > (size_t) 0U) { /* support pipelining */
readnbd -= scanned;
memmove(cmd, cmd + scanned, readnbd); /* safe */
scanned = (size_t) 0U;
}
pfd.fd = clientfd;
#ifdef __APPLE_CC__
pfd.events = POLLIN | POLLERR | POLLHUP;
#else
pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
#endif
while (scanned < cmdsize) {
if (scanned >= readnbd) { /* nothing left in the buffer */
pfd.revents = 0;
while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 &&
errno == EINTR);
if (pollret == 0) {
return -1;
}
if (pollret <= 0 ||
(pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
return -2;
}
if ((pfd.revents & (POLLIN | POLLPRI)) == 0) {
continue;
}
if (readnbd >= cmdsize) {
break;
}
#ifdef WITH_TLS
if (tls_cnx != NULL) {
while ((readnb = SSL_read
(tls_cnx, cmd + readnbd, cmdsize - readnbd))
< (ssize_t) 0 && errno == EINTR);
} else
#endif
{
while ((readnb = read(clientfd, cmd + readnbd,
cmdsize - readnbd)) < (ssize_t) 0 &&
errno == EINTR);
}
if (readnb <= (ssize_t) 0) {
return -2;
}
readnbd += readnb;
if (readnbd > cmdsize) {
return -2;
}
}
#ifdef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
if (cmd[scanned] == '\n') {
#ifndef RFC_CONFORMANT_LINES
if (seen_r != 0) {
#endif
cmd[scanned - 1U] = 0;
#ifndef RFC_CONFORMANT_LINES
} else {
cmd[scanned] = 0;
}
#endif
if (++scanned >= readnbd) { /* non-pipelined command */
scanned = readnbd = (size_t) 0U;
}
return 0;
}
seen_r = 0;
#ifdef RFC_CONFORMANT_LINES
}
#endif
if (ISCTRLCODE(cmd[scanned])) {
if (cmd[scanned] == '\r') {
seen_r = 1;
}
#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */
else if (cmd[scanned] == 0) {
cmd[scanned] = '\n';
}
#else
/* replace control chars with _ */
cmd[scanned] = '_';
#endif
}
scanned++;
}
die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */
return 0; /* to please GCC */
}
Commit Message: Flush the command buffer after switching to TLS.
Fixes a flaw similar to CVE-2011-0411.
CWE ID: CWE-399
Target: 1
Example 2:
Code: static inline u64 get_stat64(tg3_stat64_t *val)
{
return ((u64)val->high << 32) | ((u64)val->low);
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms,
int clrspc)
{
jas_image_t *image;
uint_fast32_t rawsize;
uint_fast32_t inmem;
int cmptno;
jas_image_cmptparm_t *cmptparm;
if (!(image = jas_image_create0())) {
return 0;
}
image->clrspc_ = clrspc;
image->maxcmpts_ = numcmpts;
image->inmem_ = true;
//// image->inmem_ = true;
/* Allocate memory for the per-component information. */
if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_,
sizeof(jas_image_cmpt_t *)))) {
jas_image_destroy(image);
return 0;
}
/* Initialize in case of failure. */
for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) {
image->cmpts_[cmptno] = 0;
}
/* Compute the approximate raw size of the image. */
rawsize = 0;
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
rawsize += cmptparm->width * cmptparm->height *
(cmptparm->prec + 7) / 8;
}
/* Decide whether to buffer the image data in memory, based on the
raw size of the image. */
inmem = (rawsize < JAS_IMAGE_INMEMTHRESH);
/* Create the individual image components. */
for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno,
++cmptparm) {
if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx,
cmptparm->tly, cmptparm->hstep, cmptparm->vstep,
cmptparm->width, cmptparm->height, cmptparm->prec,
cmptparm->sgnd, inmem))) {
jas_image_destroy(image);
return 0;
}
++image->numcmpts_;
}
/* Determine the bounding box for all of the components on the
reference grid (i.e., the image area) */
jas_image_setbbox(image);
return image;
}
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
Output: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.