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: static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = disconnect_mount(p, how);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
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
Target: 1
Example 2:
Code: static void process_bin_update(conn *c) {
char *key;
int nkey;
int vlen;
item *it;
protocol_binary_request_set* req = binary_get_request(c);
assert(c != NULL);
key = binary_get_key(c);
nkey = c->binary_header.request.keylen;
/* fix byteorder in the request */
req->message.body.flags = ntohl(req->message.body.flags);
req->message.body.expiration = ntohl(req->message.body.expiration);
vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen);
if (settings.verbose > 1) {
int ii;
if (c->cmd == PROTOCOL_BINARY_CMD_ADD) {
fprintf(stderr, "<%d ADD ", c->sfd);
} else if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
fprintf(stderr, "<%d SET ", c->sfd);
} else {
fprintf(stderr, "<%d REPLACE ", c->sfd);
}
for (ii = 0; ii < nkey; ++ii) {
fprintf(stderr, "%c", key[ii]);
}
fprintf(stderr, " Value len is %d", vlen);
fprintf(stderr, "\n");
}
if (settings.detail_enabled) {
stats_prefix_record_set(key, nkey);
}
it = item_alloc(key, nkey, req->message.body.flags,
realtime(req->message.body.expiration), vlen+2);
if (it == 0) {
enum store_item_type status;
if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) {
write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen);
status = TOO_LARGE;
} else {
out_of_memory(c, "SERVER_ERROR Out of memory allocating item");
/* This error generating method eats the swallow value. Add here. */
c->sbytes = vlen;
status = NO_MEMORY;
}
/* FIXME: losing c->cmd since it's translated below. refactor? */
LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE,
NULL, status, 0, key, nkey, it->exptime, ITEM_clsid(it));
/* Avoid stale data persisting in cache because we failed alloc.
* Unacceptable for SET. Anywhere else too? */
if (c->cmd == PROTOCOL_BINARY_CMD_SET) {
it = item_get(key, nkey, c, DONT_UPDATE);
if (it) {
item_unlink(it);
item_remove(it);
}
}
/* swallow the data line */
c->write_and_go = conn_swallow;
return;
}
ITEM_set_cas(it, c->binary_header.request.cas);
switch (c->cmd) {
case PROTOCOL_BINARY_CMD_ADD:
c->cmd = NREAD_ADD;
break;
case PROTOCOL_BINARY_CMD_SET:
c->cmd = NREAD_SET;
break;
case PROTOCOL_BINARY_CMD_REPLACE:
c->cmd = NREAD_REPLACE;
break;
default:
assert(0);
}
if (ITEM_get_cas(it) != 0) {
c->cmd = NREAD_CAS;
}
c->item = it;
c->ritem = ITEM_data(it);
c->rlbytes = vlen;
conn_set_state(c, conn_nread);
c->substate = bin_read_set_value;
}
Commit Message: Don't overflow item refcount on get
Counts as a miss if the refcount is too high. ASCII multigets are the only
time refcounts can be held for so long.
doing a dirty read of refcount. is aligned.
trying to avoid adding an extra refcount branch for all calls of item_get due
to performance. might be able to move it in there after logging refactoring
simplifies some of the branches.
CWE ID: CWE-190
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 fprintf_ngiflib_img(FILE * f, struct ngiflib_img * i) {
fprintf(f, " * ngiflib_img @ %p\n", i);
fprintf(f, " next = %p\n", i->next);
fprintf(f, " parent = %p\n", i->parent);
fprintf(f, " palette = %p\n", i->palette);
fprintf(f, " %3d couleurs", i->ncolors);
if(i->interlaced) fprintf(f, " interlaced");
fprintf(f, "\n taille : %dx%d, pos (%d,%d)\n", i->width, i->height, i->posX, i->posY);
fprintf(f, " sort_flag=%x localpalbits=%d\n", i->sort_flag, i->localpalbits);
}
Commit Message: fix "pixel overrun"
fixes #3
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: kg_seal(minor_status, context_handle, conf_req_flag, qop_req,
input_message_buffer, conf_state, output_message_buffer, toktype)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
gss_buffer_t input_message_buffer;
int *conf_state;
gss_buffer_t output_message_buffer;
int toktype;
{
krb5_gss_ctx_id_rec *ctx;
krb5_error_code code;
krb5_context context;
output_message_buffer->length = 0;
output_message_buffer->value = NULL;
/* Only default qop or matching established cryptosystem is allowed.
There are NO EXTENSIONS to this set for AES and friends! The
new spec says "just use 0". The old spec plus extensions would
actually allow for certain non-zero values. Fix this to handle
them later. */
if (qop_req != 0) {
*minor_status = (OM_uint32) G_UNKNOWN_QOP;
return GSS_S_FAILURE;
}
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
context = ctx->k5_context;
switch (ctx->proto)
{
case 0:
code = make_seal_token_v1(context, ctx->enc, ctx->seq,
&ctx->seq_send, ctx->initiate,
input_message_buffer, output_message_buffer,
ctx->signalg, ctx->cksum_size, ctx->sealalg,
conf_req_flag, toktype, ctx->mech_used);
break;
case 1:
code = gss_krb5int_make_seal_token_v3(context, ctx,
input_message_buffer,
output_message_buffer,
conf_req_flag, toktype);
break;
default:
code = G_UNKNOWN_QOP; /* XXX */
break;
}
if (code) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if (conf_state)
*conf_state = conf_req_flag;
*minor_status = 0;
return(GSS_S_COMPLETE);
}
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: void OmniboxViewWin::OnKeyDown(TCHAR key,
UINT repeat_count,
UINT flags) {
delete_at_end_pressed_ = false;
if (OnKeyDownAllModes(key, repeat_count, flags))
return;
if (popup_window_mode_) {
DefWindowProc(GetCurrentMessage()->message, key, MAKELPARAM(repeat_count,
flags));
return;
}
if (OnKeyDownOnlyWritable(key, repeat_count, flags))
return;
HandleKeystroke(GetCurrentMessage()->message, key, repeat_count, flags);
}
Commit Message: Change omnibox behavior when stripping javascript schema to navigate after stripping the schema on drag drop.
BUG=109245
TEST=N/A
Review URL: http://codereview.chromium.org/9116016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116692 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: void sctp_association_free(struct sctp_association *asoc)
{
struct sock *sk = asoc->base.sk;
struct sctp_transport *transport;
struct list_head *pos, *temp;
int i;
/* Only real associations count against the endpoint, so
* don't bother for if this is a temporary association.
*/
if (!list_empty(&asoc->asocs)) {
list_del(&asoc->asocs);
/* Decrement the backlog value for a TCP-style listening
* socket.
*/
if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
sk->sk_ack_backlog--;
}
/* Mark as dead, so other users can know this structure is
* going away.
*/
asoc->base.dead = true;
/* Dispose of any data lying around in the outqueue. */
sctp_outq_free(&asoc->outqueue);
/* Dispose of any pending messages for the upper layer. */
sctp_ulpq_free(&asoc->ulpq);
/* Dispose of any pending chunks on the inqueue. */
sctp_inq_free(&asoc->base.inqueue);
sctp_tsnmap_free(&asoc->peer.tsn_map);
/* Free ssnmap storage. */
sctp_ssnmap_free(asoc->ssnmap);
/* Clean up the bound address list. */
sctp_bind_addr_free(&asoc->base.bind_addr);
/* Do we need to go through all of our timers and
* delete them? To be safe we will try to delete all, but we
* should be able to go through and make a guess based
* on our state.
*/
for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
if (del_timer(&asoc->timers[i]))
sctp_association_put(asoc);
}
/* Free peer's cached cookie. */
kfree(asoc->peer.cookie);
kfree(asoc->peer.peer_random);
kfree(asoc->peer.peer_chunks);
kfree(asoc->peer.peer_hmacs);
/* Release the transport structures. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
transport = list_entry(pos, struct sctp_transport, transports);
list_del_rcu(pos);
sctp_transport_free(transport);
}
asoc->peer.transport_count = 0;
sctp_asconf_queue_teardown(asoc);
/* Free pending address space being deleted */
if (asoc->asconf_addr_del_pending != NULL)
kfree(asoc->asconf_addr_del_pending);
/* AUTH - Free the endpoint shared keys */
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
/* AUTH - Free the association shared key */
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_association_put(asoc);
}
Commit Message: net: sctp: inherit auth_capable on INIT collisions
Jason reported an oops caused by SCTP on his ARM machine with
SCTP authentication enabled:
Internal error: Oops: 17 [#1] ARM
CPU: 0 PID: 104 Comm: sctp-test Not tainted 3.13.0-68744-g3632f30c9b20-dirty #1
task: c6eefa40 ti: c6f52000 task.ti: c6f52000
PC is at sctp_auth_calculate_hmac+0xc4/0x10c
LR is at sg_init_table+0x20/0x38
pc : [<c024bb80>] lr : [<c00f32dc>] psr: 40000013
sp : c6f538e8 ip : 00000000 fp : c6f53924
r10: c6f50d80 r9 : 00000000 r8 : 00010000
r7 : 00000000 r6 : c7be4000 r5 : 00000000 r4 : c6f56254
r3 : c00c8170 r2 : 00000001 r1 : 00000008 r0 : c6f1e660
Flags: nZcv IRQs on FIQs on Mode SVC_32 ISA ARM Segment user
Control: 0005397f Table: 06f28000 DAC: 00000015
Process sctp-test (pid: 104, stack limit = 0xc6f521c0)
Stack: (0xc6f538e8 to 0xc6f54000)
[...]
Backtrace:
[<c024babc>] (sctp_auth_calculate_hmac+0x0/0x10c) from [<c0249af8>] (sctp_packet_transmit+0x33c/0x5c8)
[<c02497bc>] (sctp_packet_transmit+0x0/0x5c8) from [<c023e96c>] (sctp_outq_flush+0x7fc/0x844)
[<c023e170>] (sctp_outq_flush+0x0/0x844) from [<c023ef78>] (sctp_outq_uncork+0x24/0x28)
[<c023ef54>] (sctp_outq_uncork+0x0/0x28) from [<c0234364>] (sctp_side_effects+0x1134/0x1220)
[<c0233230>] (sctp_side_effects+0x0/0x1220) from [<c02330b0>] (sctp_do_sm+0xac/0xd4)
[<c0233004>] (sctp_do_sm+0x0/0xd4) from [<c023675c>] (sctp_assoc_bh_rcv+0x118/0x160)
[<c0236644>] (sctp_assoc_bh_rcv+0x0/0x160) from [<c023d5bc>] (sctp_inq_push+0x6c/0x74)
[<c023d550>] (sctp_inq_push+0x0/0x74) from [<c024a6b0>] (sctp_rcv+0x7d8/0x888)
While we already had various kind of bugs in that area
ec0223ec48a9 ("net: sctp: fix sctp_sf_do_5_1D_ce to verify if
we/peer is AUTH capable") and b14878ccb7fa ("net: sctp: cache
auth_enable per endpoint"), this one is a bit of a different
kind.
Giving a bit more background on why SCTP authentication is
needed can be found in RFC4895:
SCTP uses 32-bit verification tags to protect itself against
blind attackers. These values are not changed during the
lifetime of an SCTP association.
Looking at new SCTP extensions, there is the need to have a
method of proving that an SCTP chunk(s) was really sent by
the original peer that started the association and not by a
malicious attacker.
To cause this bug, we're triggering an INIT collision between
peers; normal SCTP handshake where both sides intent to
authenticate packets contains RANDOM; CHUNKS; HMAC-ALGO
parameters that are being negotiated among peers:
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
RFC4895 says that each endpoint therefore knows its own random
number and the peer's random number *after* the association
has been established. The local and peer's random number along
with the shared key are then part of the secret used for
calculating the HMAC in the AUTH chunk.
Now, in our scenario, we have 2 threads with 1 non-blocking
SEQ_PACKET socket each, setting up common shared SCTP_AUTH_KEY
and SCTP_AUTH_ACTIVE_KEY properly, and each of them calling
sctp_bindx(3), listen(2) and connect(2) against each other,
thus the handshake looks similar to this, e.g.:
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
<--------- INIT[RANDOM; CHUNKS; HMAC-ALGO] -----------
-------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] -------->
...
Since such collisions can also happen with verification tags,
the RFC4895 for AUTH rather vaguely says under section 6.1:
In case of INIT collision, the rules governing the handling
of this Random Number follow the same pattern as those for
the Verification Tag, as explained in Section 5.2.4 of
RFC 2960 [5]. Therefore, each endpoint knows its own Random
Number and the peer's Random Number after the association
has been established.
In RFC2960, section 5.2.4, we're eventually hitting Action B:
B) In this case, both sides may be attempting to start an
association at about the same time but the peer endpoint
started its INIT after responding to the local endpoint's
INIT. Thus it may have picked a new Verification Tag not
being aware of the previous Tag it had sent this endpoint.
The endpoint should stay in or enter the ESTABLISHED
state but it MUST update its peer's Verification Tag from
the State Cookie, stop any init or cookie timers that may
running and send a COOKIE ACK.
In other words, the handling of the Random parameter is the
same as behavior for the Verification Tag as described in
Action B of section 5.2.4.
Looking at the code, we exactly hit the sctp_sf_do_dupcook_b()
case which triggers an SCTP_CMD_UPDATE_ASSOC command to the
side effect interpreter, and in fact it properly copies over
peer_{random, hmacs, chunks} parameters from the newly created
association to update the existing one.
Also, the old asoc_shared_key is being released and based on
the new params, sctp_auth_asoc_init_active_key() updated.
However, the issue observed in this case is that the previous
asoc->peer.auth_capable was 0, and has *not* been updated, so
that instead of creating a new secret, we're doing an early
return from the function sctp_auth_asoc_init_active_key()
leaving asoc->asoc_shared_key as NULL. However, we now have to
authenticate chunks from the updated chunk list (e.g. COOKIE-ACK).
That in fact causes the server side when responding with ...
<------------------ AUTH; COOKIE-ACK -----------------
... to trigger a NULL pointer dereference, since in
sctp_packet_transmit(), it discovers that an AUTH chunk is
being queued for xmit, and thus it calls sctp_auth_calculate_hmac().
Since the asoc->active_key_id is still inherited from the
endpoint, and the same as encoded into the chunk, it uses
asoc->asoc_shared_key, which is still NULL, as an asoc_key
and dereferences it in ...
crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len)
... causing an oops. All this happens because sctp_make_cookie_ack()
called with the *new* association has the peer.auth_capable=1
and therefore marks the chunk with auth=1 after checking
sctp_auth_send_cid(), but it is *actually* sent later on over
the then *updated* association's transport that didn't initialize
its shared key due to peer.auth_capable=0. Since control chunks
in that case are not sent by the temporary association which
are scheduled for deletion, they are issued for xmit via
SCTP_CMD_REPLY in the interpreter with the context of the
*updated* association. peer.auth_capable was 0 in the updated
association (which went from COOKIE_WAIT into ESTABLISHED state),
since all previous processing that performed sctp_process_init()
was being done on temporary associations, that we eventually
throw away each time.
The correct fix is to update to the new peer.auth_capable
value as well in the collision case via sctp_assoc_update(),
so that in case the collision migrated from 0 -> 1,
sctp_auth_asoc_init_active_key() can properly recalculate
the secret. This therefore fixes the observed server panic.
Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing")
Reported-by: Jason Gunthorpe <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Tested-by: Jason Gunthorpe <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[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: ImageTransportClientTexture(
WebKit::WebGraphicsContext3D* host_context,
const gfx::Size& size,
float device_scale_factor,
uint64 surface_id)
: ui::Texture(true, size, device_scale_factor),
host_context_(host_context),
texture_id_(surface_id) {
}
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:
Target: 1
Example 2:
Code: void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer* layer, IntRect& layerBounds, bool& boundsComputed)
{
if (layer->isRootLayer())
return;
if (!boundsComputed) {
layerBounds = enclosingIntRect(overlapMap.geometryMap().absoluteRect(layer->overlapBounds()));
if (layerBounds.isEmpty())
layerBounds.setSize(IntSize(1, 1));
boundsComputed = true;
}
IntRect clipRect = pixelSnappedIntRect(layer->clipper().backgroundClipRect(ClipRectsContext(rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
clipRect.intersect(layerBounds);
overlapMap.add(layer, clipRect);
}
Commit Message: Disable some more query compositingState asserts.
This gets the tests passing again on Mac. See the bug for the stacktrace.
A future patch will need to actually fix the incorrect reading of
compositingState.
BUG=343179
Review URL: https://codereview.chromium.org/162153002
git-svn-id: svn://svn.chromium.org/blink/trunk@167069 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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 walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
pmd_t *pmd;
unsigned long next;
int err = 0;
pmd = pmd_offset(pud, addr);
do {
again:
next = pmd_addr_end(addr, end);
if (pmd_none(*pmd)) {
if (walk->pte_hole)
err = walk->pte_hole(addr, next, walk);
if (err)
break;
continue;
}
/*
* This implies that each ->pmd_entry() handler
* needs to know about pmd_trans_huge() pmds
*/
if (walk->pmd_entry)
err = walk->pmd_entry(pmd, addr, next, walk);
if (err)
break;
/*
* Check this here so we only break down trans_huge
* pages when we _need_ to
*/
if (!walk->pte_entry)
continue;
split_huge_page_pmd(walk->mm, pmd);
if (pmd_none_or_clear_bad(pmd))
goto again;
err = walk_pte_range(pmd, addr, next, walk);
if (err)
break;
} while (pmd++, addr = next, addr != end);
return err;
}
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: | 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 alpha_perf_event_irq_handler(unsigned long la_ptr,
struct pt_regs *regs)
{
struct cpu_hw_events *cpuc;
struct perf_sample_data data;
struct perf_event *event;
struct hw_perf_event *hwc;
int idx, j;
__get_cpu_var(irq_pmi_count)++;
cpuc = &__get_cpu_var(cpu_hw_events);
/* Completely counting through the PMC's period to trigger a new PMC
* overflow interrupt while in this interrupt routine is utterly
* disastrous! The EV6 and EV67 counters are sufficiently large to
* prevent this but to be really sure disable the PMCs.
*/
wrperfmon(PERFMON_CMD_DISABLE, cpuc->idx_mask);
/* la_ptr is the counter that overflowed. */
if (unlikely(la_ptr >= alpha_pmu->num_pmcs)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: silly index %ld\n", la_ptr);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
idx = la_ptr;
perf_sample_data_init(&data, 0);
for (j = 0; j < cpuc->n_events; j++) {
if (cpuc->current_idx[j] == idx)
break;
}
if (unlikely(j == cpuc->n_events)) {
/* This can occur if the event is disabled right on a PMC overflow. */
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
event = cpuc->event[j];
if (unlikely(!event)) {
/* This should never occur! */
irq_err_count++;
pr_warning("PMI: No event at index %d!\n", idx);
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
hwc = &event->hw;
alpha_perf_event_update(event, hwc, idx, alpha_pmu->pmc_max_period[idx]+1);
data.period = event->hw.last_period;
if (alpha_perf_event_set_period(event, hwc, idx)) {
if (perf_event_overflow(event, 1, &data, regs)) {
/* Interrupts coming too quickly; "throttle" the
* counter, i.e., disable it for a little while.
*/
alpha_pmu_stop(event, 0);
}
}
wrperfmon(PERFMON_CMD_ENABLE, cpuc->idx_mask);
return;
}
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: 1
Example 2:
Code: void LoadingPredictor::MaybeAddPreconnect(
const GURL& url,
std::vector<PreconnectRequest> requests,
HintOrigin origin) {
DCHECK(!shutdown_);
preconnect_manager()->Start(url, std::move(requests));
}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
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: bool PpapiPluginProcessHost::OnMessageReceived(const IPC::Message& msg) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(PpapiPluginProcessHost, msg)
IPC_MESSAGE_HANDLER(PpapiHostMsg_ChannelCreated,
OnRendererPluginChannelCreated)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
DCHECK(handled);
return handled;
}
Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins.
BUG=151895
Review URL: https://chromiumcodereview.appspot.com/10956065
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98
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: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
Commit Message:
CWE ID: CWE-682
Target: 1
Example 2:
Code: ResourceDispatcherHostImpl::CreateResourceHandlerForDownload(
net::URLRequest* request,
bool is_content_initiated,
bool must_download,
DownloadId id,
scoped_ptr<DownloadSaveInfo> save_info,
const DownloadResourceHandler::OnStartedCallback& started_cb) {
scoped_ptr<ResourceHandler> handler(
new DownloadResourceHandler(id, request, started_cb, save_info.Pass()));
if (delegate_) {
const ResourceRequestInfo* request_info(
ResourceRequestInfo::ForRequest(request));
ScopedVector<ResourceThrottle> throttles;
delegate_->DownloadStarting(
request, request_info->GetContext(), request_info->GetChildID(),
request_info->GetRouteID(), request_info->GetRequestID(),
is_content_initiated, must_download, &throttles);
if (!throttles.empty()) {
handler.reset(
new ThrottlingResourceHandler(
handler.Pass(), request_info->GetChildID(),
request_info->GetRequestID(), throttles.Pass()));
}
}
return handler.Pass();
}
Commit Message: Revert cross-origin auth prompt blocking.
BUG=174129
Review URL: https://chromiumcodereview.appspot.com/12183030
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181113 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
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 run_delalloc_range(struct inode *inode, struct page *locked_page,
u64 start, u64 end, int *page_started,
unsigned long *nr_written)
{
int ret;
struct btrfs_root *root = BTRFS_I(inode)->root;
if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 1, nr_written);
} else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
ret = run_delalloc_nocow(inode, locked_page, start, end,
page_started, 0, nr_written);
} else if (!btrfs_test_opt(root, COMPRESS) &&
!(BTRFS_I(inode)->force_compress) &&
!(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
ret = cow_file_range(inode, locked_page, start, end,
page_started, nr_written, 1);
} else {
set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
&BTRFS_I(inode)->runtime_flags);
ret = cow_file_range_async(inode, locked_page, start, end,
page_started, nr_written);
}
return ret;
}
Commit Message: Btrfs: fix hash overflow handling
The handling for directory crc hash overflows was fairly obscure,
split_leaf returns EOVERFLOW when we try to extend the item and that is
supposed to bubble up to userland. For a while it did so, but along the
way we added better handling of errors and forced the FS readonly if we
hit IO errors during the directory insertion.
Along the way, we started testing only for EEXIST and the EOVERFLOW case
was dropped. The end result is that we may force the FS readonly if we
catch a directory hash bucket overflow.
This fixes a few problem spots. First I add tests for EOVERFLOW in the
places where we can safely just return the error up the chain.
btrfs_rename is harder though, because it tries to insert the new
directory item only after it has already unlinked anything the rename
was going to overwrite. Rather than adding very complex logic, I added
a helper to test for the hash overflow case early while it is still safe
to bail out.
Snapshot and subvolume creation had a similar problem, so they are using
the new helper now too.
Signed-off-by: Chris Mason <[email protected]>
Reported-by: Pascal Junod <[email protected]>
CWE ID: CWE-310
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 mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
{
s->avctx->profile = get_bits(gb, 4);
s->avctx->level = get_bits(gb, 4);
if (s->avctx->profile == 0 && s->avctx->level == 8) {
s->avctx->level = 0;
}
return 0;
}
Commit Message: avcodec/mpeg4videodec: Check read profile before setting it
Fixes: null pointer dereference
Fixes: ffmpeg_crash_7.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: bool DocumentThreadableLoader::isAllowedRedirect(const KURL& url) const
{
if (m_options.crossOriginRequestPolicy == AllowCrossOriginRequests)
return true;
return m_sameOriginRequest && getSecurityOrigin()->canRequest(url);
}
Commit Message: DocumentThreadableLoader: Add guards for sync notifyFinished() in setResource()
In loadRequest(), setResource() can call clear() synchronously:
DocumentThreadableLoader::clear()
DocumentThreadableLoader::handleError()
Resource::didAddClient()
RawResource::didAddClient()
and thus |m_client| can be null while resource() isn't null after setResource(),
causing crashes (Issue 595964).
This CL checks whether |*this| is destructed and
whether |m_client| is null after setResource().
BUG=595964
Review-Url: https://codereview.chromium.org/1902683002
Cr-Commit-Position: refs/heads/master@{#391001}
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 CreatePrintSettingsDictionary(DictionaryValue* dict) {
dict->SetBoolean(printing::kSettingLandscape, false);
dict->SetBoolean(printing::kSettingCollate, false);
dict->SetInteger(printing::kSettingColor, printing::GRAY);
dict->SetBoolean(printing::kSettingPrintToPDF, true);
dict->SetInteger(printing::kSettingDuplexMode, printing::SIMPLEX);
dict->SetInteger(printing::kSettingCopies, 1);
dict->SetString(printing::kSettingDeviceName, "dummy");
dict->SetString(printing::kPreviewUIAddr, "0xb33fbeef");
dict->SetInteger(printing::kPreviewRequestID, 12345);
dict->SetBoolean(printing::kIsFirstRequest, true);
dict->SetInteger(printing::kSettingMarginsType, printing::DEFAULT_MARGINS);
dict->SetBoolean(printing::kSettingPreviewModifiable, false);
dict->SetBoolean(printing::kSettingHeaderFooterEnabled, false);
dict->SetBoolean(printing::kSettingGenerateDraftData, true);
}
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
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 Image *EnhanceImage(const Image *image,ExceptionInfo *exception)
{
#define EnhanceImageTag "Enhance/Image"
#define EnhancePixel(weight) \
mean=QuantumScale*((double) GetPixelRed(image,r)+pixel.red)/2.0; \
distance=QuantumScale*((double) GetPixelRed(image,r)-pixel.red); \
distance_squared=(4.0+mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelGreen(image,r)+pixel.green)/2.0; \
distance=QuantumScale*((double) GetPixelGreen(image,r)-pixel.green); \
distance_squared+=(7.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlue(image,r)+pixel.blue)/2.0; \
distance=QuantumScale*((double) GetPixelBlue(image,r)-pixel.blue); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelBlack(image,r)+pixel.black)/2.0; \
distance=QuantumScale*((double) GetPixelBlack(image,r)-pixel.black); \
distance_squared+=(5.0-mean)*distance*distance; \
mean=QuantumScale*((double) GetPixelAlpha(image,r)+pixel.alpha)/2.0; \
distance=QuantumScale*((double) GetPixelAlpha(image,r)-pixel.alpha); \
distance_squared+=(5.0-mean)*distance*distance; \
if (distance_squared < 0.069) \
{ \
aggregate.red+=(weight)*GetPixelRed(image,r); \
aggregate.green+=(weight)*GetPixelGreen(image,r); \
aggregate.blue+=(weight)*GetPixelBlue(image,r); \
aggregate.black+=(weight)*GetPixelBlack(image,r); \
aggregate.alpha+=(weight)*GetPixelAlpha(image,r); \
total_weight+=(weight); \
} \
r+=GetPixelChannels(image);
CacheView
*enhance_view,
*image_view;
Image
*enhance_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Initialize enhanced image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
enhance_image=CloneImage(image,0,0,MagickTrue,
exception);
if (enhance_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(enhance_image,DirectClass,exception) == MagickFalse)
{
enhance_image=DestroyImage(enhance_image);
return((Image *) NULL);
}
/*
Enhance image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
enhance_view=AcquireAuthenticCacheView(enhance_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,enhance_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
center;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-2,y-2,image->columns+4,5,exception);
q=QueueCacheViewAuthenticPixels(enhance_view,0,y,enhance_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(2*(image->columns+4)+2);
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
distance,
distance_squared,
mean,
total_weight;
PixelInfo
aggregate;
register const Quantum
*magick_restrict r;
GetPixelInfo(image,&aggregate);
total_weight=0.0;
GetPixelInfoPixel(image,p+center,&pixel);
r=p;
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
r=p+GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+2*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(10.0); EnhancePixel(40.0); EnhancePixel(80.0);
EnhancePixel(40.0); EnhancePixel(10.0);
r=p+3*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(8.0); EnhancePixel(20.0); EnhancePixel(40.0);
EnhancePixel(20.0); EnhancePixel(8.0);
r=p+4*GetPixelChannels(image)*(image->columns+4);
EnhancePixel(5.0); EnhancePixel(8.0); EnhancePixel(10.0);
EnhancePixel(8.0); EnhancePixel(5.0);
if (total_weight > MagickEpsilon)
{
pixel.red=((aggregate.red+total_weight/2.0)/total_weight);
pixel.green=((aggregate.green+total_weight/2.0)/total_weight);
pixel.blue=((aggregate.blue+total_weight/2.0)/total_weight);
pixel.black=((aggregate.black+total_weight/2.0)/total_weight);
pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight);
}
SetPixelViaPixelInfo(image,&pixel,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(enhance_image);
}
if (SyncCacheViewAuthenticPixels(enhance_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,EnhanceImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
enhance_view=DestroyCacheView(enhance_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
enhance_image=DestroyImage(enhance_image);
return(enhance_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1611
CWE ID: CWE-119
Target: 1
Example 2:
Code: void RenderView::OnEnumerateDirectoryResponse(
int id,
const std::vector<FilePath>& paths) {
if (!enumeration_completions_[id])
return;
WebVector<WebString> ws_file_names(paths.size());
for (size_t i = 0; i < paths.size(); ++i)
ws_file_names[i] = webkit_glue::FilePathToWebString(paths[i]);
enumeration_completions_[id]->didChooseFile(ws_file_names);
enumeration_completions_.erase(id);
}
Commit Message: DevTools: move DevToolsAgent/Client into content.
BUG=84078
TEST=
Review URL: http://codereview.chromium.org/7461019
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 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: varbittypmodout(PG_FUNCTION_ARGS)
{
int32 typmod = PG_GETARG_INT32(0);
PG_RETURN_CSTRING(anybit_typmodout(typmod));
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189
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 InputHandler::SetRenderer(RenderProcessHost* process_host,
RenderFrameHostImpl* frame_host) {
if (frame_host == host_)
return;
ClearInputState();
if (host_) {
host_->GetRenderWidgetHost()->RemoveInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(false);
}
host_ = frame_host;
if (host_) {
host_->GetRenderWidgetHost()->AddInputEventObserver(this);
if (ignore_input_events_)
host_->GetRenderWidgetHost()->SetIgnoreInputEvents(true);
}
}
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: int inet6_sk_rebuild_header(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dst_entry *dst;
dst = __sk_dst_check(sk, np->dst_cookie);
if (!dst) {
struct inet_sock *inet = inet_sk(sk);
struct in6_addr *final_p, final;
struct flowi6 fl6;
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;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
rcu_read_lock();
final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt),
&final);
rcu_read_unlock();
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
sk->sk_route_caps = 0;
sk->sk_err_soft = -PTR_ERR(dst);
return PTR_ERR(dst);
}
ip6_dst_store(sk, dst, NULL, NULL);
}
return 0;
}
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: long Segment::ParseCues(long long off, long long& pos, long& len) {
if (m_pCues)
return 0; // success
if (off < 0)
return -1;
long long total, avail;
const int status = m_pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
pos = m_start + off;
if ((total < 0) || (pos >= total))
return 1; // don't bother parsing cues
const long long element_start = pos;
const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long idpos = pos;
const long long id = ReadUInt(m_pReader, idpos, len);
if (id != 0x0C53BB6B) // Cues ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume ID
assert((segment_stop < 0) || (pos <= segment_stop));
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(m_pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // underflow (weird)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
if ((segment_stop >= 0) && ((pos + len) > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(m_pReader, pos, len);
if (size < 0) // error
return static_cast<long>(size);
if (size == 0) // weird, although technically not illegal
return 1; // done
pos += len; // consume length of size of element
assert((segment_stop < 0) || (pos <= segment_stop));
const long long element_stop = pos + size;
if ((segment_stop >= 0) && (element_stop > segment_stop))
return E_FILE_FORMAT_INVALID;
if ((total >= 0) && (element_stop > total))
return 1; // don't bother parsing anymore
len = static_cast<long>(size);
if (element_stop > avail)
return E_BUFFER_NOT_FULL;
const long long element_size = element_stop - element_start;
m_pCues =
new (std::nothrow) Cues(this, pos, size, element_start, element_size);
assert(m_pCues); // TODO
return 0; // success
}
Commit Message: 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: int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u16 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
return -ENOMEM;
}
memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->scmd = NULL;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
megasas_free_cmds(instance);
}
return 0;
}
Commit Message: scsi: megaraid_sas: return error when create DMA pool failed
when create DMA pool for cmd frames failed, we should return -ENOMEM,
instead of 0.
In some case in:
megasas_init_adapter_fusion()
-->megasas_alloc_cmds()
-->megasas_create_frame_pool
create DMA pool failed,
--> megasas_free_cmds() [1]
-->megasas_alloc_cmds_fusion()
failed, then goto fail_alloc_cmds.
-->megasas_free_cmds() [2]
we will call megasas_free_cmds twice, [1] will kfree cmd_list,
[2] will use cmd_list.it will cause a problem:
Unable to handle kernel NULL pointer dereference at virtual address
00000000
pgd = ffffffc000f70000
[00000000] *pgd=0000001fbf893003, *pud=0000001fbf893003,
*pmd=0000001fbf894003, *pte=006000006d000707
Internal error: Oops: 96000005 [#1] SMP
Modules linked in:
CPU: 18 PID: 1 Comm: swapper/0 Not tainted
task: ffffffdfb9290000 ti: ffffffdfb923c000 task.ti: ffffffdfb923c000
PC is at megasas_free_cmds+0x30/0x70
LR is at megasas_free_cmds+0x24/0x70
...
Call trace:
[<ffffffc0005b779c>] megasas_free_cmds+0x30/0x70
[<ffffffc0005bca74>] megasas_init_adapter_fusion+0x2f4/0x4d8
[<ffffffc0005b926c>] megasas_init_fw+0x2dc/0x760
[<ffffffc0005b9ab0>] megasas_probe_one+0x3c0/0xcd8
[<ffffffc0004a5abc>] local_pci_probe+0x4c/0xb4
[<ffffffc0004a5c40>] pci_device_probe+0x11c/0x14c
[<ffffffc00053a5e4>] driver_probe_device+0x1ec/0x430
[<ffffffc00053a92c>] __driver_attach+0xa8/0xb0
[<ffffffc000538178>] bus_for_each_dev+0x74/0xc8
[<ffffffc000539e88>] driver_attach+0x28/0x34
[<ffffffc000539a18>] bus_add_driver+0x16c/0x248
[<ffffffc00053b234>] driver_register+0x6c/0x138
[<ffffffc0004a5350>] __pci_register_driver+0x5c/0x6c
[<ffffffc000ce3868>] megasas_init+0xc0/0x1a8
[<ffffffc000082a58>] do_one_initcall+0xe8/0x1ec
[<ffffffc000ca7be8>] kernel_init_freeable+0x1c8/0x284
[<ffffffc0008d90b8>] kernel_init+0x1c/0xe4
Signed-off-by: Jason Yan <[email protected]>
Acked-by: Sumit Saxena <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: static int ssh_channelcmp(void *av, void *bv)
{
struct ssh_channel *a = (struct ssh_channel *) av;
struct ssh_channel *b = (struct ssh_channel *) bv;
if (a->localid < b->localid)
return -1;
if (a->localid > b->localid)
return +1;
return 0;
}
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 userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
struct userfaultfd_ctx *release_new_ctx;
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
release_new_ctx = NULL;
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (READ_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
/*
* &ewq->wq may be queued in fork_event, but
* __remove_wait_queue ignores the head
* parameter. It would be a problem if it
* didn't.
*/
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
release_new_ctx = new;
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, EPOLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
if (release_new_ctx) {
struct vm_area_struct *vma;
struct mm_struct *mm = release_new_ctx->mm;
/* the various vma->vm_userfaultfd_ctx still points to it */
down_write(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next)
if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
}
up_write(&mm->mmap_sem);
userfaultfd_ctx_put(release_new_ctx);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
WRITE_ONCE(ctx->mmap_changing, false);
userfaultfd_ctx_put(ctx);
}
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
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 V8LazyEventListener::prepareListenerObject(ExecutionContext* executionContext)
{
if (!executionContext)
return;
v8::HandleScope handleScope(toIsolate(executionContext));
v8::Local<v8::Context> v8Context = toV8Context(executionContext, world());
if (v8Context.IsEmpty())
return;
ScriptState* scriptState = ScriptState::from(v8Context);
if (!scriptState->contextIsValid())
return;
if (executionContext->isDocument() && !toDocument(executionContext)->allowInlineEventHandlers(m_node, this, m_sourceURL, m_position.m_line)) {
clearListenerObject();
return;
}
if (hasExistingListenerObject())
return;
ASSERT(executionContext->isDocument());
ScriptState::Scope scope(scriptState);
String listenerSource = InspectorInstrumentation::preprocessEventListener(toDocument(executionContext)->frame(), m_code, m_sourceURL, m_functionName);
String code = "(function() {"
"with (this[2]) {"
"with (this[1]) {"
"with (this[0]) {"
"return function(" + m_eventParameterName + ") {" +
listenerSource + "\n" // Insert '\n' otherwise //-style comments could break the handler.
"};"
"}}}})";
v8::Handle<v8::String> codeExternalString = v8String(isolate(), code);
v8::Local<v8::Value> result = V8ScriptRunner::compileAndRunInternalScript(codeExternalString, isolate(), m_sourceURL, m_position);
if (result.IsEmpty())
return;
ASSERT(result->IsFunction());
v8::Local<v8::Function> intermediateFunction = result.As<v8::Function>();
HTMLFormElement* formElement = 0;
if (m_node && m_node->isHTMLElement())
formElement = toHTMLElement(m_node)->formOwner();
v8::Handle<v8::Object> nodeWrapper = toObjectWrapper<Node>(m_node, scriptState);
v8::Handle<v8::Object> formWrapper = toObjectWrapper<HTMLFormElement>(formElement, scriptState);
v8::Handle<v8::Object> documentWrapper = toObjectWrapper<Document>(m_node ? m_node->ownerDocument() : 0, scriptState);
v8::Local<v8::Object> thisObject = v8::Object::New(isolate());
if (thisObject.IsEmpty())
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 0), nodeWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 1), formWrapper))
return;
if (!thisObject->ForceSet(v8::Integer::New(isolate(), 2), documentWrapper))
return;
v8::Local<v8::Value> innerValue = V8ScriptRunner::callInternalFunction(intermediateFunction, thisObject, 0, 0, isolate());
if (innerValue.IsEmpty() || !innerValue->IsFunction())
return;
v8::Local<v8::Function> wrappedFunction = innerValue.As<v8::Function>();
v8::Local<v8::Function> toStringFunction = v8::Function::New(isolate(), V8LazyEventListenerToString);
ASSERT(!toStringFunction.IsEmpty());
String toStringString = "function " + m_functionName + "(" + m_eventParameterName + ") {\n " + m_code + "\n}";
V8HiddenValue::setHiddenValue(isolate(), wrappedFunction, V8HiddenValue::toStringString(isolate()), v8String(isolate(), toStringString));
wrappedFunction->Set(v8AtomicString(isolate(), "toString"), toStringFunction);
wrappedFunction->SetName(v8String(isolate(), m_functionName));
setListenerObject(wrappedFunction);
}
Commit Message: Turn a bunch of ASSERTs into graceful failures when compiling listeners
BUG=456192
[email protected]
Review URL: https://codereview.chromium.org/906193002
git-svn-id: svn://svn.chromium.org/blink/trunk@189796 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-17
Target: 1
Example 2:
Code: static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi,
void __user *arg,
struct packet_command *cgc)
{
const struct cdrom_device_ops *cdo = cdi->ops;
struct cdrom_msf msf;
cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n");
if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf)))
return -EFAULT;
cgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF;
cgc->cmd[3] = msf.cdmsf_min0;
cgc->cmd[4] = msf.cdmsf_sec0;
cgc->cmd[5] = msf.cdmsf_frame0;
cgc->cmd[6] = msf.cdmsf_min1;
cgc->cmd[7] = msf.cdmsf_sec1;
cgc->cmd[8] = msf.cdmsf_frame1;
cgc->data_direction = CGC_DATA_NONE;
return cdo->generic_packet(cdi, cgc);
}
Commit Message: cdrom: fix improper type cast, which can leat to information leak.
There is another cast from unsigned long to int which causes
a bounds check to fail with specially crafted input. The value is
then used as an index in the slot array in cdrom_slot_status().
This issue is similar to CVE-2018-16658 and CVE-2018-10940.
Signed-off-by: Young_X <[email protected]>
Signed-off-by: Jens Axboe <[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: static int vmxnet3_post_load(void *opaque, int version_id)
{
VMXNET3State *s = opaque;
PCIDevice *d = PCI_DEVICE(s);
vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr);
vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr);
if (s->msix_used) {
if (!vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS)) {
VMW_WRPRN("Failed to re-use MSI-X vectors");
msix_uninit(d, &s->msix_bar, &s->msix_bar);
s->msix_used = false;
return -1;
}
}
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: void Automation::InitWithBrowserPath(const FilePath& browser_exe,
const CommandLine& options,
Error** error) {
if (!file_util::PathExists(browser_exe)) {
std::string message = base::StringPrintf(
"Could not find Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
*error = new Error(kUnknownError, message);
return;
}
CommandLine command(browser_exe);
command.AppendSwitch(switches::kDisableHangMonitor);
command.AppendSwitch(switches::kDisablePromptOnRepost);
command.AppendSwitch(switches::kDomAutomationController);
command.AppendSwitch(switches::kFullMemoryCrashReport);
command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL);
command.AppendSwitch(switches::kNoDefaultBrowserCheck);
command.AppendSwitch(switches::kNoFirstRun);
command.AppendSwitchASCII(switches::kTestType, "webdriver");
command.AppendArguments(options, false);
launcher_.reset(new AnonymousProxyLauncher(false));
ProxyLauncher::LaunchState launch_props = {
false, // clear_profile
FilePath(), // template_user_data
ProxyLauncher::DEFAULT_THEME,
command,
true, // include_testing_id
true // show_window
};
std::string chrome_details = base::StringPrintf(
"Using Chrome binary at: %" PRFilePath,
browser_exe.value().c_str());
VLOG(1) << chrome_details;
if (!launcher_->LaunchBrowserAndServer(launch_props, true)) {
*error = new Error(
kUnknownError,
"Unable to either launch or connect to Chrome. Please check that "
"ChromeDriver is up-to-date. " + chrome_details);
return;
}
launcher_->automation()->set_action_timeout_ms(base::kNoTimeout);
VLOG(1) << "Chrome launched successfully. Version: "
<< automation()->server_version();
bool has_automation_version = false;
*error = CompareVersion(730, 0, &has_automation_version);
if (*error)
return;
chrome_details += ", version (" + automation()->server_version() + ")";
if (has_automation_version) {
int version = 0;
std::string error_msg;
if (!SendGetChromeDriverAutomationVersion(
automation(), &version, &error_msg)) {
*error = new Error(kUnknownError, error_msg + " " + chrome_details);
return;
}
if (version > automation::kChromeDriverAutomationVersion) {
*error = new Error(
kUnknownError,
"ChromeDriver is not compatible with this version of Chrome. " +
chrome_details);
return;
}
}
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: ShellAuraPlatformData::~ShellAuraPlatformData() {
}
Commit Message: shell_aura: Set child to root window size, not host size
The host size is in pixels and the root window size is in scaled pixels.
So, using the pixel size may make the child window much larger than the
root window (and screen). Fix this by matching the root window size.
BUG=335713
TEST=ozone content_shell with --force-device-scale-factor=2
Review URL: https://codereview.chromium.org/141853003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@246389 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: static int dsa_do_verify(const unsigned char *dgst, int dgst_len,
DSA_SIG *sig, DSA *dsa)
{
BN_CTX *ctx;
BIGNUM u1, u2, t1;
BN_MONT_CTX *mont = NULL;
int ret = -1, i;
if (!dsa->p || !dsa->q || !dsa->g) {
DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MISSING_PARAMETERS);
return -1;
}
i = BN_num_bits(dsa->q);
/* fips 186-3 allows only different sizes for q */
if (i != 160 && i != 224 && i != 256) {
DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_BAD_Q_VALUE);
return -1;
}
if (BN_num_bits(dsa->p) > OPENSSL_DSA_MAX_MODULUS_BITS) {
DSAerr(DSA_F_DSA_DO_VERIFY, DSA_R_MODULUS_TOO_LARGE);
return -1;
}
BN_init(&u1);
BN_init(&u2);
BN_init(&t1);
if ((ctx = BN_CTX_new()) == NULL)
goto err;
if (BN_is_zero(sig->r) || BN_is_negative(sig->r) ||
BN_ucmp(sig->r, dsa->q) >= 0) {
ret = 0;
goto err;
}
if (BN_is_zero(sig->s) || BN_is_negative(sig->s) ||
BN_ucmp(sig->s, dsa->q) >= 0) {
ret = 0;
goto err;
}
/*
* Calculate W = inv(S) mod Q save W in u2
*/
if ((BN_mod_inverse(&u2, sig->s, dsa->q, ctx)) == NULL)
goto err;
/* save M in u1 */
if (dgst_len > (i >> 3))
/*
* if the digest length is greater than the size of q use the
* BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3,
* 4.2
*/
dgst_len = (i >> 3);
if (BN_bin2bn(dgst, dgst_len, &u1) == NULL)
goto err;
/* u1 = M * w mod q */
if (!BN_mod_mul(&u1, &u1, &u2, dsa->q, ctx))
goto err;
/* u2 = r * w mod q */
if (!BN_mod_mul(&u2, sig->r, &u2, dsa->q, ctx))
goto err;
if (dsa->flags & DSA_FLAG_CACHE_MONT_P) {
mont = BN_MONT_CTX_set_locked(&dsa->method_mont_p,
CRYPTO_LOCK_DSA, dsa->p, ctx);
if (!mont)
goto err;
}
DSA_MOD_EXP(goto err, dsa, &t1, dsa->g, &u1, dsa->pub_key, &u2, dsa->p,
ctx, mont);
/* BN_copy(&u1,&t1); */
/* let u1 = u1 mod q */
if (!BN_mod(&u1, &t1, dsa->q, ctx))
goto err;
/*
* V is now in u1. If the signature is correct, it will be equal to R.
*/
ret = (BN_ucmp(&u1, sig->r) == 0);
err:
if (ret < 0)
DSAerr(DSA_F_DSA_DO_VERIFY, ERR_R_BN_LIB);
if (ctx != NULL)
BN_CTX_free(ctx);
BN_free(&u1);
BN_free(&u2);
BN_free(&t1);
return (ret);
}
Commit Message:
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: read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
char *errbuf)
{
size_t amt_read;
amt_read = fread(buf, 1, bytes_to_read, fp);
if (amt_read != bytes_to_read) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
} else {
if (amt_read == 0 && !fail_on_eof)
return (0); /* EOF */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"truncated dump file; tried to read %" PRIsize " bytes, only got %" PRIsize,
bytes_to_read, amt_read);
}
return (-1);
}
return (1);
}
Commit Message: do sanity checks on PHB header length before allocating memory. There was no fault; but doing the check results in a more consistent error
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb)
{
struct tcp_sock *tp = tcp_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
u32 now;
inet_csk_schedule_ack(sk);
tcp_measure_rcv_mss(sk, skb);
tcp_rcv_rtt_measure(tp);
now = tcp_time_stamp;
if (!icsk->icsk_ack.ato) {
/* The _first_ data packet received, initialize
* delayed ACK engine.
*/
tcp_incr_quickack(sk);
icsk->icsk_ack.ato = TCP_ATO_MIN;
} else {
int m = now - icsk->icsk_ack.lrcvtime;
if (m <= TCP_ATO_MIN / 2) {
/* The fastest case is the first. */
icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2;
} else if (m < icsk->icsk_ack.ato) {
icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m;
if (icsk->icsk_ack.ato > icsk->icsk_rto)
icsk->icsk_ack.ato = icsk->icsk_rto;
} else if (m > icsk->icsk_rto) {
/* Too long gap. Apparently sender failed to
* restart window, so that we send ACKs quickly.
*/
tcp_incr_quickack(sk);
sk_mem_reclaim(sk);
}
}
icsk->icsk_ack.lrcvtime = now;
TCP_ECN_check_ce(tp, skb);
if (skb->len >= 128)
tcp_grow_window(sk, skb);
}
Commit Message: tcp: drop SYN+FIN messages
Denys Fedoryshchenko reported that SYN+FIN attacks were bringing his
linux machines to their limits.
Dont call conn_request() if the TCP flags includes SYN flag
Reported-by: Denys Fedoryshchenko <[email protected]>
Signed-off-by: Eric Dumazet <[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: bool HTMLFormControlElement::supportsAutofocus() const {
return false;
}
Commit Message: Form validation: Do not show validation bubble if the page is invisible.
BUG=673163
Review-Url: https://codereview.chromium.org/2572813003
Cr-Commit-Position: refs/heads/master@{#438476}
CWE ID: CWE-1021
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: update_display(struct display *dp)
/* called once after the first read to update all the info, original_pp and
* original_ip must have been filled in.
*/
{
png_structp pp;
png_infop ip;
/* Now perform the initial read with a 0 tranform. */
read_png(dp, &dp->original_file, "original read", 0/*no transform*/);
/* Move the result to the 'original' fields */
dp->original_pp = pp = dp->read_pp, dp->read_pp = NULL;
dp->original_ip = ip = dp->read_ip, dp->read_ip = NULL;
dp->original_rowbytes = png_get_rowbytes(pp, ip);
if (dp->original_rowbytes == 0)
display_log(dp, LIBPNG_BUG, "png_get_rowbytes returned 0");
dp->chunks = png_get_valid(pp, ip, 0xffffffff);
if ((dp->chunks & PNG_INFO_IDAT) == 0) /* set by png_read_png */
display_log(dp, LIBPNG_BUG, "png_read_png did not set IDAT flag");
dp->original_rows = png_get_rows(pp, ip);
if (dp->original_rows == NULL)
display_log(dp, LIBPNG_BUG, "png_read_png did not create row buffers");
if (!png_get_IHDR(pp, ip,
&dp->width, &dp->height, &dp->bit_depth, &dp->color_type,
&dp->interlace_method, &dp->compression_method, &dp->filter_method))
display_log(dp, LIBPNG_BUG, "png_get_IHDR failed");
/* 'active' transforms are discovered based on the original image format;
* running one active transform can activate others. At present the code
* does not attempt to determine the closure.
*/
{
png_uint_32 chunks = dp->chunks;
int active = 0, inactive = 0;
int ct = dp->color_type;
int bd = dp->bit_depth;
unsigned int i;
for (i=0; i<TTABLE_SIZE; ++i)
{
int transform = transform_info[i].transform;
if ((transform_info[i].valid_chunks == 0 ||
(transform_info[i].valid_chunks & chunks) != 0) &&
(transform_info[i].color_mask_required & ct) ==
transform_info[i].color_mask_required &&
(transform_info[i].color_mask_absent & ct) == 0 &&
(transform_info[i].bit_depths & bd) != 0 &&
(transform_info[i].when & TRANSFORM_R) != 0)
active |= transform;
else if ((transform_info[i].when & TRANSFORM_R) != 0)
inactive |= transform;
}
/* Some transforms appear multiple times in the table; the 'active' status
* is the logical OR of these and the inactive status must be adjusted to
* take this into account.
*/
inactive &= ~active;
dp->active_transforms = active;
dp->ignored_transforms = inactive; /* excluding write-only transforms */
if (active == 0)
display_log(dp, INTERNAL_ERROR, "bad transform table");
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
struct eb_objects *eb,
struct drm_i915_gem_relocation_entry *reloc)
{
struct drm_device *dev = obj->base.dev;
struct drm_gem_object *target_obj;
uint32_t target_offset;
int ret = -EINVAL;
/* we've already hold a reference to all valid objects */
target_obj = &eb_get_object(eb, reloc->target_handle)->base;
if (unlikely(target_obj == NULL))
return -ENOENT;
target_offset = to_intel_bo(target_obj)->gtt_offset;
/* The target buffer should have appeared before us in the
* exec_object list, so it should have a GTT space bound by now.
*/
if (unlikely(target_offset == 0)) {
DRM_DEBUG("No GTT space found for object %d\n",
reloc->target_handle);
return ret;
}
/* Validate that the target is in a valid r/w GPU domain */
if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
DRM_DEBUG("reloc with multiple write domains: "
"obj %p target %d offset %d "
"read %08x write %08x",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->read_domains,
reloc->write_domain);
return ret;
}
if (unlikely((reloc->write_domain | reloc->read_domains)
& ~I915_GEM_GPU_DOMAINS)) {
DRM_DEBUG("reloc with read/write non-GPU domains: "
"obj %p target %d offset %d "
"read %08x write %08x",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->read_domains,
reloc->write_domain);
return ret;
}
if (unlikely(reloc->write_domain && target_obj->pending_write_domain &&
reloc->write_domain != target_obj->pending_write_domain)) {
DRM_DEBUG("Write domain conflict: "
"obj %p target %d offset %d "
"new %08x old %08x\n",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->write_domain,
target_obj->pending_write_domain);
return ret;
}
target_obj->pending_read_domains |= reloc->read_domains;
target_obj->pending_write_domain |= reloc->write_domain;
/* If the relocation already has the right value in it, no
* more work needs to be done.
*/
if (target_offset == reloc->presumed_offset)
return 0;
/* Check that the relocation address is valid... */
if (unlikely(reloc->offset > obj->base.size - 4)) {
DRM_DEBUG("Relocation beyond object bounds: "
"obj %p target %d offset %d size %d.\n",
obj, reloc->target_handle,
(int) reloc->offset,
(int) obj->base.size);
return ret;
}
if (unlikely(reloc->offset & 3)) {
DRM_DEBUG("Relocation not 4-byte aligned: "
"obj %p target %d offset %d.\n",
obj, reloc->target_handle,
(int) reloc->offset);
return ret;
}
reloc->delta += target_offset;
if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
uint32_t page_offset = reloc->offset & ~PAGE_MASK;
char *vaddr;
vaddr = kmap_atomic(obj->pages[reloc->offset >> PAGE_SHIFT]);
*(uint32_t *)(vaddr + page_offset) = reloc->delta;
kunmap_atomic(vaddr);
} else {
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t __iomem *reloc_entry;
void __iomem *reloc_page;
/* We can't wait for rendering with pagefaults disabled */
if (obj->active && in_atomic())
return -EFAULT;
ret = i915_gem_object_set_to_gtt_domain(obj, 1);
if (ret)
return ret;
/* Map the page containing the relocation we're going to perform. */
reloc->offset += obj->gtt_offset;
reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
reloc->offset & PAGE_MASK);
reloc_entry = (uint32_t __iomem *)
(reloc_page + (reloc->offset & ~PAGE_MASK));
iowrite32(reloc->delta, reloc_entry);
io_mapping_unmap_atomic(reloc_page);
}
/* and update the user's relocation entry */
reloc->presumed_offset = target_offset;
return 0;
}
Commit Message: drm/i915: fix integer overflow in i915_gem_do_execbuffer()
On 32-bit systems, a large args->num_cliprects from userspace via ioctl
may overflow the allocation size, leading to out-of-bounds access.
This vulnerability was introduced in commit 432e58ed ("drm/i915: Avoid
allocation for execbuffer object list").
Signed-off-by: Xi Wang <[email protected]>
Reviewed-by: Chris Wilson <[email protected]>
Cc: [email protected]
Signed-off-by: Daniel Vetter <[email protected]>
CWE ID: CWE-189
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 PrintWebViewHelper::OnPrintForPrintPreview(
const base::DictionaryValue& job_settings) {
if (prep_frame_view_)
return;
if (!render_view()->GetWebView())
return;
blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame();
if (!main_frame)
return;
blink::WebDocument document = main_frame->document();
blink::WebElement pdf_element = document.getElementById("pdf-viewer");
if (pdf_element.isNull()) {
NOTREACHED();
return;
}
blink::WebLocalFrame* plugin_frame = pdf_element.document().frame();
blink::WebElement plugin_element = pdf_element;
if (pdf_element.hasHTMLTagName("iframe")) {
plugin_frame = blink::WebLocalFrame::fromFrameOwnerElement(pdf_element);
plugin_element = delegate_->GetPdfElement(plugin_frame);
if (plugin_element.isNull()) {
NOTREACHED();
return;
}
}
base::AutoReset<bool> set_printing_flag(&print_for_preview_, true);
if (!UpdatePrintSettings(plugin_frame, plugin_element, job_settings)) {
LOG(ERROR) << "UpdatePrintSettings failed";
DidFinishPrinting(FAIL_PRINT);
return;
}
PrintMsg_Print_Params& print_params = print_pages_params_->params;
print_params.printable_area = gfx::Rect(print_params.page_size);
if (!RenderPagesForPrint(plugin_frame, plugin_element)) {
LOG(ERROR) << "RenderPagesForPrint failed";
DidFinishPrinting(FAIL_PRINT);
}
}
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:
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: wiki_handle_http_request(HttpRequest *req)
{
HttpResponse *res = http_response_new(req);
char *page = http_request_get_path_info(req);
char *command = http_request_get_query_string(req);
char *wikitext = "";
util_dehttpize(page); /* remove any encoding on the requested
page name. */
if (!strcmp(page, "/"))
{
if (access("WikiHome", R_OK) != 0)
wiki_redirect(res, "/WikiHome?create");
page = "/WikiHome";
}
if (!strcmp(page, "/styles.css"))
{
/* Return CSS page */
http_response_set_content_type(res, "text/css");
http_response_printf(res, "%s", CssData);
http_response_send(res);
exit(0);
}
if (!strcmp(page, "/favicon.ico"))
{
/* Return favicon */
http_response_set_content_type(res, "image/ico");
http_response_set_data(res, FaviconData, FaviconDataLen);
http_response_send(res);
exit(0);
}
page = page + 1; /* skip slash */
if (!strncmp(page, "api/", 4))
{
char *p;
page += 4;
for (p=page; *p != '\0'; p++)
if (*p=='?') { *p ='\0'; break; }
wiki_handle_rest_call(req, res, page);
exit(0);
}
/* A little safety. issue a malformed request for any paths,
* There shouldn't need to be any..
*/
if (strchr(page, '/'))
{
http_response_set_status(res, 404, "Not Found");
http_response_printf(res, "<html><body>404 Not Found</body></html>\n");
http_response_send(res);
exit(0);
}
if (!strcmp(page, "Changes"))
{
wiki_show_changes_page(res);
}
else if (!strcmp(page, "ChangesRss"))
{
wiki_show_changes_page_rss(res);
}
else if (!strcmp(page, "Search"))
{
wiki_show_search_results_page(res, http_request_param_get(req, "expr"));
}
else if (!strcmp(page, "Create"))
{
if ( (wikitext = http_request_param_get(req, "title")) != NULL)
{
/* create page and redirect */
wiki_redirect(res, http_request_param_get(req, "title"));
}
else
{
/* show create page form */
wiki_show_create_page(res);
}
}
else
{
/* TODO: dont blindly write wikitext data to disk */
if ( (wikitext = http_request_param_get(req, "wikitext")) != NULL)
{
file_write(page, wikitext);
}
if (access(page, R_OK) == 0) /* page exists */
{
wikitext = file_read(page);
if (!strcmp(command, "edit"))
{
/* print edit page */
wiki_show_edit_page(res, wikitext, page);
}
else
{
wiki_show_page(res, wikitext, page);
}
}
else
{
if (!strcmp(command, "create"))
{
wiki_show_edit_page(res, NULL, page);
}
else
{
char buf[1024];
snprintf(buf, 1024, "%s?create", page);
wiki_redirect(res, buf);
}
}
}
}
Commit Message: page_name_is_good function
CWE ID: CWE-22
Target: 1
Example 2:
Code: char *FLTGetIsBetweenComparisonSQLExpresssion(FilterEncodingNode *psFilterNode,
layerObj *lp)
{
const size_t bufferSize = 1024;
char szBuffer[1024];
char **aszBounds = NULL;
int nBounds = 0;
int bString=0;
char szTmp[256];
char* pszEscapedStr;
szBuffer[0] = '\0';
if (!psFilterNode ||
!(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
return NULL;
if (!psFilterNode->psLeftNode || !psFilterNode->psRightNode )
return NULL;
/* -------------------------------------------------------------------- */
/* Get the bounds value which are stored like boundmin;boundmax */
/* -------------------------------------------------------------------- */
aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
if (nBounds != 2) {
msFreeCharArray(aszBounds, nBounds);
return NULL;
}
/* -------------------------------------------------------------------- */
/* check if the value is a numeric value or alphanumeric. If it */
/* is alphanumeric, add quotes around attribute and values. */
/* -------------------------------------------------------------------- */
bString = 0;
if (aszBounds[0]) {
const char* pszOFGType;
snprintf(szTmp, sizeof(szTmp), "%s_type", psFilterNode->psLeftNode->pszValue);
pszOFGType = msOWSLookupMetadata(&(lp->metadata), "OFG", szTmp);
if (pszOFGType!= NULL && strcasecmp(pszOFGType, "Character") == 0)
bString = 1;
else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
bString = 1;
}
if (!bString) {
if (aszBounds[1]) {
if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
bString = 1;
}
}
/* -------------------------------------------------------------------- */
/* build expresssion. */
/* -------------------------------------------------------------------- */
/*opening paranthesis */
strlcat(szBuffer, " (", bufferSize);
/* attribute */
pszEscapedStr = msLayerEscapePropertyName(lp, psFilterNode->psLeftNode->pszValue);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr = NULL;
/*between*/
strlcat(szBuffer, " BETWEEN ", bufferSize);
/*bound 1*/
if (bString)
strlcat(szBuffer,"'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[0]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
strlcat(szBuffer, " AND ", bufferSize);
/*bound 2*/
if (bString)
strlcat(szBuffer, "'", bufferSize);
pszEscapedStr = msLayerEscapeSQLParam( lp, aszBounds[1]);
strlcat(szBuffer, pszEscapedStr, bufferSize);
msFree(pszEscapedStr);
pszEscapedStr=NULL;
if (bString)
strlcat(szBuffer,"'", bufferSize);
/*closing paranthesis*/
strlcat(szBuffer, ")", bufferSize);
msFreeCharArray(aszBounds, nBounds);
return msStrdup(szBuffer);
}
Commit Message: security fix (patch by EvenR)
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 CWebServer::Cmd_UpdateMobileDevice(WebEmSession & session, const request& req, Json::Value &root)
{
if (session.rights != 2)
{
session.reply_status = reply::forbidden;
return; //Only admin user allowed
}
std::string sidx = request::findValue(&req, "idx");
std::string enabled = request::findValue(&req, "enabled");
std::string name = request::findValue(&req, "name");
if (
(sidx.empty()) ||
(enabled.empty()) ||
(name.empty())
)
return;
uint64_t idx = std::strtoull(sidx.c_str(), nullptr, 10);
m_sql.safe_query("UPDATE MobileDevices SET Name='%q', Active=%d WHERE (ID==%" PRIu64 ")",
name.c_str(), (enabled == "true") ? 1 : 0, idx);
root["status"] = "OK";
root["title"] = "UpdateMobile";
}
Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!)
CWE ID: CWE-89
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 sock_send_all(int sock_fd, const uint8_t* buf, int len)
{
int s = len;
int ret;
while(s)
{
do ret = send(sock_fd, buf, s, 0);
while(ret < 0 && errno == EINTR);
if(ret <= 0)
{
BTIF_TRACE_ERROR("sock fd:%d send errno:%d, ret:%d", sock_fd, errno, ret);
return -1;
}
buf += ret;
s -= ret;
}
return len;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
{
const void* p;
uint32_t val;
uint32_t order;
uint32_t mem;
uint32_t restore_method;
/* Remove previous decompression context if it exists. */
if(zip->ppmd8_valid) {
__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
zip->ppmd8_valid = 0;
}
/* Create a new decompression context. */
__archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
zip->ppmd8_stream_failed = 0;
/* Setup function pointers required by Ppmd8 decompressor. The
* 'ppmd_read' function will feed new bytes to the decompressor,
* and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
zip->zipx_ppmd_stream.a = a;
zip->zipx_ppmd_stream.Read = &ppmd_read;
/* Reset number of read bytes to 0. */
zip->zipx_ppmd_read_compressed = 0;
/* Read Ppmd8 header (2 bytes). */
p = __archive_read_ahead(a, 2, NULL);
if(!p) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated file data in PPMd8 stream");
return (ARCHIVE_FATAL);
}
__archive_read_consume(a, 2);
/* Decode the stream's compression parameters. */
val = archive_le16dec(p);
order = (val & 15) + 1;
mem = ((val >> 4) & 0xff) + 1;
restore_method = (val >> 12);
if(order < 2 || restore_method > 2) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid parameter set in PPMd8 stream (order=%d, "
"restore=%d)", order, restore_method);
return (ARCHIVE_FAILED);
}
/* Allocate the memory needed to properly decompress the file. */
if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
archive_set_error(&a->archive, ENOMEM,
"Unable to allocate memory for PPMd8 stream: %d bytes",
mem << 20);
return (ARCHIVE_FATAL);
}
/* Signal the cleanup function to release Ppmd8 context in the
* cleanup phase. */
zip->ppmd8_valid = 1;
/* Perform further Ppmd8 initialization. */
if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"PPMd8 stream range decoder initialization error");
return (ARCHIVE_FATAL);
}
__archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order, restore_method);
/* Allocate the buffer that will hold uncompressed data. */
free(zip->uncompressed_buffer);
zip->uncompressed_buffer_size = 256 * 1024;
zip->uncompressed_buffer =
(uint8_t*) malloc(zip->uncompressed_buffer_size);
if(zip->uncompressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for PPMd8 decompression");
return ARCHIVE_FATAL;
}
/* Ppmd8 initialization is done. */
zip->decompress_init = 1;
/* We've already read 2 bytes in the output stream. Additionally,
* Ppmd8 initialization code could read some data as well. So we
* are advancing the stream by 2 bytes plus whatever number of
* bytes Ppmd8 init function used. */
zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
return ARCHIVE_OK;
}
Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup()
Frees lzma_stream on cleanup()
Fixes #1165
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 Ins_RTDG( INS_ARG )
{ (void)args;
CUR.GS.round_state = TT_Round_To_Double_Grid;
CUR.func_round = (TRound_Function)Round_To_Double_Grid;
}
Commit Message:
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: CURLcode Curl_urldecode(struct SessionHandle *data,
const char *string, size_t length,
char **ostring, size_t *olen,
bool reject_ctrl)
{
size_t alloc = (length?length:strlen(string))+1;
char *ns = malloc(alloc);
unsigned char in;
size_t strindex=0;
unsigned long hex;
CURLcode res;
if(!ns)
return CURLE_OUT_OF_MEMORY;
while(--alloc > 0) {
in = *string;
if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) {
/* this is two hexadecimal digits following a '%' */
char hexstr[3];
char *ptr;
hexstr[0] = string[1];
hexstr[1] = string[2];
hexstr[2] = 0;
hex = strtoul(hexstr, &ptr, 16);
in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */
res = Curl_convert_from_network(data, &in, 1);
if(res) {
/* Curl_convert_from_network calls failf if unsuccessful */
free(ns);
return res;
}
string+=2;
alloc-=2;
}
if(reject_ctrl && (in < 0x20)) {
free(ns);
return CURLE_URL_MALFORMAT;
}
ns[strindex++] = in;
string++;
}
ns[strindex]=0; /* terminate it */
if(olen)
/* store output size */
*olen = strindex;
if(ostring)
/* store output string */
*ostring = ns;
return CURLE_OK;
}
Commit Message: Curl_urldecode: no peeking beyond end of input buffer
Security problem: CVE-2013-2174
If a program would give a string like "%FF" to curl_easy_unescape() but
ask for it to decode only the first byte, it would still parse and
decode the full hex sequence. The function then not only read beyond the
allowed buffer but it would also deduct the *unsigned* counter variable
for how many more bytes there's left to read in the buffer by two,
making the counter wrap. Continuing this, the function would go on
reading beyond the buffer and soon writing beyond the allocated target
buffer...
Bug: http://curl.haxx.se/docs/adv_20130622.html
Reported-by: Timo Sirainen
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int max_track_id = 1, i;
int64_t max_track_len = 0;
int version;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
MOV_TIMESCALE,
mov->tracks[i].timescale,
AV_ROUND_UP);
if (max_track_len < max_track_len_temp)
max_track_len = max_track_len_temp;
if (max_track_id < mov->tracks[i].track_id)
max_track_id = mov->tracks[i].track_id;
}
}
/* If using delay_moov, make sure the output is the same as if no
* samples had been written yet. */
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
max_track_len = 0;
max_track_id = 1;
}
version = max_track_len < UINT32_MAX ? 0 : 1;
avio_wb32(pb, version == 1 ? 120 : 108); /* size */
ffio_wfourcc(pb, "mvhd");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
if (version == 1) {
avio_wb64(pb, mov->time);
avio_wb64(pb, mov->time);
} else {
avio_wb32(pb, mov->time); /* creation time */
avio_wb32(pb, mov->time); /* modification time */
}
avio_wb32(pb, MOV_TIMESCALE);
(version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
avio_wb16(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
/* Matrix structure */
write_matrix(pb, 1, 0, 0, 1, 0, 0);
avio_wb32(pb, 0); /* reserved (preview time) */
avio_wb32(pb, 0); /* reserved (preview duration) */
avio_wb32(pb, 0); /* reserved (poster time) */
avio_wb32(pb, 0); /* reserved (selection time) */
avio_wb32(pb, 0); /* reserved (selection duration) */
avio_wb32(pb, 0); /* reserved (current time) */
avio_wb32(pb, max_track_id + 1); /* Next track id */
return 0x6c;
}
Commit Message: avformat/movenc: Write version 2 of audio atom if channels is not known
The version 1 needs the channel count and would divide by 0
Fixes: division by 0
Fixes: fpe_movenc.c_1108_1.ogg
Fixes: fpe_movenc.c_1108_2.ogg
Fixes: fpe_movenc.c_1108_3.wav
Found-by: #CHEN HONGXU# <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-369
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 __dm_destroy(struct mapped_device *md, bool wait)
{
struct request_queue *q = dm_get_md_queue(md);
struct dm_table *map;
int srcu_idx;
might_sleep();
spin_lock(&_minor_lock);
idr_replace(&_minor_idr, MINOR_ALLOCED, MINOR(disk_devt(dm_disk(md))));
set_bit(DMF_FREEING, &md->flags);
spin_unlock(&_minor_lock);
blk_set_queue_dying(q);
if (dm_request_based(md) && md->kworker_task)
kthread_flush_worker(&md->kworker);
/*
* Take suspend_lock so that presuspend and postsuspend methods
* do not race with internal suspend.
*/
mutex_lock(&md->suspend_lock);
map = dm_get_live_table(md, &srcu_idx);
if (!dm_suspended_md(md)) {
dm_table_presuspend_targets(map);
dm_table_postsuspend_targets(map);
}
/* dm_put_live_table must be before msleep, otherwise deadlock is possible */
dm_put_live_table(md, srcu_idx);
mutex_unlock(&md->suspend_lock);
/*
* Rare, but there may be I/O requests still going to complete,
* for example. Wait for all references to disappear.
* No one should increment the reference count of the mapped_device,
* after the mapped_device state becomes DMF_FREEING.
*/
if (wait)
while (atomic_read(&md->holders))
msleep(1);
else if (atomic_read(&md->holders))
DMWARN("%s: Forcibly removing mapped_device still in use! (%d users)",
dm_device_name(md), atomic_read(&md->holders));
dm_sysfs_exit(md);
dm_table_destroy(__unbind(md));
free_dev(md);
}
Commit Message: dm: fix race between dm_get_from_kobject() and __dm_destroy()
The following BUG_ON was hit when testing repeat creation and removal of
DM devices:
kernel BUG at drivers/md/dm.c:2919!
CPU: 7 PID: 750 Comm: systemd-udevd Not tainted 4.1.44
Call Trace:
[<ffffffff81649e8b>] dm_get_from_kobject+0x34/0x3a
[<ffffffff81650ef1>] dm_attr_show+0x2b/0x5e
[<ffffffff817b46d1>] ? mutex_lock+0x26/0x44
[<ffffffff811df7f5>] sysfs_kf_seq_show+0x83/0xcf
[<ffffffff811de257>] kernfs_seq_show+0x23/0x25
[<ffffffff81199118>] seq_read+0x16f/0x325
[<ffffffff811de994>] kernfs_fop_read+0x3a/0x13f
[<ffffffff8117b625>] __vfs_read+0x26/0x9d
[<ffffffff8130eb59>] ? security_file_permission+0x3c/0x44
[<ffffffff8117bdb8>] ? rw_verify_area+0x83/0xd9
[<ffffffff8117be9d>] vfs_read+0x8f/0xcf
[<ffffffff81193e34>] ? __fdget_pos+0x12/0x41
[<ffffffff8117c686>] SyS_read+0x4b/0x76
[<ffffffff817b606e>] system_call_fastpath+0x12/0x71
The bug can be easily triggered, if an extra delay (e.g. 10ms) is added
between the test of DMF_FREEING & DMF_DELETING and dm_get() in
dm_get_from_kobject().
To fix it, we need to ensure the test of DMF_FREEING & DMF_DELETING and
dm_get() are done in an atomic way, so _minor_lock is used.
The other callers of dm_get() have also been checked to be OK: some
callers invoke dm_get() under _minor_lock, some callers invoke it under
_hash_lock, and dm_start_request() invoke it after increasing
md->open_count.
Cc: [email protected]
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Mike Snitzer <[email protected]>
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: PHP_FUNCTION(mcrypt_module_get_algo_key_size)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir));
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void xmlGROW (xmlParserCtxtPtr ctxt) {
unsigned long curEnd = ctxt->input->end - ctxt->input->cur;
unsigned long curBase = ctxt->input->cur - ctxt->input->base;
if (((curEnd > (unsigned long) XML_MAX_LOOKUP_LIMIT) ||
(curBase > (unsigned long) XML_MAX_LOOKUP_LIMIT)) &&
((ctxt->input->buf) && (ctxt->input->buf->readcallback != (xmlInputReadCallback) xmlNop)) &&
((ctxt->options & XML_PARSE_HUGE) == 0)) {
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "Huge input lookup");
xmlHaltParser(ctxt);
return;
}
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
if ((ctxt->input->cur > ctxt->input->end) ||
(ctxt->input->cur < ctxt->input->base)) {
xmlHaltParser(ctxt);
xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "cur index out of bound");
return;
}
if ((ctxt->input->cur != NULL) && (*ctxt->input->cur == 0))
xmlParserInputGrow(ctxt->input, INPUT_CHUNK);
}
Commit Message: Detect infinite recursion in parameter entities
When expanding a parameter entity in a DTD, infinite recursion could
lead to an infinite loop or memory exhaustion.
Thanks to Wei Lei for the first of many reports.
Fixes bug 759579.
CWE ID: CWE-835
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 bmp_validate(jas_stream_t *in)
{
int n;
int i;
uchar buf[2];
assert(JAS_STREAM_MAXPUTBACK >= 2);
/* Read the first two characters that constitute the signature. */
if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
return -1;
}
/* Put the characters read back onto the stream. */
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
/* Did we read enough characters? */
if (n < 2) {
return -1;
}
/* Is the signature correct for the BMP format? */
if (buf[0] == (BMP_MAGIC & 0xff) && buf[1] == (BMP_MAGIC >> 8)) {
return 0;
}
return -1;
}
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: PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes)
{
int i, count = 0;
int *key_sizes;
MCRYPT_GET_TD_ARG
array_init(return_value);
key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count);
for (i = 0; i < count; i++) {
add_index_long(return_value, i, key_sizes[i]);
}
mcrypt_free(key_sizes);
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: static void bmpr_convert_row_32_16(struct iwbmprcontext *rctx, const iw_byte *src, size_t row)
{
int i,k;
unsigned int v,x;
int numchannels;
numchannels = rctx->has_alpha_channel ? 4 : 3;
for(i=0;i<rctx->width;i++) {
if(rctx->bitcount==32) {
x = ((unsigned int)src[i*4+0]) | ((unsigned int)src[i*4+1])<<8 |
((unsigned int)src[i*4+2])<<16 | ((unsigned int)src[i*4+3])<<24;
}
else { // 16
x = ((unsigned int)src[i*2+0]) | ((unsigned int)src[i*2+1])<<8;
}
v = 0;
for(k=0;k<numchannels;k++) { // For red, green, blue [, alpha]:
v = x & rctx->bf_mask[k];
if(rctx->bf_low_bit[k]>0)
v >>= rctx->bf_low_bit[k];
if(rctx->img->bit_depth==16) {
rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+0] = (iw_byte)(v>>8);
rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+1] = (iw_byte)(v&0xff);
}
else {
rctx->img->pixels[row*rctx->img->bpr + i*numchannels + k] = (iw_byte)v;
}
}
}
}
Commit Message: Fixed a bug that could cause invalid memory to be accessed
The bug could happen when transparency is removed from an image.
Also fixed a semi-related BMP error handling logic bug.
Fixes issue #21
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: xmlBufFree(xmlBufPtr buf) {
if (buf == NULL) {
#ifdef DEBUG_BUFFER
xmlGenericError(xmlGenericErrorContext,
"xmlBufFree: buf == NULL\n");
#endif
return;
}
if ((buf->alloc == XML_BUFFER_ALLOC_IO) &&
(buf->contentIO != NULL)) {
xmlFree(buf->contentIO);
} else if ((buf->content != NULL) &&
(buf->alloc != XML_BUFFER_ALLOC_IMMUTABLE)) {
xmlFree(buf->content);
}
xmlFree(buf);
}
Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9
Removes a few patches fixed upstream:
https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3
https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882
Stops using the NOXXE flag which was reverted upstream:
https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d
Changes the patch to uri.c to not add limits.h, which is included
upstream.
Bug: 722079
Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac
Reviewed-on: https://chromium-review.googlesource.com/535233
Reviewed-by: Scott Graham <[email protected]>
Commit-Queue: Dominic Cooney <[email protected]>
Cr-Commit-Position: refs/heads/master@{#480755}
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: MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
Commit Message: Check context is attached before creating MediaRecorder
Bug: 896736
Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34
Reviewed-on: https://chromium-review.googlesource.com/c/1324231
Commit-Queue: Emircan Uysaler <[email protected]>
Reviewed-by: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606242}
CWE ID: CWE-119
Target: 1
Example 2:
Code: MockNetworkTransaction::MockNetworkTransaction(RequestPriority priority,
MockNetworkLayer* factory)
: request_(nullptr),
data_cursor_(0),
content_length_(0),
priority_(priority),
read_handler_(nullptr),
websocket_handshake_stream_create_helper_(nullptr),
transaction_factory_(factory->AsWeakPtr()),
received_bytes_(0),
sent_bytes_(0),
socket_log_id_(NetLog::Source::kInvalidId),
done_reading_called_(false),
weak_factory_(this) {}
Commit Message: Replace fixed string uses of AddHeaderFromString
Uses of AddHeaderFromString() with a static string may as well be
replaced with SetHeader(). Do so.
BUG=None
Review-Url: https://codereview.chromium.org/2236933005
Cr-Commit-Position: refs/heads/master@{#418161}
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: WebContents* ShowSingletonTab(const GURL& page) {
::ShowSingletonTab(browser(), page);
WebContents* wc = browser()->tab_strip_model()->GetActiveWebContents();
CHECK(wc->GetURL() == page);
WaitForLauncherThread();
WaitForMessageProcessing(wc);
return wc;
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119
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 CoordinatorImpl::GetVmRegionsForHeapProfiler(
const GetVmRegionsForHeapProfilerCallback& callback) {
RequestGlobalMemoryDump(
MemoryDumpType::EXPLICITLY_TRIGGERED,
MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER, {}, 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: PHP_FUNCTION(stream_is_local)
{
zval **zstream;
php_stream *stream = NULL;
php_stream_wrapper *wrapper = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &zstream) == FAILURE) {
RETURN_FALSE;
}
if (Z_TYPE_PP(zstream) == IS_RESOURCE) {
php_stream_from_zval(stream, zstream);
if (stream == NULL) {
RETURN_FALSE;
}
wrapper = stream->wrapper;
} else {
convert_to_string_ex(zstream);
wrapper = php_stream_locate_url_wrapper(Z_STRVAL_PP(zstream), NULL, 0 TSRMLS_CC);
}
if (!wrapper) {
RETURN_FALSE;
}
RETURN_BOOL(wrapper->is_url==0);
}
Commit Message:
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: main(int ac, char **av)
{
int c_flag = 0, d_flag = 0, D_flag = 0, k_flag = 0, s_flag = 0;
int sock, fd, ch, result, saved_errno;
u_int nalloc;
char *shell, *format, *pidstr, *agentsocket = NULL;
fd_set *readsetp = NULL, *writesetp = NULL;
struct rlimit rlim;
extern int optind;
extern char *optarg;
pid_t pid;
char pidstrbuf[1 + 3 * sizeof pid];
struct timeval *tvp = NULL;
size_t len;
mode_t prev_mask;
ssh_malloc_init(); /* must be called before any mallocs */
/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
sanitise_stdfd();
/* drop */
setegid(getgid());
setgid(getgid());
#ifdef WITH_OPENSSL
OpenSSL_add_all_algorithms();
#endif
while ((ch = getopt(ac, av, "cDdksE:a:t:")) != -1) {
switch (ch) {
case 'E':
fingerprint_hash = ssh_digest_alg_by_name(optarg);
if (fingerprint_hash == -1)
fatal("Invalid hash algorithm \"%s\"", optarg);
break;
case 'c':
if (s_flag)
usage();
c_flag++;
break;
case 'k':
k_flag++;
break;
case 's':
if (c_flag)
usage();
s_flag++;
break;
case 'd':
if (d_flag || D_flag)
usage();
d_flag++;
break;
case 'D':
if (d_flag || D_flag)
usage();
D_flag++;
break;
case 'a':
agentsocket = optarg;
break;
case 't':
if ((lifetime = convtime(optarg)) == -1) {
fprintf(stderr, "Invalid lifetime\n");
usage();
}
break;
default:
usage();
}
}
ac -= optind;
av += optind;
if (ac > 0 && (c_flag || k_flag || s_flag || d_flag || D_flag))
usage();
if (ac == 0 && !c_flag && !s_flag) {
shell = getenv("SHELL");
if (shell != NULL && (len = strlen(shell)) > 2 &&
strncmp(shell + len - 3, "csh", 3) == 0)
c_flag = 1;
}
if (k_flag) {
const char *errstr = NULL;
pidstr = getenv(SSH_AGENTPID_ENV_NAME);
if (pidstr == NULL) {
fprintf(stderr, "%s not set, cannot kill agent\n",
SSH_AGENTPID_ENV_NAME);
exit(1);
}
pid = (int)strtonum(pidstr, 2, INT_MAX, &errstr);
if (errstr) {
fprintf(stderr,
"%s=\"%s\", which is not a good PID: %s\n",
SSH_AGENTPID_ENV_NAME, pidstr, errstr);
exit(1);
}
if (kill(pid, SIGTERM) == -1) {
perror("kill");
exit(1);
}
format = c_flag ? "unsetenv %s;\n" : "unset %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME);
printf(format, SSH_AGENTPID_ENV_NAME);
printf("echo Agent pid %ld killed;\n", (long)pid);
exit(0);
}
parent_pid = getpid();
if (agentsocket == NULL) {
/* Create private directory for agent socket */
mktemp_proto(socket_dir, sizeof(socket_dir));
if (mkdtemp(socket_dir) == NULL) {
perror("mkdtemp: private socket dir");
exit(1);
}
snprintf(socket_name, sizeof socket_name, "%s/agent.%ld", socket_dir,
(long)parent_pid);
} else {
/* Try to use specified agent socket */
socket_dir[0] = '\0';
strlcpy(socket_name, agentsocket, sizeof socket_name);
}
/*
* Create socket early so it will exist before command gets run from
* the parent.
*/
prev_mask = umask(0177);
sock = unix_listener(socket_name, SSH_LISTEN_BACKLOG, 0);
if (sock < 0) {
/* XXX - unix_listener() calls error() not perror() */
*socket_name = '\0'; /* Don't unlink any existing file */
cleanup_exit(1);
}
umask(prev_mask);
/*
* Fork, and have the parent execute the command, if any, or present
* the socket data. The child continues as the authentication agent.
*/
if (D_flag || d_flag) {
log_init(__progname,
d_flag ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
SYSLOG_FACILITY_AUTH, 1);
format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
SSH_AUTHSOCKET_ENV_NAME);
printf("echo Agent pid %ld;\n", (long)parent_pid);
fflush(stdout);
goto skip;
}
pid = fork();
if (pid == -1) {
perror("fork");
cleanup_exit(1);
}
if (pid != 0) { /* Parent - execute the given command. */
close(sock);
snprintf(pidstrbuf, sizeof pidstrbuf, "%ld", (long)pid);
if (ac == 0) {
format = c_flag ? "setenv %s %s;\n" : "%s=%s; export %s;\n";
printf(format, SSH_AUTHSOCKET_ENV_NAME, socket_name,
SSH_AUTHSOCKET_ENV_NAME);
printf(format, SSH_AGENTPID_ENV_NAME, pidstrbuf,
SSH_AGENTPID_ENV_NAME);
printf("echo Agent pid %ld;\n", (long)pid);
exit(0);
}
if (setenv(SSH_AUTHSOCKET_ENV_NAME, socket_name, 1) == -1 ||
setenv(SSH_AGENTPID_ENV_NAME, pidstrbuf, 1) == -1) {
perror("setenv");
exit(1);
}
execvp(av[0], av);
perror(av[0]);
exit(1);
}
/* child */
log_init(__progname, SYSLOG_LEVEL_INFO, SYSLOG_FACILITY_AUTH, 0);
if (setsid() == -1) {
error("setsid: %s", strerror(errno));
cleanup_exit(1);
}
(void)chdir("/");
if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
/* XXX might close listen socket */
(void)dup2(fd, STDIN_FILENO);
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO);
if (fd > 2)
close(fd);
}
/* deny core dumps, since memory contains unencrypted private keys */
rlim.rlim_cur = rlim.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &rlim) < 0) {
error("setrlimit RLIMIT_CORE: %s", strerror(errno));
cleanup_exit(1);
}
skip:
cleanup_pid = getpid();
#ifdef ENABLE_PKCS11
pkcs11_init(0);
#endif
new_socket(AUTH_SOCKET, sock);
if (ac > 0)
parent_alive_interval = 10;
idtab_init();
signal(SIGPIPE, SIG_IGN);
signal(SIGINT, (d_flag | D_flag) ? cleanup_handler : SIG_IGN);
signal(SIGHUP, cleanup_handler);
signal(SIGTERM, cleanup_handler);
nalloc = 0;
if (pledge("stdio cpath unix id proc exec", NULL) == -1)
fatal("%s: pledge: %s", __progname, strerror(errno));
while (1) {
prepare_select(&readsetp, &writesetp, &max_fd, &nalloc, &tvp);
result = select(max_fd + 1, readsetp, writesetp, NULL, tvp);
saved_errno = errno;
if (parent_alive_interval != 0)
check_parent_exists();
(void) reaper(); /* remove expired keys */
if (result < 0) {
if (saved_errno == EINTR)
continue;
fatal("select: %s", strerror(saved_errno));
} else if (result > 0)
after_select(readsetp, writesetp);
}
/* NOTREACHED */
}
Commit Message: add a whitelist of paths from which ssh-agent will load (via
ssh-pkcs11-helper) a PKCS#11 module; ok markus@
CWE ID: CWE-426
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_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;
size_t copied;
unsigned char *asmptr;
struct sk_buff *skb;
int n, er, qbit;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL)
return er;
qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;
skb_pull(skb, ROSE_MIN_LEN);
if (rose->qbitincl) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (srose != NULL) {
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->dest_addr;
srose->srose_call = rose->dest_call;
srose->srose_ndigis = rose->dest_ndigis;
if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {
struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;
for (n = 0 ; n < rose->dest_ndigis ; n++)
full_srose->srose_digis[n] = rose->dest_digis[n];
msg->msg_namelen = sizeof(struct full_sockaddr_rose);
} else {
if (rose->dest_ndigis >= 1) {
srose->srose_ndigis = 1;
srose->srose_digi = rose->dest_digis[0];
}
msg->msg_namelen = sizeof(struct sockaddr_rose);
}
}
skb_free_datagram(sk, skb);
return copied;
}
Commit Message: rose: fix info leak via msg_name in rose_recvmsg()
The code in rose_recvmsg() does not initialize all of the members of
struct sockaddr_rose/full_sockaddr_rose when filling the sockaddr info.
Nor does it initialize the padding bytes of the structure inserted by
the compiler for alignment. This will lead to leaking uninitialized
kernel stack bytes in net/socket.c.
Fix the issue by initializing the memory used for sockaddr info with
memset(0).
Cc: Ralf Baechle <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool ChromeContentBrowserClient::IsSuitableHost(
content::RenderProcessHost* process_host,
const GURL& site_url) {
Profile* profile =
Profile::FromBrowserContext(process_host->GetBrowserContext());
if (!profile)
return true;
#if !defined(OS_ANDROID)
InstantService* instant_service =
InstantServiceFactory::GetForProfile(profile);
if (instant_service) {
bool is_instant_process = instant_service->IsInstantProcess(
process_host->GetID());
bool should_be_in_instant_process =
search::ShouldAssignURLToInstantRenderer(site_url, profile);
if (is_instant_process || should_be_in_instant_process)
return is_instant_process && should_be_in_instant_process;
}
#endif
#if BUILDFLAG(ENABLE_EXTENSIONS)
return ChromeContentBrowserClientExtensionsPart::IsSuitableHost(
profile, process_host, site_url);
#else
return true;
#endif
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
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 ServiceWorkerPaymentInstrument::OnCanMakePaymentEventSkipped(
ValidateCanMakePaymentCallback callback) {
can_make_payment_result_ = true;
has_enrolled_instrument_result_ = false;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), this, can_make_payment_result_));
}
Commit Message: [Payment Handler] Don't wait for response from closed payment app.
Before this patch, tapping the back button on top of the payment handler
window on desktop would not affect the |response_helper_|, which would
continue waiting for a response from the payment app. The service worker
of the closed payment app could timeout after 5 minutes and invoke the
|response_helper_|. Depending on what else the user did afterwards, in
the best case scenario, the payment sheet would display a "Transaction
failed" error message. In the worst case scenario, the
|response_helper_| would be used after free.
This patch clears the |response_helper_| in the PaymentRequestState and
in the ServiceWorkerPaymentInstrument after the payment app is closed.
After this patch, the cancelled payment app does not show "Transaction
failed" and does not use memory after it was freed.
Bug: 956597
Change-Id: I64134b911a4f8c154cb56d537a8243a68a806394
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1588682
Reviewed-by: anthonyvd <[email protected]>
Commit-Queue: Rouslan Solomakhin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654995}
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 color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples, i, max, max_w, max_h;
int prec, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof = cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm", "wb");
fwrite(image->icc_profile_buf, 1, image->icc_profile_len, icm);
fclose(icm);
#endif
if (in_prof == NULL) {
return;
}
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = image->comps[0].w;
max_h = image->comps[0].h;
prec = (int)image->comps[0].prec;
if (out_space == cmsSigRgbData) { /* enumCS 16 */
unsigned int i, nr_comp = image->numcomps;
if (nr_comp > 4) {
nr_comp = 4;
}
for (i = 1; i < nr_comp; ++i) { /* AFL test */
if (image->comps[0].dx != image->comps[i].dx) {
break;
}
if (image->comps[0].dy != image->comps[i].dy) {
break;
}
if (image->comps[0].prec != image->comps[i].prec) {
break;
}
if (image->comps[0].sgnd != image->comps[i].sgnd) {
break;
}
}
if (i != nr_comp) {
cmsCloseProfile(in_prof);
return;
}
if (prec <= 8) {
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
} else {
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigGrayData) { /* enumCS 17 */
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
} else {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__, __LINE__, out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if (out_prof == NULL) {
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,
"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n", __FILE__, __LINE__, image->numcomps, prec,
max_w, max_h, (void*)in_prof, (void*)out_prof);
fprintf(stderr, "\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space >> 24) & 0xff, (in_space >> 16) & 0xff,
(in_space >> 8) & 0xff, in_space & 0xff,
out_space,
(out_space >> 24) & 0xff, (out_space >> 16) & 0xff,
(out_space >> 8) & 0xff, out_space & 0xff,
in_type, out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type, out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (transform == NULL) {
#ifdef DEBUG_PROFILE
fprintf(stderr, "%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n", __FILE__, __LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if (image->numcomps > 2) { /* RGB, RGBA */
if (prec <= 8) {
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails0;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
*in++ = (unsigned char) * g++;
*in++ = (unsigned char) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails0:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
} else { /* prec > 8 */
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
if (inbuf == NULL || outbuf == NULL) {
goto fails1;
}
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U ; i < max; ++i) {
*in++ = (unsigned short) * r++;
*in++ = (unsigned short) * g++;
*in++ = (unsigned short) * b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
ok = 1;
fails1:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
}
} else { /* image->numcomps <= 2 : GRAY, GRAYA */
if (prec <= 8) {
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned char*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails2;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails2;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned char) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0U; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails2:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
} else { /* prec > 8 */
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3U * sizeof(unsigned short));
in = inbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
out = outbuf = (unsigned short*)opj_image_data_alloc(nr_samples);
g = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
b = (int*)opj_image_data_alloc((size_t)max * sizeof(int));
if (inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) {
goto fails3;
}
new_comps = (opj_image_comp_t*)realloc(image->comps,
(image->numcomps + 2) * sizeof(opj_image_comp_t));
if (new_comps == NULL) {
goto fails3;
}
image->comps = new_comps;
if (image->numcomps == 2) {
image->comps[3] = image->comps[1];
}
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for (i = 0U; i < max; ++i) {
*in++ = (unsigned short) * r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for (i = 0; i < max; ++i) {
*r++ = (int) * out++;
*g++ = (int) * out++;
*b++ = (int) * out++;
}
r = g = b = NULL;
ok = 1;
fails3:
opj_image_data_free(inbuf);
opj_image_data_free(outbuf);
opj_image_data_free(g);
opj_image_data_free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if (ok) {
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
Commit Message: color_apply_icc_profile: avoid potential heap buffer overflow
Derived from a patch by Thuan Pham
CWE ID: CWE-119
Target: 1
Example 2:
Code: option_clear_or_none(const char *o)
{
return o == NULL || strcasecmp(o, "none") == 0;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
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 union _zend_function *incomplete_class_get_method(zval **object, char *method, int method_len, const zend_literal *key TSRMLS_DC) /* {{{ */
{
incomplete_class_message(*object, E_ERROR TSRMLS_CC);
return NULL;
}
/* }}} */
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 CtcpHandler::parse(Message::Type messageType, const QString &prefix, const QString &target, const QByteArray &message) {
QByteArray ctcp;
QByteArray dequotedMessage = lowLevelDequote(message);
CtcpType ctcptype = messageType == Message::Notice
? CtcpReply
: CtcpQuery;
Message::Flags flags = (messageType == Message::Notice && !network()->isChannelName(target))
? Message::Redirected
: Message::None;
int xdelimPos = -1;
int xdelimEndPos = -1;
int spacePos = -1;
while((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) {
if(xdelimPos > 0)
displayMsg(messageType, target, userDecode(target, dequotedMessage.left(xdelimPos)), prefix, flags);
xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1);
if(xdelimEndPos == -1) {
xdelimEndPos = dequotedMessage.count();
}
ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1));
dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1);
QString ctcpcmd = userDecode(target, ctcp.left(spacePos));
QString ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
spacePos = ctcp.indexOf(' ');
if(spacePos != -1) {
ctcpcmd = userDecode(target, ctcp.left(spacePos));
ctcpparam = userDecode(target, ctcp.mid(spacePos + 1));
} else {
ctcpcmd = userDecode(target, ctcp);
ctcpparam = QString();
ctcpparam = QString();
}
handle(ctcpcmd, Q_ARG(CtcpType, ctcptype), Q_ARG(QString, prefix), Q_ARG(QString, target), Q_ARG(QString, ctcpparam));
}
if(!dequotedMessage.isEmpty())
void CtcpHandler::query(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("PRIVMSG", params);
}
void CtcpHandler::reply(const QString &bufname, const QString &ctcpTag, const QString &message) {
QList<QByteArray> params;
params << serverEncode(bufname) << lowLevelQuote(pack(serverEncode(ctcpTag), userEncode(bufname, message)));
emit putCmd("NOTICE", params);
}
void CtcpHandler::handleAction(CtcpType ctcptype, const QString &prefix, const QString &target, const QString ¶m) {
Q_UNUSED(ctcptype)
emit displayMsg(Message::Action, typeByTarget(target), target, param, prefix);
}
emit putCmd("NOTICE", params);
}
Commit Message:
CWE ID: CWE-399
Target: 1
Example 2:
Code: GLES2DecoderPassthroughImpl::DoInitializeDiscardableTextureCHROMIUM(
GLuint texture_id,
ServiceDiscardableHandle&& discardable_handle) {
scoped_refptr<TexturePassthrough> texture_passthrough = nullptr;
if (!resources_->texture_object_map.GetServiceID(texture_id,
&texture_passthrough) ||
texture_passthrough == nullptr) {
InsertError(GL_INVALID_VALUE, "Invalid texture ID");
return error::kNoError;
}
group_->passthrough_discardable_manager()->InitializeTexture(
texture_id, group_.get(), texture_passthrough->estimated_size(),
std::move(discardable_handle));
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 int pit_ioport_read(struct kvm_io_device *this,
gpa_t addr, int len, void *data)
{
struct kvm_pit *pit = dev_to_pit(this);
struct kvm_kpit_state *pit_state = &pit->pit_state;
struct kvm *kvm = pit->kvm;
int ret, count;
struct kvm_kpit_channel_state *s;
if (!pit_in_range(addr))
return -EOPNOTSUPP;
addr &= KVM_PIT_CHANNEL_MASK;
s = &pit_state->channels[addr];
mutex_lock(&pit_state->lock);
if (s->status_latched) {
s->status_latched = 0;
ret = s->status;
} else if (s->count_latched) {
switch (s->count_latched) {
default:
case RW_STATE_LSB:
ret = s->latched_count & 0xff;
s->count_latched = 0;
break;
case RW_STATE_MSB:
ret = s->latched_count >> 8;
s->count_latched = 0;
break;
case RW_STATE_WORD0:
ret = s->latched_count & 0xff;
s->count_latched = RW_STATE_MSB;
break;
}
} else {
switch (s->read_state) {
default:
case RW_STATE_LSB:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
break;
case RW_STATE_MSB:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
break;
case RW_STATE_WORD0:
count = pit_get_count(kvm, addr);
ret = count & 0xff;
s->read_state = RW_STATE_WORD1;
break;
case RW_STATE_WORD1:
count = pit_get_count(kvm, addr);
ret = (count >> 8) & 0xff;
s->read_state = RW_STATE_WORD0;
break;
}
}
if (len > sizeof(ret))
len = sizeof(ret);
memcpy(data, (char *)&ret, len);
mutex_unlock(&pit_state->lock);
return 0;
}
Commit Message: KVM: PIT: control word is write-only
PIT control word (address 0x43) is write-only, reads are undefined.
Cc: [email protected]
Signed-off-by: Marcelo Tosatti <[email protected]>
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 spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */
{
int ret = SUCCESS;
do {
ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC);
} while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY));
if (ret == SUCCESS) {
size_t buf_len = intern->u.file.current_line_len;
char *buf = estrndup(intern->u.file.current_line, buf_len);
if (intern->u.file.current_zval) {
zval_ptr_dtor(&intern->u.file.current_zval);
}
ALLOC_INIT_ZVAL(intern->u.file.current_zval);
php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC);
if (return_value) {
if (Z_TYPE_P(return_value) != IS_NULL) {
zval_dtor(return_value);
ZVAL_NULL(return_value);
}
ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0);
}
}
return ret;
}
/* }}} */
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int i_ipmi_req_ipmb(struct ipmi_smi *intf,
struct ipmi_addr *addr,
long msgid,
struct kernel_ipmi_msg *msg,
struct ipmi_smi_msg *smi_msg,
struct ipmi_recv_msg *recv_msg,
unsigned char source_address,
unsigned char source_lun,
int retries,
unsigned int retry_time_ms)
{
struct ipmi_ipmb_addr *ipmb_addr;
unsigned char ipmb_seq;
long seqid;
int broadcast = 0;
struct ipmi_channel *chans;
int rv = 0;
if (addr->channel >= IPMI_MAX_CHANNELS) {
ipmi_inc_stat(intf, sent_invalid_commands);
return -EINVAL;
}
chans = READ_ONCE(intf->channel_list)->c;
if (chans[addr->channel].medium != IPMI_CHANNEL_MEDIUM_IPMB) {
ipmi_inc_stat(intf, sent_invalid_commands);
return -EINVAL;
}
if (addr->addr_type == IPMI_IPMB_BROADCAST_ADDR_TYPE) {
/*
* Broadcasts add a zero at the beginning of the
* message, but otherwise is the same as an IPMB
* address.
*/
addr->addr_type = IPMI_IPMB_ADDR_TYPE;
broadcast = 1;
retries = 0; /* Don't retry broadcasts. */
}
/*
* 9 for the header and 1 for the checksum, plus
* possibly one for the broadcast.
*/
if ((msg->data_len + 10 + broadcast) > IPMI_MAX_MSG_LENGTH) {
ipmi_inc_stat(intf, sent_invalid_commands);
return -EMSGSIZE;
}
ipmb_addr = (struct ipmi_ipmb_addr *) addr;
if (ipmb_addr->lun > 3) {
ipmi_inc_stat(intf, sent_invalid_commands);
return -EINVAL;
}
memcpy(&recv_msg->addr, ipmb_addr, sizeof(*ipmb_addr));
if (recv_msg->msg.netfn & 0x1) {
/*
* It's a response, so use the user's sequence
* from msgid.
*/
ipmi_inc_stat(intf, sent_ipmb_responses);
format_ipmb_msg(smi_msg, msg, ipmb_addr, msgid,
msgid, broadcast,
source_address, source_lun);
/*
* Save the receive message so we can use it
* to deliver the response.
*/
smi_msg->user_data = recv_msg;
} else {
/* It's a command, so get a sequence for it. */
unsigned long flags;
spin_lock_irqsave(&intf->seq_lock, flags);
if (is_maintenance_mode_cmd(msg))
intf->ipmb_maintenance_mode_timeout =
maintenance_mode_timeout_ms;
if (intf->ipmb_maintenance_mode_timeout && retry_time_ms == 0)
/* Different default in maintenance mode */
retry_time_ms = default_maintenance_retry_ms;
/*
* Create a sequence number with a 1 second
* timeout and 4 retries.
*/
rv = intf_next_seq(intf,
recv_msg,
retry_time_ms,
retries,
broadcast,
&ipmb_seq,
&seqid);
if (rv)
/*
* We have used up all the sequence numbers,
* probably, so abort.
*/
goto out_err;
ipmi_inc_stat(intf, sent_ipmb_commands);
/*
* Store the sequence number in the message,
* so that when the send message response
* comes back we can start the timer.
*/
format_ipmb_msg(smi_msg, msg, ipmb_addr,
STORE_SEQ_IN_MSGID(ipmb_seq, seqid),
ipmb_seq, broadcast,
source_address, source_lun);
/*
* Copy the message into the recv message data, so we
* can retransmit it later if necessary.
*/
memcpy(recv_msg->msg_data, smi_msg->data,
smi_msg->data_size);
recv_msg->msg.data = recv_msg->msg_data;
recv_msg->msg.data_len = smi_msg->data_size;
/*
* We don't unlock until here, because we need
* to copy the completed message into the
* recv_msg before we release the lock.
* Otherwise, race conditions may bite us. I
* know that's pretty paranoid, but I prefer
* to be correct.
*/
out_err:
spin_unlock_irqrestore(&intf->seq_lock, flags);
}
return rv;
}
Commit Message: ipmi: fix use-after-free of user->release_barrier.rda
When we do the following test, we got oops in ipmi_msghandler driver
while((1))
do
service ipmievd restart & service ipmievd restart
done
---------------------------------------------------------------
[ 294.230186] Unable to handle kernel paging request at virtual address 0000803fea6ea008
[ 294.230188] Mem abort info:
[ 294.230190] ESR = 0x96000004
[ 294.230191] Exception class = DABT (current EL), IL = 32 bits
[ 294.230193] SET = 0, FnV = 0
[ 294.230194] EA = 0, S1PTW = 0
[ 294.230195] Data abort info:
[ 294.230196] ISV = 0, ISS = 0x00000004
[ 294.230197] CM = 0, WnR = 0
[ 294.230199] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000a1c1b75a
[ 294.230201] [0000803fea6ea008] pgd=0000000000000000
[ 294.230204] Internal error: Oops: 96000004 [#1] SMP
[ 294.235211] Modules linked in: nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm iw_cm dm_mirror dm_region_hash dm_log dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ghash_ce sha2_ce ses sha256_arm64 sha1_ce hibmc_drm hisi_sas_v2_hw enclosure sg hisi_sas_main sbsa_gwdt ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe ipmi_si mdio hns_dsaf ipmi_devintf ipmi_msghandler hns_enet_drv hns_mdio
[ 294.277745] CPU: 3 PID: 0 Comm: swapper/3 Kdump: loaded Not tainted 5.0.0-rc2+ #113
[ 294.285511] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017
[ 294.292835] pstate: 80000005 (Nzcv daif -PAN -UAO)
[ 294.297695] pc : __srcu_read_lock+0x38/0x58
[ 294.301940] lr : acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.307853] sp : ffff00001001bc80
[ 294.311208] x29: ffff00001001bc80 x28: ffff0000117e5000
[ 294.316594] x27: 0000000000000000 x26: dead000000000100
[ 294.321980] x25: dead000000000200 x24: ffff803f6bd06800
[ 294.327366] x23: 0000000000000000 x22: 0000000000000000
[ 294.332752] x21: ffff00001001bd04 x20: ffff80df33d19018
[ 294.338137] x19: ffff80df33d19018 x18: 0000000000000000
[ 294.343523] x17: 0000000000000000 x16: 0000000000000000
[ 294.348908] x15: 0000000000000000 x14: 0000000000000002
[ 294.354293] x13: 0000000000000000 x12: 0000000000000000
[ 294.359679] x11: 0000000000000000 x10: 0000000000100000
[ 294.365065] x9 : 0000000000000000 x8 : 0000000000000004
[ 294.370451] x7 : 0000000000000000 x6 : ffff80df34558678
[ 294.375836] x5 : 000000000000000c x4 : 0000000000000000
[ 294.381221] x3 : 0000000000000001 x2 : 0000803fea6ea000
[ 294.386607] x1 : 0000803fea6ea008 x0 : 0000000000000001
[ 294.391994] Process swapper/3 (pid: 0, stack limit = 0x0000000083087293)
[ 294.398791] Call trace:
[ 294.401266] __srcu_read_lock+0x38/0x58
[ 294.405154] acquire_ipmi_user+0x2c/0x70 [ipmi_msghandler]
[ 294.410716] deliver_response+0x80/0xf8 [ipmi_msghandler]
[ 294.416189] deliver_local_response+0x28/0x68 [ipmi_msghandler]
[ 294.422193] handle_one_recv_msg+0x158/0xcf8 [ipmi_msghandler]
[ 294.432050] handle_new_recv_msgs+0xc0/0x210 [ipmi_msghandler]
[ 294.441984] smi_recv_tasklet+0x8c/0x158 [ipmi_msghandler]
[ 294.451618] tasklet_action_common.isra.5+0x88/0x138
[ 294.460661] tasklet_action+0x2c/0x38
[ 294.468191] __do_softirq+0x120/0x2f8
[ 294.475561] irq_exit+0x134/0x140
[ 294.482445] __handle_domain_irq+0x6c/0xc0
[ 294.489954] gic_handle_irq+0xb8/0x178
[ 294.497037] el1_irq+0xb0/0x140
[ 294.503381] arch_cpu_idle+0x34/0x1a8
[ 294.510096] do_idle+0x1d4/0x290
[ 294.516322] cpu_startup_entry+0x28/0x30
[ 294.523230] secondary_start_kernel+0x184/0x1d0
[ 294.530657] Code: d538d082 d2800023 8b010c81 8b020021 (c85f7c25)
[ 294.539746] ---[ end trace 8a7a880dee570b29 ]---
[ 294.547341] Kernel panic - not syncing: Fatal exception in interrupt
[ 294.556837] SMP: stopping secondary CPUs
[ 294.563996] Kernel Offset: disabled
[ 294.570515] CPU features: 0x002,21006008
[ 294.577638] Memory Limit: none
[ 294.587178] Starting crashdump kernel...
[ 294.594314] Bye!
Because the user->release_barrier.rda is freed in ipmi_destroy_user(), but
the refcount is not zero, when acquire_ipmi_user() uses user->release_barrier.rda
in __srcu_read_lock(), it causes oops.
Fix this by calling cleanup_srcu_struct() when the refcount is zero.
Fixes: e86ee2d44b44 ("ipmi: Rework locking and shutdown for hot remove")
Cc: [email protected] # 4.18
Signed-off-by: Yang Yingliang <[email protected]>
Signed-off-by: Corey Minyard <[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: status_t Parcel::readUtf8FromUtf16(std::string* str) const {
size_t utf16Size = 0;
const char16_t* src = readString16Inplace(&utf16Size);
if (!src) {
return UNEXPECTED_NULL;
}
if (utf16Size == 0u) {
str->clear();
return NO_ERROR;
}
ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size);
if (utf8Size < 0) {
return BAD_VALUE;
}
str->resize(utf8Size + 1);
utf16_to_utf8(src, utf16Size, &((*str)[0]));
str->resize(utf8Size);
return NO_ERROR;
}
Commit Message: Add bound checks to utf16_to_utf8
Bug: 29250543
Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a
(cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719)
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 v8::Handle<v8::Value> overloadedMethod2Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.overloadedMethod2");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(TestObj*, objArg, V8TestObj::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8TestObj::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
if (args.Length() <= 1) {
imp->overloadedMethod(objArg);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined)));
imp->overloadedMethod(objArg, intArg);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID:
Target: 1
Example 2:
Code: void set_run_unload_listener(bool value) { run_unload_ = value; }
Commit Message: chromeos: fix bug where "aw snap" page replaces first tab if it was a NTP when closing window with > 1 tab.
BUG=chromium-os:12088
TEST=verify bug per bug report.
Review URL: http://codereview.chromium.org/6882058
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83031 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: static int ssl3_check_finished(SSL *s)
{
int ok = 0;
if (s->version < TLS1_VERSION || !s->tls_session_secret_cb ||
!s->session->tlsext_tick)
return 0;
/* Need to permit this temporarily, in case the next message is Finished. */
s->s3->flags |= SSL3_FLAGS_CCS_OK;
/*
* This function is called when we might get a Certificate message instead,
* so permit appropriate message length.
* We ignore the return value as we're only interested in the message type
* and not its length.
*/
s->method->ssl_get_message(s,
SSL3_ST_CR_CERT_A,
SSL3_ST_CR_CERT_B,
-1, s->max_cert_list, &ok);
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
if (!ok)
return -1;
s->s3->tmp.reuse_message = 1;
if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
return 1;
/* If we're not done, then the CCS arrived early and we should bail. */
if (s->s3->change_cipher_spec) {
SSLerr(SSL_F_SSL3_CHECK_FINISHED, SSL_R_CCS_RECEIVED_EARLY);
ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
return -1;
}
return 0;
}
Commit Message:
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: static int em_jcxz(struct x86_emulate_ctxt *ctxt)
{
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: void SupervisedUserService::SetActive(bool active) {
if (active_ == active)
return;
active_ = active;
if (!delegate_ || !delegate_->SetActive(active_)) {
if (active_) {
#if !defined(OS_ANDROID)
ProfileOAuth2TokenService* token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
token_service->LoadCredentials(
supervised_users::kSupervisedUserPseudoEmail);
#else
NOTREACHED();
#endif
}
}
#if !defined(OS_ANDROID)
ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_);
if (theme_service->UsingDefaultTheme() || theme_service->UsingSystemTheme())
theme_service->UseDefaultTheme();
#endif
browser_sync::ProfileSyncService* sync_service =
ProfileSyncServiceFactory::GetForProfile(profile_);
sync_service->SetEncryptEverythingAllowed(!active_);
GetSettingsService()->SetActive(active_);
#if BUILDFLAG(ENABLE_EXTENSIONS)
SetExtensionsActive();
#endif
if (active_) {
pref_change_registrar_.Add(
prefs::kDefaultSupervisedUserFilteringBehavior,
base::BindRepeating(
&SupervisedUserService::OnDefaultFilteringBehaviorChanged,
base::Unretained(this)));
#if BUILDFLAG(ENABLE_EXTENSIONS)
pref_change_registrar_.Add(
prefs::kSupervisedUserApprovedExtensions,
base::BindRepeating(&SupervisedUserService::UpdateApprovedExtensions,
base::Unretained(this)));
#endif
pref_change_registrar_.Add(
prefs::kSupervisedUserSafeSites,
base::BindRepeating(&SupervisedUserService::OnSafeSitesSettingChanged,
base::Unretained(this)));
pref_change_registrar_.Add(
prefs::kSupervisedUserManualHosts,
base::BindRepeating(&SupervisedUserService::UpdateManualHosts,
base::Unretained(this)));
pref_change_registrar_.Add(
prefs::kSupervisedUserManualURLs,
base::BindRepeating(&SupervisedUserService::UpdateManualURLs,
base::Unretained(this)));
for (const char* pref : kCustodianInfoPrefs) {
pref_change_registrar_.Add(
pref,
base::BindRepeating(&SupervisedUserService::OnCustodianInfoChanged,
base::Unretained(this)));
}
OnDefaultFilteringBehaviorChanged();
OnSafeSitesSettingChanged();
whitelist_service_->Init();
UpdateManualHosts();
UpdateManualURLs();
#if BUILDFLAG(ENABLE_EXTENSIONS)
UpdateApprovedExtensions();
#endif
#if !defined(OS_ANDROID)
BrowserList::AddObserver(this);
#endif
} else {
permissions_creators_.clear();
url_reporter_.reset();
pref_change_registrar_.Remove(
prefs::kDefaultSupervisedUserFilteringBehavior);
#if BUILDFLAG(ENABLE_EXTENSIONS)
pref_change_registrar_.Remove(prefs::kSupervisedUserApprovedExtensions);
#endif
pref_change_registrar_.Remove(prefs::kSupervisedUserManualHosts);
pref_change_registrar_.Remove(prefs::kSupervisedUserManualURLs);
for (const char* pref : kCustodianInfoPrefs) {
pref_change_registrar_.Remove(pref);
}
url_filter_.Clear();
for (SupervisedUserServiceObserver& observer : observer_list_)
observer.OnURLFilterChanged();
#if !defined(OS_ANDROID)
BrowserList::RemoveObserver(this);
#endif
}
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20
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 GLES2DecoderImpl::DoIsRenderbuffer(GLuint client_id) {
const Renderbuffer* renderbuffer =
GetRenderbuffer(client_id);
return renderbuffer && renderbuffer->IsValid() && !renderbuffer->IsDeleted();
}
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
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: nfs3svc_decode_symlinkargs(struct svc_rqst *rqstp, __be32 *p,
struct nfsd3_symlinkargs *args)
{
unsigned int len, avail;
char *old, *new;
struct kvec *vec;
if (!(p = decode_fh(p, &args->ffh)) ||
!(p = decode_filename(p, &args->fname, &args->flen))
)
return 0;
p = decode_sattr3(p, &args->attrs);
/* now decode the pathname, which might be larger than the first page.
* As we have to check for nul's anyway, we copy it into a new page
* This page appears in the rq_res.pages list, but as pages_len is always
* 0, it won't get in the way
*/
len = ntohl(*p++);
if (len == 0 || len > NFS3_MAXPATHLEN || len >= PAGE_SIZE)
return 0;
args->tname = new = page_address(*(rqstp->rq_next_page++));
args->tlen = len;
/* first copy and check from the first page */
old = (char*)p;
vec = &rqstp->rq_arg.head[0];
avail = vec->iov_len - (old - (char*)vec->iov_base);
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
/* now copy next page if there is one */
if (len && !avail && rqstp->rq_arg.page_len) {
avail = min_t(unsigned int, rqstp->rq_arg.page_len, PAGE_SIZE);
old = page_address(rqstp->rq_arg.pages[0]);
}
while (len && avail && *old) {
*new++ = *old++;
len--;
avail--;
}
*new = '\0';
if (len)
return 0;
return 1;
}
Commit Message: nfsd: stricter decoding of write-like NFSv2/v3 ops
The NFSv2/v3 code does not systematically check whether we decode past
the end of the buffer. This generally appears to be harmless, but there
are a few places where we do arithmetic on the pointers involved and
don't account for the possibility that a length could be negative. Add
checks to catch these.
Reported-by: Tuomas Haanpää <[email protected]>
Reported-by: Ari Kauppi <[email protected]>
Reviewed-by: NeilBrown <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void reflectReflectedNameAttributeTestAttributeAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info)
{
TestObjectPython* imp = V8TestObjectPython::toNative(info.Holder());
v8SetReturnValueFast(info, WTF::getPtr(imp->fastGetAttribute(HTMLNames::reflectedNameAttributeAttr)), imp);
}
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 __exit vmx_exit(void)
{
free_page((unsigned long)vmx_msr_bitmap_legacy_x2apic);
free_page((unsigned long)vmx_msr_bitmap_longmode_x2apic);
free_page((unsigned long)vmx_msr_bitmap_legacy);
free_page((unsigned long)vmx_msr_bitmap_longmode);
free_page((unsigned long)vmx_io_bitmap_b);
free_page((unsigned long)vmx_io_bitmap_a);
free_page((unsigned long)vmx_vmwrite_bitmap);
free_page((unsigned long)vmx_vmread_bitmap);
#ifdef CONFIG_KEXEC
RCU_INIT_POINTER(crash_vmclear_loaded_vmcss, NULL);
synchronize_rcu();
#endif
kvm_exit();
}
Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry
CR4 isn't constant; at least the TSD and PCE bits can vary.
TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks
like it's correct.
This adds a branch and a read from cr4 to each vm entry. Because it is
extremely likely that consecutive entries into the same vcpu will have
the same host cr4 value, this fixes up the vmcs instead of restoring cr4
after the fact. A subsequent patch will add a kernel-wide cr4 shadow,
reducing the overhead in the common case to just two memory reads and a
branch.
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: Paolo Bonzini <[email protected]>
Cc: [email protected]
Cc: Petr Matousek <[email protected]>
Cc: Gleb Natapov <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
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: sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net,
const struct sctp_endpoint *ep,
const struct sctp_association *asoc,
const sctp_subtype_t type, void *arg,
sctp_cmd_seq_t *commands)
{
struct sctp_chunk *chunk = arg;
struct sctp_association *new_asoc;
sctp_init_chunk_t *peer_init;
struct sctp_chunk *repl;
struct sctp_ulpevent *ev, *ai_ev = NULL;
int error = 0;
struct sctp_chunk *err_chk_p;
struct sock *sk;
/* If the packet is an OOTB packet which is temporarily on the
* control endpoint, respond with an ABORT.
*/
if (ep == sctp_sk(net->sctp.ctl_sock)->ep) {
SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
}
/* Make sure that the COOKIE_ECHO chunk has a valid length.
* In this case, we check that we have enough for at least a
* chunk header. More detailed verification is done
* in sctp_unpack_cookie().
*/
if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t)))
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
/* If the endpoint is not listening or if the number of associations
* on the TCP-style socket exceed the max backlog, respond with an
* ABORT.
*/
sk = ep->base.sk;
if (!sctp_sstate(sk, LISTENING) ||
(sctp_style(sk, TCP) && sk_acceptq_is_full(sk)))
return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands);
/* "Decode" the chunk. We have no optional parameters so we
* are in good shape.
*/
chunk->subh.cookie_hdr =
(struct sctp_signed_cookie *)chunk->skb->data;
if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) -
sizeof(sctp_chunkhdr_t)))
goto nomem;
/* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint
* "Z" will reply with a COOKIE ACK chunk after building a TCB
* and moving to the ESTABLISHED state.
*/
new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error,
&err_chk_p);
/* FIXME:
* If the re-build failed, what is the proper error path
* from here?
*
* [We should abort the association. --piggy]
*/
if (!new_asoc) {
/* FIXME: Several errors are possible. A bad cookie should
* be silently discarded, but think about logging it too.
*/
switch (error) {
case -SCTP_IERROR_NOMEM:
goto nomem;
case -SCTP_IERROR_STALE_COOKIE:
sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands,
err_chk_p);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
case -SCTP_IERROR_BAD_SIG:
default:
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
/* Delay state machine commands until later.
*
* Re-build the bind address for the association is done in
* the sctp_unpack_cookie() already.
*/
/* This is a brand-new association, so these are not yet side
* effects--it is safe to run them here.
*/
peer_init = &chunk->subh.cookie_hdr->c.peer_init[0];
if (!sctp_process_init(new_asoc, chunk,
&chunk->subh.cookie_hdr->c.peer_addr,
peer_init, GFP_ATOMIC))
goto nomem_init;
/* SCTP-AUTH: Now that we've populate required fields in
* sctp_process_init, set up the assocaition shared keys as
* necessary so that we can potentially authenticate the ACK
*/
error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC);
if (error)
goto nomem_init;
/* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo
* is supposed to be authenticated and we have to do delayed
* authentication. We've just recreated the association using
* the information in the cookie and now it's much easier to
* do the authentication.
*/
if (chunk->auth_chunk) {
struct sctp_chunk auth;
sctp_ierror_t ret;
/* set-up our fake chunk so that we can process it */
auth.skb = chunk->auth_chunk;
auth.asoc = chunk->asoc;
auth.sctp_hdr = chunk->sctp_hdr;
auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk,
sizeof(sctp_chunkhdr_t));
skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t));
auth.transport = chunk->transport;
ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth);
/* We can now safely free the auth_chunk clone */
kfree_skb(chunk->auth_chunk);
if (ret != SCTP_IERROR_NO_ERROR) {
sctp_association_free(new_asoc);
return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands);
}
}
repl = sctp_make_cookie_ack(new_asoc, chunk);
if (!repl)
goto nomem_init;
/* RFC 2960 5.1 Normal Establishment of an Association
*
* D) IMPLEMENTATION NOTE: An implementation may choose to
* send the Communication Up notification to the SCTP user
* upon reception of a valid COOKIE ECHO chunk.
*/
ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0,
new_asoc->c.sinit_num_ostreams,
new_asoc->c.sinit_max_instreams,
NULL, GFP_ATOMIC);
if (!ev)
goto nomem_ev;
/* Sockets API Draft Section 5.3.1.6
* When a peer sends a Adaptation Layer Indication parameter , SCTP
* delivers this notification to inform the application that of the
* peers requested adaptation layer.
*/
if (new_asoc->peer.adaptation_ind) {
ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc,
GFP_ATOMIC);
if (!ai_ev)
goto nomem_aiev;
}
/* Add all the state machine commands now since we've created
* everything. This way we don't introduce memory corruptions
* during side-effect processing and correclty count established
* associations.
*/
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc));
sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE,
SCTP_STATE(SCTP_STATE_ESTABLISHED));
SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB);
SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS);
sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL());
if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE])
sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START,
SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE));
/* This will send the COOKIE ACK */
sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl));
/* Queue the ASSOC_CHANGE event */
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev));
/* Send up the Adaptation Layer Indication event */
if (ai_ev)
sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP,
SCTP_ULPEVENT(ai_ev));
return SCTP_DISPOSITION_CONSUME;
nomem_aiev:
sctp_ulpevent_free(ev);
nomem_ev:
sctp_chunk_free(repl);
nomem_init:
sctp_association_free(new_asoc);
nomem:
return SCTP_DISPOSITION_NOMEM;
}
Commit Message: net: sctp: fix sctp_sf_do_5_1D_ce to verify if we/peer is AUTH capable
RFC4895 introduced AUTH chunks for SCTP; during the SCTP
handshake RANDOM; CHUNKS; HMAC-ALGO are negotiated (CHUNKS
being optional though):
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
A special case is when an endpoint requires COOKIE-ECHO
chunks to be authenticated:
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
------------------ AUTH; COOKIE-ECHO ---------------->
<-------------------- COOKIE-ACK ---------------------
RFC4895, section 6.3. Receiving Authenticated Chunks says:
The receiver MUST use the HMAC algorithm indicated in
the HMAC Identifier field. If this algorithm was not
specified by the receiver in the HMAC-ALGO parameter in
the INIT or INIT-ACK chunk during association setup, the
AUTH chunk and all the chunks after it MUST be discarded
and an ERROR chunk SHOULD be sent with the error cause
defined in Section 4.1. [...] If no endpoint pair shared
key has been configured for that Shared Key Identifier,
all authenticated chunks MUST be silently discarded. [...]
When an endpoint requires COOKIE-ECHO chunks to be
authenticated, some special procedures have to be followed
because the reception of a COOKIE-ECHO chunk might result
in the creation of an SCTP association. If a packet arrives
containing an AUTH chunk as a first chunk, a COOKIE-ECHO
chunk as the second chunk, and possibly more chunks after
them, and the receiver does not have an STCB for that
packet, then authentication is based on the contents of
the COOKIE-ECHO chunk. In this situation, the receiver MUST
authenticate the chunks in the packet by using the RANDOM
parameters, CHUNKS parameters and HMAC_ALGO parameters
obtained from the COOKIE-ECHO chunk, and possibly a local
shared secret as inputs to the authentication procedure
specified in Section 6.3. If authentication fails, then
the packet is discarded. If the authentication is successful,
the COOKIE-ECHO and all the chunks after the COOKIE-ECHO
MUST be processed. If the receiver has an STCB, it MUST
process the AUTH chunk as described above using the STCB
from the existing association to authenticate the
COOKIE-ECHO chunk and all the chunks after it. [...]
Commit bbd0d59809f9 introduced the possibility to receive
and verification of AUTH chunk, including the edge case for
authenticated COOKIE-ECHO. On reception of COOKIE-ECHO,
the function sctp_sf_do_5_1D_ce() handles processing,
unpacks and creates a new association if it passed sanity
checks and also tests for authentication chunks being
present. After a new association has been processed, it
invokes sctp_process_init() on the new association and
walks through the parameter list it received from the INIT
chunk. It checks SCTP_PARAM_RANDOM, SCTP_PARAM_HMAC_ALGO
and SCTP_PARAM_CHUNKS, and copies them into asoc->peer
meta data (peer_random, peer_hmacs, peer_chunks) in case
sysctl -w net.sctp.auth_enable=1 is set. If in INIT's
SCTP_PARAM_SUPPORTED_EXT parameter SCTP_CID_AUTH is set,
peer_random != NULL and peer_hmacs != NULL the peer is to be
assumed asoc->peer.auth_capable=1, in any other case
asoc->peer.auth_capable=0.
Now, if in sctp_sf_do_5_1D_ce() chunk->auth_chunk is
available, we set up a fake auth chunk and pass that on to
sctp_sf_authenticate(), which at latest in
sctp_auth_calculate_hmac() reliably dereferences a NULL pointer
at position 0..0008 when setting up the crypto key in
crypto_hash_setkey() by using asoc->asoc_shared_key that is
NULL as condition key_id == asoc->active_key_id is true if
the AUTH chunk was injected correctly from remote. This
happens no matter what net.sctp.auth_enable sysctl says.
The fix is to check for net->sctp.auth_enable and for
asoc->peer.auth_capable before doing any operations like
sctp_sf_authenticate() as no key is activated in
sctp_auth_asoc_init_active_key() for each case.
Now as RFC4895 section 6.3 states that if the used HMAC-ALGO
passed from the INIT chunk was not used in the AUTH chunk, we
SHOULD send an error; however in this case it would be better
to just silently discard such a maliciously prepared handshake
as we didn't even receive a parameter at all. Also, as our
endpoint has no shared key configured, section 6.3 says that
MUST silently discard, which we are doing from now onwards.
Before calling sctp_sf_pdiscard(), we need not only to free
the association, but also the chunk->auth_chunk skb, as
commit bbd0d59809f9 created a skb clone in that case.
I have tested this locally by using netfilter's nfqueue and
re-injecting packets into the local stack after maliciously
modifying the INIT chunk (removing RANDOM; HMAC-ALGO param)
and the SCTP packet containing the COOKIE_ECHO (injecting
AUTH chunk before COOKIE_ECHO). Fixed with this patch applied.
Fixes: bbd0d59809f9 ("[SCTP]: Implement the receive and verification of AUTH chunk")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Cc: Neil Horman <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: GDataCache::GDataCache(
const FilePath& cache_root_path,
base::SequencedWorkerPool* pool,
const base::SequencedWorkerPool::SequenceToken& sequence_token)
: cache_root_path_(cache_root_path),
cache_paths_(GetCachePaths(cache_root_path_)),
pool_(pool),
sequence_token_(sequence_token),
ui_weak_ptr_factory_(this),
ui_weak_ptr_(ui_weak_ptr_factory_.GetWeakPtr()) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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 ExtensionOptionsGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached()) {
auto guest_zoom_controller =
ui_zoom::ZoomController::FromWebContents(web_contents());
guest_zoom_controller->SetZoomMode(
ui_zoom::ZoomController::ZOOM_MODE_ISOLATED);
SetGuestZoomLevelToMatchEmbedder();
if (params.url.GetOrigin() != options_page_.GetOrigin()) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EOG_BAD_ORIGIN);
}
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
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: juniper_pppoe_atm_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
uint16_t extracted_ethertype;
l2info.pictype = DLT_JUNIPER_PPPOE_ATM;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
extracted_ethertype = EXTRACT_16BITS(p);
/* this DLT contains nothing but raw PPPoE frames,
* prepended with a type field*/
if (ethertype_print(ndo, extracted_ethertype,
p+ETHERTYPE_LEN,
l2info.length-ETHERTYPE_LEN,
l2info.caplen-ETHERTYPE_LEN,
NULL, NULL) == 0)
/* ether_type not known, probably it wasn't one */
ND_PRINT((ndo, "unknown ethertype 0x%04x", extracted_ethertype));
return l2info.header_len;
}
Commit Message: CVE-2017-12993/Juniper: Add more bounds checks.
This fixes a buffer over-read discovered by Kamil Frankowicz.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void rds_inc_addref(struct rds_incoming *inc)
{
rdsdebug("addref inc %p ref %d\n", inc, atomic_read(&inc->i_refcount));
atomic_inc(&inc->i_refcount);
}
Commit Message: rds: set correct msg_namelen
Jay Fenlason ([email protected]) found a bug,
that recvfrom() on an RDS socket can return the contents of random kernel
memory to userspace if it was called with a address length larger than
sizeof(struct sockaddr_in).
rds_recvmsg() also fails to set the addr_len paramater properly before
returning, but that's just a bug.
There are also a number of cases wher recvfrom() can return an entirely bogus
address. Anything in rds_recvmsg() that returns a non-negative value but does
not go through the "sin = (struct sockaddr_in *)msg->msg_name;" code path
at the end of the while(1) loop will return up to 128 bytes of kernel memory
to userspace.
And I write two test programs to reproduce this bug, you will see that in
rds_server, fromAddr will be overwritten and the following sock_fd will be
destroyed.
Yes, it is the programmer's fault to set msg_namelen incorrectly, but it is
better to make the kernel copy the real length of address to user space in
such case.
How to run the test programs ?
I test them on 32bit x86 system, 3.5.0-rc7.
1 compile
gcc -o rds_client rds_client.c
gcc -o rds_server rds_server.c
2 run ./rds_server on one console
3 run ./rds_client on another console
4 you will see something like:
server is waiting to receive data...
old socket fd=3
server received data from client:data from client
msg.msg_namelen=32
new socket fd=-1067277685
sendmsg()
: Bad file descriptor
/***************** rds_client.c ********************/
int main(void)
{
int sock_fd;
struct sockaddr_in serverAddr;
struct sockaddr_in toAddr;
char recvBuffer[128] = "data from client";
struct msghdr msg;
struct iovec iov;
sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0);
if (sock_fd < 0) {
perror("create socket error\n");
exit(1);
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(4001);
if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
perror("bind() error\n");
close(sock_fd);
exit(1);
}
memset(&toAddr, 0, sizeof(toAddr));
toAddr.sin_family = AF_INET;
toAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
toAddr.sin_port = htons(4000);
msg.msg_name = &toAddr;
msg.msg_namelen = sizeof(toAddr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base = recvBuffer;
msg.msg_iov->iov_len = strlen(recvBuffer) + 1;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
if (sendmsg(sock_fd, &msg, 0) == -1) {
perror("sendto() error\n");
close(sock_fd);
exit(1);
}
printf("client send data:%s\n", recvBuffer);
memset(recvBuffer, '\0', 128);
msg.msg_name = &toAddr;
msg.msg_namelen = sizeof(toAddr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base = recvBuffer;
msg.msg_iov->iov_len = 128;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
if (recvmsg(sock_fd, &msg, 0) == -1) {
perror("recvmsg() error\n");
close(sock_fd);
exit(1);
}
printf("receive data from server:%s\n", recvBuffer);
close(sock_fd);
return 0;
}
/***************** rds_server.c ********************/
int main(void)
{
struct sockaddr_in fromAddr;
int sock_fd;
struct sockaddr_in serverAddr;
unsigned int addrLen;
char recvBuffer[128];
struct msghdr msg;
struct iovec iov;
sock_fd = socket(AF_RDS, SOCK_SEQPACKET, 0);
if(sock_fd < 0) {
perror("create socket error\n");
exit(0);
}
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(4000);
if (bind(sock_fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
perror("bind error\n");
close(sock_fd);
exit(1);
}
printf("server is waiting to receive data...\n");
msg.msg_name = &fromAddr;
/*
* I add 16 to sizeof(fromAddr), ie 32,
* and pay attention to the definition of fromAddr,
* recvmsg() will overwrite sock_fd,
* since kernel will copy 32 bytes to userspace.
*
* If you just use sizeof(fromAddr), it works fine.
* */
msg.msg_namelen = sizeof(fromAddr) + 16;
/* msg.msg_namelen = sizeof(fromAddr); */
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_iov->iov_base = recvBuffer;
msg.msg_iov->iov_len = 128;
msg.msg_control = 0;
msg.msg_controllen = 0;
msg.msg_flags = 0;
while (1) {
printf("old socket fd=%d\n", sock_fd);
if (recvmsg(sock_fd, &msg, 0) == -1) {
perror("recvmsg() error\n");
close(sock_fd);
exit(1);
}
printf("server received data from client:%s\n", recvBuffer);
printf("msg.msg_namelen=%d\n", msg.msg_namelen);
printf("new socket fd=%d\n", sock_fd);
strcat(recvBuffer, "--data from server");
if (sendmsg(sock_fd, &msg, 0) == -1) {
perror("sendmsg()\n");
close(sock_fd);
exit(1);
}
}
close(sock_fd);
return 0;
}
Signed-off-by: Weiping Pan <[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: void Location::reload(LocalDOMWindow* current_window) {
if (!IsAttached())
return;
if (GetDocument()->Url().ProtocolIsJavaScript())
return;
ToLocalDOMWindow(dom_window_)
->GetFrame()
->Reload(WebFrameLoadType::kReload,
ClientRedirectPolicy::kClientRedirect);
}
Commit Message: Check the source browsing context's CSP in Location::SetLocation prior to dispatching a navigation to a `javascript:` URL.
Makes `javascript:` navigations via window.location.href compliant with
https://html.spec.whatwg.org/#navigate, which states that the source
browsing context must be checked (rather than the current browsing
context).
Bug: 909865
Change-Id: Id6aef6eef56865e164816c67eb9fe07ea1cb1b4e
Reviewed-on: https://chromium-review.googlesource.com/c/1359823
Reviewed-by: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andrew Comminos <[email protected]>
Cr-Commit-Position: refs/heads/master@{#614451}
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: GLboolean WebGLRenderingContextBase::isFramebuffer(
WebGLFramebuffer* framebuffer) {
if (!framebuffer || isContextLost())
return 0;
if (!framebuffer->HasEverBeenBound())
return 0;
if (framebuffer->IsDeleted())
return 0;
return ContextGL()->IsFramebuffer(framebuffer->Object());
}
Commit Message: Validate all incoming WebGLObjects.
A few entry points were missing the correct validation.
Tested with improved conformance tests in
https://github.com/KhronosGroup/WebGL/pull/2654 .
Bug: 848914
Cq-Include-Trybots: luci.chromium.try:android_optional_gpu_tests_rel;luci.chromium.try:linux_optional_gpu_tests_rel;luci.chromium.try:mac_optional_gpu_tests_rel;luci.chromium.try:win_optional_gpu_tests_rel
Change-Id: Ib98a61cc5bf378d1b3338b04acd7e1bc4c2fe008
Reviewed-on: https://chromium-review.googlesource.com/1086718
Reviewed-by: Kai Ninomiya <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Commit-Queue: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565016}
CWE ID: CWE-119
Target: 1
Example 2:
Code: void V8WindowShell::clearForClose(bool destroyGlobal)
{
if (destroyGlobal)
m_global.clear();
if (m_context.isEmpty())
return;
m_document.clear();
disposeContext();
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 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: size_t jsvGetString(const JsVar *v, char *str, size_t len) {
assert(len>0);
const char *s = jsvGetConstString(v);
if (s) {
/* don't use strncpy here because we don't
* want to pad the entire buffer with zeros */
len--;
int l = 0;
while (*s && l<len) {
str[l] = s[l];
l++;
}
str[l] = 0;
return l;
} else if (jsvIsInt(v)) {
itostr(v->varData.integer, str, 10);
return strlen(str);
} else if (jsvIsFloat(v)) {
ftoa_bounded(v->varData.floating, str, len);
return strlen(str);
} else if (jsvHasCharacterData(v)) {
assert(!jsvIsStringExt(v));
size_t l = len;
JsvStringIterator it;
jsvStringIteratorNewConst(&it, v, 0);
while (jsvStringIteratorHasChar(&it)) {
if (l--<=1) {
*str = 0;
jsvStringIteratorFree(&it);
return len;
}
*(str++) = jsvStringIteratorGetChar(&it);
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
*str = 0;
return len-l;
} else {
JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here
if (stringVar) {
size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var
jsvUnLock(stringVar);
return l;
} else {
str[0] = 0;
jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string");
return 0;
}
}
}
Commit Message: fix jsvGetString regression
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 ResourceFetcher::StartLoad(Resource* resource) {
DCHECK(resource);
DCHECK(resource->StillNeedsLoad());
ResourceRequest request(resource->GetResourceRequest());
ResourceLoader* loader = nullptr;
{
Resource::RevalidationStartForbiddenScope
revalidation_start_forbidden_scope(resource);
ScriptForbiddenIfMainThreadScope script_forbidden_scope;
if (!Context().ShouldLoadNewResource(resource->GetType()) &&
IsMainThread()) {
GetMemoryCache()->Remove(resource);
return false;
}
ResourceResponse response;
blink::probe::PlatformSendRequest probe(&Context(), resource->Identifier(),
request, response,
resource->Options().initiator_info);
Context().DispatchWillSendRequest(resource->Identifier(), request, response,
resource->Options().initiator_info);
SecurityOrigin* source_origin = Context().GetSecurityOrigin();
if (source_origin && source_origin->HasSuborigin())
request.SetServiceWorkerMode(WebURLRequest::ServiceWorkerMode::kNone);
resource->SetResourceRequest(request);
loader = ResourceLoader::Create(this, scheduler_, resource);
if (resource->ShouldBlockLoadEvent())
loaders_.insert(loader);
else
non_blocking_loaders_.insert(loader);
StorePerformanceTimingInitiatorInformation(resource);
resource->SetFetcherSecurityOrigin(source_origin);
Resource::ProhibitAddRemoveClientInScope
prohibit_add_remove_client_in_scope(resource);
resource->NotifyStartLoad();
}
loader->Start();
return true;
}
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: 1
Example 2:
Code: void OmniboxViewViews::ShowImeIfNeeded() {
GetInputMethod()->ShowImeIfNeeded();
}
Commit Message: Strip JavaScript schemas on Linux text drop
When dropping text onto the Omnibox, any leading JavaScript schemes
should be stripped to avoid a "self-XSS" attack. This stripping already
occurs in all cases except when plaintext is dropped on Linux. This CL
corrects that oversight.
Bug: 768910
Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062
Reviewed-on: https://chromium-review.googlesource.com/685638
Reviewed-by: Justin Donnelly <[email protected]>
Commit-Queue: Eric Lawrence <[email protected]>
Cr-Commit-Position: refs/heads/master@{#504695}
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 se_portal_group *tcm_loop_make_naa_tpg(
struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct tcm_loop_hba *tl_hba = container_of(wwn,
struct tcm_loop_hba, tl_hba_wwn);
struct tcm_loop_tpg *tl_tpg;
char *tpgt_str, *end_ptr;
int ret;
unsigned short int tpgt;
tpgt_str = strstr(name, "tpgt_");
if (!tpgt_str) {
printk(KERN_ERR "Unable to locate \"tpgt_#\" directory"
" group\n");
return ERR_PTR(-EINVAL);
}
tpgt_str += 5; /* Skip ahead of "tpgt_" */
tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0);
if (tpgt > TL_TPGS_PER_HBA) {
printk(KERN_ERR "Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"
" %u\n", tpgt, TL_TPGS_PER_HBA);
return ERR_PTR(-EINVAL);
}
tl_tpg = &tl_hba->tl_hba_tpgs[tpgt];
tl_tpg->tl_hba = tl_hba;
tl_tpg->tl_tpgt = tpgt;
/*
* Register the tl_tpg as a emulated SAS TCM Target Endpoint
*/
ret = core_tpg_register(&tcm_loop_fabric_configfs->tf_ops,
wwn, &tl_tpg->tl_se_tpg, tl_tpg,
TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0)
return ERR_PTR(-ENOMEM);
printk(KERN_INFO "TCM_Loop_ConfigFS: Allocated Emulated %s"
" Target Port %s,t,0x%04x\n", tcm_loop_dump_proto_id(tl_hba),
config_item_name(&wwn->wwn_group.cg_item), tpgt);
return &tl_tpg->tl_se_tpg;
}
Commit Message: loopback: off by one in tcm_loop_make_naa_tpg()
This is an off by one 'tgpt' check in tcm_loop_make_naa_tpg() that could result
in memory corruption.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas A. Bellinger <[email protected]>
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 encrypted_update(struct key *key, struct key_preparsed_payload *prep)
{
struct encrypted_key_payload *epayload = key->payload.data[0];
struct encrypted_key_payload *new_epayload;
char *buf;
char *new_master_desc = NULL;
const char *format = NULL;
size_t datalen = prep->datalen;
int ret = 0;
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags))
return -ENOKEY;
if (datalen <= 0 || datalen > 32767 || !prep->data)
return -EINVAL;
buf = kmalloc(datalen + 1, GFP_KERNEL);
if (!buf)
return -ENOMEM;
buf[datalen] = 0;
memcpy(buf, prep->data, datalen);
ret = datablob_parse(buf, &format, &new_master_desc, NULL, NULL);
if (ret < 0)
goto out;
ret = valid_master_desc(new_master_desc, epayload->master_desc);
if (ret < 0)
goto out;
new_epayload = encrypted_key_alloc(key, epayload->format,
new_master_desc, epayload->datalen);
if (IS_ERR(new_epayload)) {
ret = PTR_ERR(new_epayload);
goto out;
}
__ekey_init(new_epayload, epayload->format, new_master_desc,
epayload->datalen);
memcpy(new_epayload->iv, epayload->iv, ivsize);
memcpy(new_epayload->payload_data, epayload->payload_data,
epayload->payload_datalen);
rcu_assign_keypointer(key, new_epayload);
call_rcu(&epayload->rcu, encrypted_rcu_free);
out:
kzfree(buf);
return ret;
}
Commit Message: KEYS: Fix race between updating and finding a negative key
Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection
error into one field such that:
(1) The instantiation state can be modified/read atomically.
(2) The error can be accessed atomically with the state.
(3) The error isn't stored unioned with the payload pointers.
This deals with the problem that the state is spread over three different
objects (two bits and a separate variable) and reading or updating them
atomically isn't practical, given that not only can uninstantiated keys
change into instantiated or rejected keys, but rejected keys can also turn
into instantiated keys - and someone accessing the key might not be using
any locking.
The main side effect of this problem is that what was held in the payload
may change, depending on the state. For instance, you might observe the
key to be in the rejected state. You then read the cached error, but if
the key semaphore wasn't locked, the key might've become instantiated
between the two reads - and you might now have something in hand that isn't
actually an error code.
The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error
code if the key is negatively instantiated. The key_is_instantiated()
function is replaced with key_is_positive() to avoid confusion as negative
keys are also 'instantiated'.
Additionally, barriering is included:
(1) Order payload-set before state-set during instantiation.
(2) Order state-read before payload-read when using the key.
Further separate barriering is necessary if RCU is being used to access the
payload content after reading the payload pointers.
Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data")
Cc: [email protected] # v4.4+
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
Reviewed-by: Eric Biggers <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: int simple_set_acl(struct inode *inode, struct posix_acl *acl, int type)
{
int error;
if (type == ACL_TYPE_ACCESS) {
error = posix_acl_equiv_mode(acl, &inode->i_mode);
if (error < 0)
return 0;
if (error == 0)
acl = NULL;
}
inode->i_ctime = CURRENT_TIME;
set_cached_acl(inode, type, acl);
return 0;
}
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: 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: XRRGetOutputPrimary(Display *dpy, Window window)
{
XExtDisplayInfo *info = XRRFindDisplay(dpy);
xRRGetOutputPrimaryReq *req;
xRRGetOutputPrimaryReply rep;
int major_version, minor_version;
RRCheckExtension (dpy, info, 0);
if (!XRRQueryVersion (dpy, &major_version, &minor_version) ||
!_XRRHasOutputPrimary (major_version, minor_version))
return None;
LockDisplay(dpy);
GetReq (RRGetOutputPrimary, req);
req->reqType = info->codes->major_opcode;
req->randrReqType = X_RRGetOutputPrimary;
req->window = window;
if (!_XReply (dpy, (xReply *) &rep, 0, xFalse))
rep.output = None;
UnlockDisplay(dpy);
SyncHandle();
return rep.output;
}
Commit Message:
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: static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr)
{
mainprog_info *mainprog_ptr;
/* retrieve the pointer to our special-purpose struct */
mainprog_ptr = png_get_progressive_ptr(png_ptr);
/* let the main program know that it should flush any buffered image
* data to the display now and set a "done" flag or whatever, but note
* that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do
* NOT call readpng2_cleanup() either here or in the finish_display()
* routine; wait until control returns to the main program via
* readpng2_decode_data() */
(*mainprog_ptr->mainprog_finish_display)();
/* all done */
return;
}
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: base::FilePath GetDownloadDirectory(Browser* browser) {
return GetDownloadPrefs(browser)->DownloadPath();
}
Commit Message: When turning a download into a navigation, navigate the right frame
Code changes from Nate Chapin <[email protected]>
Bug: 926105
Change-Id: I098599394e6ebe7d2fce5af838014297a337d294
Reviewed-on: https://chromium-review.googlesource.com/c/1454962
Reviewed-by: Camille Lamy <[email protected]>
Commit-Queue: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629547}
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: static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
smart_str *str = (smart_str *)rsrc->ptr;
smart_str_free(str);
efree(str);
}
Commit Message:
CWE ID: CWE-502
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 ip6_frag_queue(struct frag_queue *fq, struct sk_buff *skb,
struct frag_hdr *fhdr, int nhoff)
{
struct sk_buff *prev, *next;
struct net_device *dev;
int offset, end;
struct net *net = dev_net(skb_dst(skb)->dev);
if (fq->q.last_in & INET_FRAG_COMPLETE)
goto err;
offset = ntohs(fhdr->frag_off) & ~0x7;
end = offset + (ntohs(ipv6_hdr(skb)->payload_len) -
((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1)));
if ((unsigned int)end > IPV6_MAXPLEN) {
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
((u8 *)&fhdr->frag_off -
skb_network_header(skb)));
return -1;
}
if (skb->ip_summed == CHECKSUM_COMPLETE) {
const unsigned char *nh = skb_network_header(skb);
skb->csum = csum_sub(skb->csum,
csum_partial(nh, (u8 *)(fhdr + 1) - nh,
0));
}
/* Is this the final fragment? */
if (!(fhdr->frag_off & htons(IP6_MF))) {
/* If we already have some bits beyond end
* or have different end, the segment is corrupted.
*/
if (end < fq->q.len ||
((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len))
goto err;
fq->q.last_in |= INET_FRAG_LAST_IN;
fq->q.len = end;
} else {
/* Check if the fragment is rounded to 8 bytes.
* Required by the RFC.
*/
if (end & 0x7) {
/* RFC2460 says always send parameter problem in
* this case. -DaveM
*/
IP6_INC_STATS_BH(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_INHDRERRORS);
icmpv6_param_prob(skb, ICMPV6_HDR_FIELD,
offsetof(struct ipv6hdr, payload_len));
return -1;
}
if (end > fq->q.len) {
/* Some bits beyond end -> corruption. */
if (fq->q.last_in & INET_FRAG_LAST_IN)
goto err;
fq->q.len = end;
}
}
if (end == offset)
goto err;
/* Point into the IP datagram 'data' part. */
if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data))
goto err;
if (pskb_trim_rcsum(skb, end - offset))
goto err;
/* Find out which fragments are in front and at the back of us
* in the chain of fragments so far. We must know where to put
* this fragment, right?
*/
prev = fq->q.fragments_tail;
if (!prev || FRAG6_CB(prev)->offset < offset) {
next = NULL;
goto found;
}
prev = NULL;
for(next = fq->q.fragments; next != NULL; next = next->next) {
if (FRAG6_CB(next)->offset >= offset)
break; /* bingo! */
prev = next;
}
found:
/* We found where to put this one. Check for overlap with
* preceding fragment, and, if needed, align things so that
* any overlaps are eliminated.
*/
if (prev) {
int i = (FRAG6_CB(prev)->offset + prev->len) - offset;
if (i > 0) {
offset += i;
if (end <= offset)
goto err;
if (!pskb_pull(skb, i))
goto err;
if (skb->ip_summed != CHECKSUM_UNNECESSARY)
skb->ip_summed = CHECKSUM_NONE;
}
}
/* Look for overlap with succeeding segments.
* If we can merge fragments, do it.
*/
while (next && FRAG6_CB(next)->offset < end) {
int i = end - FRAG6_CB(next)->offset; /* overlap is 'i' bytes */
if (i < next->len) {
/* Eat head of the next overlapped fragment
* and leave the loop. The next ones cannot overlap.
*/
if (!pskb_pull(next, i))
goto err;
FRAG6_CB(next)->offset += i; /* next fragment */
fq->q.meat -= i;
if (next->ip_summed != CHECKSUM_UNNECESSARY)
next->ip_summed = CHECKSUM_NONE;
break;
} else {
struct sk_buff *free_it = next;
/* Old fragment is completely overridden with
* new one drop it.
*/
next = next->next;
if (prev)
prev->next = next;
else
fq->q.fragments = next;
fq->q.meat -= free_it->len;
frag_kfree_skb(fq->q.net, free_it);
}
}
FRAG6_CB(skb)->offset = offset;
/* Insert this fragment in the chain of fragments. */
skb->next = next;
if (!next)
fq->q.fragments_tail = skb;
if (prev)
prev->next = skb;
else
fq->q.fragments = skb;
dev = skb->dev;
if (dev) {
fq->iif = dev->ifindex;
skb->dev = NULL;
}
fq->q.stamp = skb->tstamp;
fq->q.meat += skb->len;
atomic_add(skb->truesize, &fq->q.net->mem);
/* The first fragment.
* nhoffset is obtained from the first fragment, of course.
*/
if (offset == 0) {
fq->nhoffset = nhoff;
fq->q.last_in |= INET_FRAG_FIRST_IN;
}
if (fq->q.last_in == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) &&
fq->q.meat == fq->q.len)
return ip6_frag_reasm(fq, prev, dev);
write_lock(&ip6_frags.lock);
list_move_tail(&fq->q.lru_list, &fq->q.net->lru_list);
write_unlock(&ip6_frags.lock);
return -1;
err:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_REASMFAILS);
kfree_skb(skb);
return -1;
}
Commit Message: ipv6: discard overlapping fragment
RFC5722 prohibits reassembling fragments when some data overlaps.
Bug spotted by Zhang Zuotao <[email protected]>.
Signed-off-by: Nicolas Dichtel <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void RenderFrameImpl::ResumeBlockedRequests() {
frame_request_blocker_->Resume();
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
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: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
UWORD16 u2_height;
UWORD16 u2_width;
if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND;
}
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u2_width = impeg2d_bit_stream_get(ps_stream,12);
u2_height = impeg2d_bit_stream_get(ps_stream,12);
if (0 == u2_width || 0 == u2_height)
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR;
return e_error;
}
if ((u2_width != ps_dec->u2_horizontal_size)
|| (u2_height != ps_dec->u2_vertical_size))
{
if (0 == ps_dec->u2_header_done)
{
/* This is the first time we are reading the resolution */
ps_dec->u2_horizontal_size = u2_width;
ps_dec->u2_vertical_size = u2_height;
if (0 == ps_dec->u4_frm_buf_stride)
{
ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width);
}
}
else
{
if (0 == ps_dec->i4_pic_count)
{
/* Decoder has not decoded a single frame since the last
* reset/init. This implies that we have two headers in the
* input stream. So, do not indicate a resolution change, since
* this can take the decoder into an infinite loop.
*/
return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR;
}
else if((u2_width > ps_dec->u2_create_max_width)
|| (u2_height > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = u2_height;
ps_dec->u2_reinit_max_width = u2_width;
return e_error;
}
else
{
/* The resolution has changed */
return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED;
}
}
}
if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width)
|| (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height))
{
IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS;
ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size;
ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size;
return e_error;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* aspect_ratio_info (4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4);
/*------------------------------------------------------------------------*/
/* Frame rate code(4 bits) */
/*------------------------------------------------------------------------*/
ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4);
if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE)
{
return IMPEG2D_FRM_HDR_DECODE_ERR;
}
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* bit_rate_value (18 bits) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,18);
GET_MARKER_BIT(ps_dec,ps_stream);
/*------------------------------------------------------------------------*/
/* Flush the following as they are not being used */
/* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */
/*------------------------------------------------------------------------*/
impeg2d_bit_stream_flush(ps_stream,11);
/*------------------------------------------------------------------------*/
/* Quantization matrix for the intra blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
/*------------------------------------------------------------------------*/
/* Quantization matrix for the inter blocks */
/*------------------------------------------------------------------------*/
if(impeg2d_bit_stream_get_bit(ps_stream) == 1)
{
UWORD16 i;
for(i = 0; i < NUM_PELS_IN_BLOCK; i++)
{
ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8);
}
}
else
{
memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default,
NUM_PELS_IN_BLOCK);
}
impeg2d_next_start_code(ps_dec);
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
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: int svc_rdma_xdr_encode_error(struct svcxprt_rdma *xprt,
struct rpcrdma_msg *rmsgp,
enum rpcrdma_errcode err, __be32 *va)
{
__be32 *startp = va;
*va++ = rmsgp->rm_xid;
*va++ = rmsgp->rm_vers;
*va++ = xprt->sc_fc_credits;
*va++ = rdma_error;
*va++ = cpu_to_be32(err);
if (err == ERR_VERS) {
*va++ = rpcrdma_version;
*va++ = rpcrdma_version;
}
return (int)((unsigned long)va - (unsigned long)startp);
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
Target: 1
Example 2:
Code: void RenderWidgetHostImpl::SetPageFocus(bool focused) {
is_focused_ = focused;
if (!focused) {
if (IsMouseLocked())
view_->UnlockMouse();
if (IsKeyboardLocked())
UnlockKeyboard();
if (auto* touch_emulator = GetExistingTouchEmulator())
touch_emulator->CancelTouch();
} else if (keyboard_lock_allowed_) {
LockKeyboard();
}
GetWidgetInputHandler()->SetFocus(focused);
if (RenderViewHost::From(this) && delegate_)
delegate_->ReplicatePageFocus(focused);
}
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: void BrowserTabStripController::PerformDrop(bool drop_before,
int index,
const GURL& url) {
chrome::NavigateParams params(browser_, url, content::PAGE_TRANSITION_LINK);
params.tabstrip_index = index;
if (drop_before) {
content::RecordAction(UserMetricsAction("Tab_DropURLBetweenTabs"));
params.disposition = NEW_FOREGROUND_TAB;
} else {
content::RecordAction(UserMetricsAction("Tab_DropURLOnTab"));
params.disposition = CURRENT_TAB;
params.source_contents = model_->GetTabContentsAt(index);
}
params.window_action = chrome::NavigateParams::SHOW_WINDOW;
chrome::Navigate(¶ms);
}
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: void NetworkHandler::ContinueInterceptedRequest(
const std::string& interception_id,
Maybe<std::string> error_reason,
Maybe<std::string> base64_raw_response,
Maybe<std::string> url,
Maybe<std::string> method,
Maybe<std::string> post_data,
Maybe<protocol::Network::Headers> headers,
Maybe<protocol::Network::AuthChallengeResponse> auth_challenge_response,
std::unique_ptr<ContinueInterceptedRequestCallback> callback) {
DevToolsInterceptorController* interceptor =
DevToolsInterceptorController::FromBrowserContext(
process_->GetBrowserContext());
if (!interceptor) {
callback->sendFailure(Response::InternalError());
return;
}
base::Optional<std::string> raw_response;
if (base64_raw_response.isJust()) {
std::string decoded;
if (!base::Base64Decode(base64_raw_response.fromJust(), &decoded)) {
callback->sendFailure(Response::InvalidParams("Invalid rawResponse."));
return;
}
raw_response = decoded;
}
base::Optional<net::Error> error;
bool mark_as_canceled = false;
if (error_reason.isJust()) {
bool ok;
error = NetErrorFromString(error_reason.fromJust(), &ok);
if (!ok) {
callback->sendFailure(Response::InvalidParams("Invalid errorReason."));
return;
}
mark_as_canceled = true;
}
interceptor->ContinueInterceptedRequest(
interception_id,
std::make_unique<DevToolsURLRequestInterceptor::Modifications>(
std::move(error), std::move(raw_response), std::move(url),
std::move(method), std::move(post_data), std::move(headers),
std::move(auth_challenge_response), mark_as_canceled),
std::move(callback));
}
Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable
This keeps BrowserContext* and StoragePartition* instead of
RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost
upon closure of DevTools front-end.
Bug: 801117, 783067, 780694
Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b
Reviewed-on: https://chromium-review.googlesource.com/876657
Commit-Queue: Andrey Kosyakov <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#531157}
CWE ID: CWE-20
Target: 1
Example 2:
Code: iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status,
gss_ctx_id_t context_handle, gss_qop_t qop_req,
gss_iov_buffer_desc *iov, int iov_count)
{
iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;
if (ctx->gssc == GSS_C_NO_CONTEXT)
return GSS_S_NO_CONTEXT;
return krb5_gss_get_mic_iov_length(minor_status, ctx->gssc, qop_req, iov,
iov_count);
}
Commit Message: Fix IAKERB context export/import [CVE-2015-2698]
The patches for CVE-2015-2696 contained a regression in the newly
added IAKERB iakerb_gss_export_sec_context() function, which could
cause it to corrupt memory. Fix the regression by properly
dereferencing the context_handle pointer before casting it.
Also, the patches did not implement an IAKERB gss_import_sec_context()
function, under the erroneous belief that an exported IAKERB context
would be tagged as a krb5 context. Implement it now to allow IAKERB
contexts to be successfully exported and imported after establishment.
CVE-2015-2698:
In any MIT krb5 release with the patches for CVE-2015-2696 applied, an
application which calls gss_export_sec_context() may experience memory
corruption if the context was established using the IAKERB mechanism.
Historically, some vulnerabilities of this nature can be translated
into remote code execution, though the necessary exploits must be
tailored to the individual application and are usually quite
complicated.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C
ticket: 8273 (new)
target_version: 1.14
tags: pullup
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: create_filesystem_object(struct archive_write_disk *a)
{
/* Create the entry. */
const char *linkname;
mode_t final_mode, mode;
int r;
/* We identify hard/symlinks according to the link names. */
/* Since link(2) and symlink(2) don't handle modes, we're done here. */
linkname = archive_entry_hardlink(a->entry);
if (linkname != NULL) {
#if !HAVE_LINK
return (EPERM);
#else
r = link(linkname, a->name) ? errno : 0;
/*
* New cpio and pax formats allow hardlink entries
* to carry data, so we may have to open the file
* for hardlink entries.
*
* If the hardlink was successfully created and
* the archive doesn't have carry data for it,
* consider it to be non-authoritative for meta data.
* This is consistent with GNU tar and BSD pax.
* If the hardlink does carry data, let the last
* archive entry decide ownership.
*/
if (r == 0 && a->filesize <= 0) {
a->todo = 0;
a->deferred = 0;
} else if (r == 0 && a->filesize > 0) {
a->fd = open(a->name,
O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(a->fd);
if (a->fd < 0)
r = errno;
}
return (r);
#endif
}
linkname = archive_entry_symlink(a->entry);
if (linkname != NULL) {
#if HAVE_SYMLINK
return symlink(linkname, a->name) ? errno : 0;
#else
return (EPERM);
#endif
}
/*
* The remaining system calls all set permissions, so let's
* try to take advantage of that to avoid an extra chmod()
* call. (Recall that umask is set to zero right now!)
*/
/* Mode we want for the final restored object (w/o file type bits). */
final_mode = a->mode & 07777;
/*
* The mode that will actually be restored in this step. Note
* that SUID, SGID, etc, require additional work to ensure
* security, so we never restore them at this point.
*/
mode = final_mode & 0777 & ~a->user_umask;
switch (a->mode & AE_IFMT) {
default:
/* POSIX requires that we fall through here. */
/* FALLTHROUGH */
case AE_IFREG:
a->fd = open(a->name,
O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
__archive_ensure_cloexec_flag(a->fd);
r = (a->fd < 0);
break;
case AE_IFCHR:
#ifdef HAVE_MKNOD
/* Note: we use AE_IFCHR for the case label, and
* S_IFCHR for the mknod() call. This is correct. */
r = mknod(a->name, mode | S_IFCHR,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a char device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFBLK:
#ifdef HAVE_MKNOD
r = mknod(a->name, mode | S_IFBLK,
archive_entry_rdev(a->entry));
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a block device node. */
return (EINVAL);
#endif /* HAVE_MKNOD */
case AE_IFDIR:
mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
r = mkdir(a->name, mode);
if (r == 0) {
/* Defer setting dir times. */
a->deferred |= (a->todo & TODO_TIMES);
a->todo &= ~TODO_TIMES;
/* Never use an immediate chmod(). */
/* We can't avoid the chmod() entirely if EXTRACT_PERM
* because of SysV SGID inheritance. */
if ((mode != final_mode)
|| (a->flags & ARCHIVE_EXTRACT_PERM))
a->deferred |= (a->todo & TODO_MODE);
a->todo &= ~TODO_MODE;
}
break;
case AE_IFIFO:
#ifdef HAVE_MKFIFO
r = mkfifo(a->name, mode);
break;
#else
/* TODO: Find a better way to warn about our inability
* to restore a fifo. */
return (EINVAL);
#endif /* HAVE_MKFIFO */
}
/* All the system calls above set errno on failure. */
if (r)
return (errno);
/* If we managed to set the final mode, we've avoided a chmod(). */
if (mode == final_mode)
a->todo &= ~TODO_MODE;
return (0);
}
Commit Message: Fixes for Issue #745 and Issue #746 from Doran Moppert.
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 page *alloc_huge_page(struct vm_area_struct *vma,
unsigned long addr, int avoid_reserve)
{
struct hstate *h = hstate_vma(vma);
struct page *page;
struct address_space *mapping = vma->vm_file->f_mapping;
struct inode *inode = mapping->host;
long chg;
/*
* Processes that did not create the mapping will have no reserves and
* will not have accounted against quota. Check that the quota can be
* made before satisfying the allocation
* MAP_NORESERVE mappings may also need pages and quota allocated
* if no reserve mapping overlaps.
*/
chg = vma_needs_reservation(h, vma, addr);
if (chg < 0)
return ERR_PTR(-VM_FAULT_OOM);
if (chg)
if (hugetlb_get_quota(inode->i_mapping, chg))
return ERR_PTR(-VM_FAULT_SIGBUS);
spin_lock(&hugetlb_lock);
page = dequeue_huge_page_vma(h, vma, addr, avoid_reserve);
spin_unlock(&hugetlb_lock);
if (!page) {
page = alloc_buddy_huge_page(h, NUMA_NO_NODE);
if (!page) {
hugetlb_put_quota(inode->i_mapping, chg);
return ERR_PTR(-VM_FAULT_SIGBUS);
}
}
set_page_private(page, (unsigned long) mapping);
vma_commit_reservation(h, vma, addr);
return page;
}
Commit Message: hugepages: fix use after free bug in "quota" handling
hugetlbfs_{get,put}_quota() are badly named. They don't interact with the
general quota handling code, and they don't much resemble its behaviour.
Rather than being about maintaining limits on on-disk block usage by
particular users, they are instead about maintaining limits on in-memory
page usage (including anonymous MAP_PRIVATE copied-on-write pages)
associated with a particular hugetlbfs filesystem instance.
Worse, they work by having callbacks to the hugetlbfs filesystem code from
the low-level page handling code, in particular from free_huge_page().
This is a layering violation of itself, but more importantly, if the
kernel does a get_user_pages() on hugepages (which can happen from KVM
amongst others), then the free_huge_page() can be delayed until after the
associated inode has already been freed. If an unmount occurs at the
wrong time, even the hugetlbfs superblock where the "quota" limits are
stored may have been freed.
Andrew Barry proposed a patch to fix this by having hugepages, instead of
storing a pointer to their address_space and reaching the superblock from
there, had the hugepages store pointers directly to the superblock,
bumping the reference count as appropriate to avoid it being freed.
Andrew Morton rejected that version, however, on the grounds that it made
the existing layering violation worse.
This is a reworked version of Andrew's patch, which removes the extra, and
some of the existing, layering violation. It works by introducing the
concept of a hugepage "subpool" at the lower hugepage mm layer - that is a
finite logical pool of hugepages to allocate from. hugetlbfs now creates
a subpool for each filesystem instance with a page limit set, and a
pointer to the subpool gets added to each allocated hugepage, instead of
the address_space pointer used now. The subpool has its own lifetime and
is only freed once all pages in it _and_ all other references to it (i.e.
superblocks) are gone.
subpools are optional - a NULL subpool pointer is taken by the code to
mean that no subpool limits are in effect.
Previous discussion of this bug found in: "Fix refcounting in hugetlbfs
quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or
http://marc.info/?l=linux-mm&m=126928970510627&w=1
v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to
alloc_huge_page() - since it already takes the vma, it is not necessary.
Signed-off-by: Andrew Barry <[email protected]>
Signed-off-by: David Gibson <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Hillf Danton <[email protected]>
Cc: Paul Mackerras <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: rpc_free_auth(struct rpc_clnt *clnt)
{
if (clnt->cl_auth == NULL) {
rpc_free_client(clnt);
return;
}
/*
* Note: RPCSEC_GSS may need to send NULL RPC calls in order to
* release remaining GSS contexts. This mechanism ensures
* that it can do so safely.
*/
atomic_inc(&clnt->cl_count);
rpcauth_release(clnt->cl_auth);
clnt->cl_auth = NULL;
if (atomic_dec_and_test(&clnt->cl_count))
rpc_free_client(clnt);
}
Commit Message: NLM: Don't hang forever on NLM unlock requests
If the NLM daemon is killed on the NFS server, we can currently end up
hanging forever on an 'unlock' request, instead of aborting. Basically,
if the rpcbind request fails, or the server keeps returning garbage, we
really want to quit instead of retrying.
Tested-by: Vasily Averin <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
Cc: [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 void __net_exit ip6mr_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
remove_proc_entry("ip6_mr_cache", net->proc_net);
remove_proc_entry("ip6_mr_vif", net->proc_net);
#endif
ip6mr_rules_exit(net);
}
Commit Message: ipv6: check sk sk_type and protocol early in ip_mroute_set/getsockopt
Commit 5e1859fbcc3c ("ipv4: ipmr: various fixes and cleanups") fixed
the issue for ipv4 ipmr:
ip_mroute_setsockopt() & ip_mroute_getsockopt() should not
access/set raw_sk(sk)->ipmr_table before making sure the socket
is a raw socket, and protocol is IGMP
The same fix should be done for ipv6 ipmr as well.
This patch can fix the panic caused by overwriting the same offset
as ipmr_table as in raw_sk(sk) when accessing other type's socket
by ip_mroute_setsockopt().
Signed-off-by: Xin Long <[email protected]>
Signed-off-by: David S. Miller <[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: static void webkit_web_view_settings_notify(WebKitWebSettings* webSettings, GParamSpec* pspec, WebKitWebView* webView)
{
Settings* settings = core(webView)->settings();
const gchar* name = g_intern_string(pspec->name);
GValue value = { 0, { { 0 } } };
g_value_init(&value, pspec->value_type);
g_object_get_property(G_OBJECT(webSettings), name, &value);
if (name == g_intern_string("default-encoding"))
settings->setDefaultTextEncodingName(g_value_get_string(&value));
else if (name == g_intern_string("cursive-font-family"))
settings->setCursiveFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-family"))
settings->setStandardFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("fantasy-font-family"))
settings->setFantasyFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("monospace-font-family"))
settings->setFixedFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("sans-serif-font-family"))
settings->setSansSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("serif-font-family"))
settings->setSerifFontFamily(g_value_get_string(&value));
else if (name == g_intern_string("default-font-size"))
settings->setDefaultFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("default-monospace-font-size"))
settings->setDefaultFixedFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-font-size"))
settings->setMinimumFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("minimum-logical-font-size"))
settings->setMinimumLogicalFontSize(pixelsFromSize(webView, g_value_get_int(&value)));
else if (name == g_intern_string("enforce-96-dpi"))
webkit_web_view_screen_changed(GTK_WIDGET(webView), NULL);
else if (name == g_intern_string("auto-load-images"))
settings->setLoadsImagesAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("auto-shrink-images"))
settings->setShrinksStandaloneImagesToFit(g_value_get_boolean(&value));
else if (name == g_intern_string("print-backgrounds"))
settings->setShouldPrintBackgrounds(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-scripts"))
settings->setJavaScriptEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-plugins"))
settings->setPluginsEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dns-prefetching"))
settings->setDNSPrefetchingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("resizable-text-areas"))
settings->setTextAreasAreResizable(g_value_get_boolean(&value));
else if (name == g_intern_string("user-stylesheet-uri"))
settings->setUserStyleSheetLocation(KURL(KURL(), g_value_get_string(&value)));
else if (name == g_intern_string("enable-developer-extras"))
settings->setDeveloperExtrasEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-private-browsing"))
settings->setPrivateBrowsingEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-caret-browsing"))
settings->setCaretBrowsingEnabled(g_value_get_boolean(&value));
#if ENABLE(DATABASE)
else if (name == g_intern_string("enable-html5-database")) {
AbstractDatabase::setIsAvailable(g_value_get_boolean(&value));
}
#endif
else if (name == g_intern_string("enable-html5-local-storage"))
settings->setLocalStorageEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-xss-auditor"))
settings->setXSSAuditorEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-spatial-navigation"))
settings->setSpatialNavigationEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-frame-flattening"))
settings->setFrameFlatteningEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-open-windows-automatically"))
settings->setJavaScriptCanOpenWindowsAutomatically(g_value_get_boolean(&value));
else if (name == g_intern_string("javascript-can-access-clipboard"))
settings->setJavaScriptCanAccessClipboard(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-offline-web-application-cache"))
settings->setOfflineWebApplicationCacheEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("editing-behavior"))
settings->setEditingBehaviorType(static_cast<WebCore::EditingBehaviorType>(g_value_get_enum(&value)));
else if (name == g_intern_string("enable-universal-access-from-file-uris"))
settings->setAllowUniversalAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-file-access-from-file-uris"))
settings->setAllowFileAccessFromFileURLs(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-dom-paste"))
settings->setDOMPasteAllowed(g_value_get_boolean(&value));
else if (name == g_intern_string("tab-key-cycles-through-elements")) {
Page* page = core(webView);
if (page)
page->setTabKeyCyclesThroughElements(g_value_get_boolean(&value));
} else if (name == g_intern_string("enable-site-specific-quirks"))
settings->setNeedsSiteSpecificQuirks(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-page-cache"))
settings->setUsesPageCache(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-java-applet"))
settings->setJavaEnabled(g_value_get_boolean(&value));
else if (name == g_intern_string("enable-hyperlink-auditing"))
settings->setHyperlinkAuditingEnabled(g_value_get_boolean(&value));
#if ENABLE(SPELLCHECK)
else if (name == g_intern_string("spell-checking-languages")) {
WebKit::EditorClient* client = static_cast<WebKit::EditorClient*>(core(webView)->editorClient());
static_cast<WebKit::TextCheckerClientEnchant*>(client->textChecker())->updateSpellCheckingLanguage(g_value_get_string(&value));
}
#endif
#if ENABLE(WEBGL)
else if (name == g_intern_string("enable-webgl"))
settings->setWebGLEnabled(g_value_get_boolean(&value));
#endif
else if (!g_object_class_find_property(G_OBJECT_GET_CLASS(webSettings), name))
g_warning("Unexpected setting '%s'", name);
g_value_unset(&value);
}
Commit Message: 2011-06-02 Joone Hur <[email protected]>
Reviewed by Martin Robinson.
[GTK] Only load dictionaries if spell check is enabled
https://bugs.webkit.org/show_bug.cgi?id=32879
We don't need to call enchant if enable-spell-checking is false.
* webkit/webkitwebview.cpp:
(webkit_web_view_update_settings): Skip loading dictionaries when enable-spell-checking is false.
(webkit_web_view_settings_notify): Ditto.
git-svn-id: svn://svn.chromium.org/blink/trunk@87925 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399
Target: 1
Example 2:
Code: v8::Handle<v8::Object> V8TestObject::createWrapper(PassRefPtr<TestObject> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
{
ASSERT(impl);
ASSERT(!DOMDataStore::containsWrapper<V8TestObject>(impl.get(), isolate));
if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) {
const WrapperTypeInfo* actualInfo = ScriptWrappable::getTypeInfoFromObject(impl.get());
RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction);
}
v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate);
if (UNLIKELY(wrapper.IsEmpty()))
return wrapper;
installPerContextEnabledProperties(wrapper, impl.get(), isolate);
V8DOMWrapper::associateObjectWithWrapper<V8TestObject>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Independent);
return wrapper;
}
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 uint8_t section_data(NeAACDecStruct *hDecoder, ic_stream *ics, bitfile *ld)
{
uint8_t g;
uint8_t sect_esc_val, sect_bits;
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
sect_bits = 3;
else
sect_bits = 5;
sect_esc_val = (1<<sect_bits) - 1;
#if 0
printf("\ntotal sfb %d\n", ics->max_sfb);
printf(" sect top cb\n");
#endif
for (g = 0; g < ics->num_window_groups; g++)
{
uint8_t k = 0;
uint8_t i = 0;
while (k < ics->max_sfb)
{
#ifdef ERROR_RESILIENCE
uint8_t vcb11 = 0;
#endif
uint8_t sfb;
uint8_t sect_len_incr;
uint16_t sect_len = 0;
uint8_t sect_cb_bits = 4;
/* if "faad_getbits" detects error and returns "0", "k" is never
incremented and we cannot leave the while loop */
if (ld->error != 0)
return 14;
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSectionDataResilienceFlag)
sect_cb_bits = 5;
#endif
ics->sect_cb[g][i] = (uint8_t)faad_getbits(ld, sect_cb_bits
DEBUGVAR(1,71,"section_data(): sect_cb"));
if (ics->sect_cb[g][i] == 12)
return 32;
#if 0
printf("%d\n", ics->sect_cb[g][i]);
#endif
#ifndef DRM
if (ics->sect_cb[g][i] == NOISE_HCB)
ics->noise_used = 1;
#else
/* PNS not allowed in DRM */
if (ics->sect_cb[g][i] == NOISE_HCB)
return 29;
#endif
if (ics->sect_cb[g][i] == INTENSITY_HCB2 || ics->sect_cb[g][i] == INTENSITY_HCB)
ics->is_used = 1;
#ifdef ERROR_RESILIENCE
if (hDecoder->aacSectionDataResilienceFlag)
{
if ((ics->sect_cb[g][i] == 11) ||
((ics->sect_cb[g][i] >= 16) && (ics->sect_cb[g][i] <= 32)))
{
vcb11 = 1;
}
}
if (vcb11)
{
sect_len_incr = 1;
} else {
#endif
sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
DEBUGVAR(1,72,"section_data(): sect_len_incr"));
#ifdef ERROR_RESILIENCE
}
#endif
while ((sect_len_incr == sect_esc_val) /* &&
(k+sect_len < ics->max_sfb)*/)
{
sect_len += sect_len_incr;
sect_len_incr = (uint8_t)faad_getbits(ld, sect_bits
DEBUGVAR(1,72,"section_data(): sect_len_incr"));
}
sect_len += sect_len_incr;
ics->sect_start[g][i] = k;
ics->sect_end[g][i] = k + sect_len;
#if 0
printf("%d\n", ics->sect_start[g][i]);
#endif
#if 0
printf("%d\n", ics->sect_end[g][i]);
#endif
if (ics->window_sequence == EIGHT_SHORT_SEQUENCE)
{
if (k + sect_len > 8*15)
return 15;
if (i >= 8*15)
return 15;
} else {
if (k + sect_len > MAX_SFB)
return 15;
if (i >= MAX_SFB)
return 15;
}
for (sfb = k; sfb < k + sect_len; sfb++)
{
ics->sfb_cb[g][sfb] = ics->sect_cb[g][i];
#if 0
printf("%d\n", ics->sfb_cb[g][sfb]);
#endif
}
#if 0
printf(" %6d %6d %6d\n",
i,
ics->sect_end[g][i],
ics->sect_cb[g][i]);
#endif
k += sect_len;
i++;
}
ics->num_sec[g] = i;
/* the sum of all sect_len_incr elements for a given window
* group shall equal max_sfb */
if (k != ics->max_sfb)
{
return 32;
}
#if 0
printf("%d\n", ics->num_sec[g]);
#endif
}
#if 0
printf("\n");
#endif
return 0;
}
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: userauth_gssapi(struct ssh *ssh)
{
Authctxt *authctxt = ssh->authctxt;
gss_OID_desc goid = {0, NULL};
Gssctxt *ctxt = NULL;
int r, present;
u_int mechs;
OM_uint32 ms;
size_t len;
u_char *doid = NULL;
if (!authctxt->valid || authctxt->user == NULL)
return (0);
if ((r = sshpkt_get_u32(ssh, &mechs)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (mechs == 0) {
debug("Mechanism negotiation is not supported");
return (0);
}
do {
mechs--;
free(doid);
present = 0;
if ((r = sshpkt_get_string(ssh, &doid, &len)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
if (len > 2 && doid[0] == SSH_GSS_OIDTYPE &&
doid[1] == len - 2) {
goid.elements = doid + 2;
goid.length = len - 2;
ssh_gssapi_test_oid_supported(&ms, &goid, &present);
} else {
logit("Badly formed OID received");
}
} while (mechs > 0 && !present);
if (!present) {
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
if (GSS_ERROR(PRIVSEP(ssh_gssapi_server_ctx(&ctxt, &goid)))) {
if (ctxt != NULL)
ssh_gssapi_delete_ctx(&ctxt);
free(doid);
authctxt->server_caused_failure = 1;
return (0);
}
authctxt->methoddata = (void *)ctxt;
/* Return the OID that we received */
if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE)) != 0 ||
(r = sshpkt_put_string(ssh, doid, len)) != 0 ||
(r = sshpkt_send(ssh)) != 0)
fatal("%s: %s", __func__, ssh_err(r));
free(doid);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token);
ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok);
authctxt->postponed = 1;
return (0);
}
Commit Message: delay bailout for invalid authenticating user until after the packet
containing the request has been fully parsed. Reported by Dariusz Tytko
and Michał Sajdak; ok deraadt
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLButtonElement::accessKeyAction(bool sendMouseEvents)
{
focus();
dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}
Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment.
This virtual function should return true if the form control can hanlde
'autofocucs' attribute if it is specified.
Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent
because interactiveness is required for autofocus capability.
BUG=none
TEST=none; no behavior changes.
Review URL: https://codereview.chromium.org/143343003
git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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 process_backlog(struct napi_struct *napi, int quota)
{
struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
bool again = true;
int work = 0;
/* Check if we have pending ipi, its better to send them now,
* not waiting net_rx_action() end.
*/
if (sd_has_rps_ipi_waiting(sd)) {
local_irq_disable();
net_rps_action_and_irq_enable(sd);
}
napi->weight = dev_rx_weight;
while (again) {
struct sk_buff *skb;
while ((skb = __skb_dequeue(&sd->process_queue))) {
rcu_read_lock();
__netif_receive_skb(skb);
rcu_read_unlock();
input_queue_head_incr(sd);
if (++work >= quota)
return work;
}
local_irq_disable();
rps_lock(sd);
if (skb_queue_empty(&sd->input_pkt_queue)) {
/*
* Inline a custom version of __napi_complete().
* only current cpu owns and manipulates this napi,
* and NAPI_STATE_SCHED is the only possible flag set
* on backlog.
* We can use a plain write instead of clear_bit(),
* and we dont need an smp_mb() memory barrier.
*/
napi->state = 0;
again = false;
} else {
skb_queue_splice_tail_init(&sd->input_pkt_queue,
&sd->process_queue);
}
rps_unlock(sd);
local_irq_enable();
}
return work;
}
Commit Message: tun: call dev_get_valid_name() before register_netdevice()
register_netdevice() could fail early when we have an invalid
dev name, in which case ->ndo_uninit() is not called. For tun
device, this is a problem because a timer etc. are already
initialized and it expects ->ndo_uninit() to clean them up.
We could move these initializations into a ->ndo_init() so
that register_netdevice() knows better, however this is still
complicated due to the logic in tun_detach().
Therefore, I choose to just call dev_get_valid_name() before
register_netdevice(), which is quicker and much easier to audit.
And for this specific case, it is already enough.
Fixes: 96442e42429e ("tuntap: choose the txq based on rxq")
Reported-by: Dmitry Alexeev <[email protected]>
Cc: Jason Wang <[email protected]>
Cc: "Michael S. Tsirkin" <[email protected]>
Signed-off-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[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: static bool TokenExitsSVG(const CompactHTMLToken& token) {
return DeprecatedEqualIgnoringCase(token.Data(),
SVGNames::foreignObjectTag.LocalName());
}
Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator.
HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML
integration point. This CL adds <annotation-xml>, <desc>, and SVG
<title>.
Bug: 805924
Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2
Reviewed-on: https://chromium-review.googlesource.com/964038
Commit-Queue: Kent Tamura <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#543634}
CWE ID: CWE-79
Target: 1
Example 2:
Code: static int valid_master_desc(const char *new_desc, const char *orig_desc)
{
if (!memcmp(new_desc, KEY_TRUSTED_PREFIX, KEY_TRUSTED_PREFIX_LEN)) {
if (strlen(new_desc) == KEY_TRUSTED_PREFIX_LEN)
goto out;
if (orig_desc)
if (memcmp(new_desc, orig_desc, KEY_TRUSTED_PREFIX_LEN))
goto out;
} else if (!memcmp(new_desc, KEY_USER_PREFIX, KEY_USER_PREFIX_LEN)) {
if (strlen(new_desc) == KEY_USER_PREFIX_LEN)
goto out;
if (orig_desc)
if (memcmp(new_desc, orig_desc, KEY_USER_PREFIX_LEN))
goto out;
} else
goto out;
return 0;
out:
return -EINVAL;
}
Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key
If a user key gets negatively instantiated, an error code is cached in the
payload area. A negatively instantiated key may be then be positively
instantiated by updating it with valid data. However, the ->update key
type method must be aware that the error code may be there.
The following may be used to trigger the bug in the user key type:
keyctl request2 user user "" @u
keyctl add user user "a" @u
which manifests itself as:
BUG: unable to handle kernel paging request at 00000000ffffff8a
IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
PGD 7cc30067 PUD 0
Oops: 0002 [#1] SMP
Modules linked in:
CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000
RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280
[<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046
RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246
RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001
RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82
RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000
R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82
R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700
FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b
CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0
Stack:
ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82
ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5
ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620
Call Trace:
[<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136
[<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129
[< inline >] __key_update security/keys/key.c:730
[<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908
[< inline >] SYSC_add_key security/keys/keyctl.c:125
[<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60
[<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185
Note the error code (-ENOKEY) in EDX.
A similar bug can be tripped by:
keyctl request2 trusted user "" @u
keyctl add trusted user "a" @u
This should also affect encrypted keys - but that has to be correctly
parameterised or it will fail with EINVAL before getting to the bit that
will crashes.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Mimi Zohar <[email protected]>
Signed-off-by: James Morris <[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: int dtls1_get_record(SSL *s)
{
int ssl_major,ssl_minor;
int i,n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr= &(s->s3->rrec);
/* The epoch may have changed. If so, process all the
* pending records. This is a non-blocking operation. */
dtls1_process_buffered_records(s);
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
again:
/* check if we have the header */
if ( (s->rstate != SSL_ST_READ_BODY) ||
(s->packet_length < DTLS1_RT_HEADER_LENGTH))
{
n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0) return(n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
{
s->packet_length = 0;
goto again;
}
s->rstate=SSL_ST_READ_BODY;
p=s->packet;
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type= *(p++);
ssl_major= *(p++);
ssl_minor= *(p++);
version=(ssl_major<<8)|ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p,rr->epoch);
memcpy(&(s->s3->read_sequence[2]), p, 6);
p+=6;
n2s(p,rr->length);
/* Lets check version */
if (!s->first_packet)
{
if (version != s->version)
{
/* unexpected version, silently discard */
rr->length = 0;
s->packet_length = 0;
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00))
{
/* wrong version, silently discard record */
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
{
/* record too long, silently discard it */
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now s->rstate == SSL_ST_READ_BODY */
}
/* s->rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
{
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i=rr->length;
n=ssl3_read_n(s,i,i,1);
/* this packet contained a partial record, dump it */
if ( n != i)
{
rr->length = 0;
s->packet_length = 0;
goto again;
}
/* now n == rr->length,
* and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
}
s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if ( bitmap == NULL)
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
{
#endif
/* Check whether this is a repeat, or aged record.
* Don't check if we're listening and this message is
* a ClientHello. They can look as if they're replayed,
* since they arrive from different connections and
* would be dropped unnecessarily.
*/
if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
s->packet_length > DTLS1_RT_HEADER_LENGTH &&
s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
!dtls1_record_replay_check(s, bitmap))
{
rr->length = 0;
s->packet_length=0; /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0) goto again;
/* If this record is from the next epoch (either HM or ALERT),
* and a handshake is currently in progress, buffer it since it
* cannot be processed at this time. However, do not buffer
* anything while listening.
*/
if (is_next_epoch)
{
if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen)
{
dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
}
rr->length = 0;
s->packet_length = 0;
goto again;
}
if (!dtls1_process_record(s))
{
rr->length = 0;
s->packet_length = 0; /* dump this record */
goto again; /* get another record */
}
return(1);
}
Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to
ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a
malloc failure, whilst the latter will fail if attempting to add a duplicate
record to the queue. This should never happen because duplicate records should
be detected and dropped before any attempt to add them to the queue.
Unfortunately records that arrive that are for the next epoch are not being
recorded correctly, and therefore replays are not being detected.
Additionally, these "should not happen" failures that can occur in
dtls1_buffer_record are not being treated as fatal and therefore an attacker
could exploit this by sending repeated replay records for the next epoch,
eventually causing a DoS through memory exhaustion.
Thanks to Chris Mueller for reporting this issue and providing initial
analysis and a patch. Further analysis and the final patch was performed by
Matt Caswell from the OpenSSL development team.
CVE-2015-0206
Reviewed-by: Dr Stephen Henson <[email protected]>
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: untrusted_launcher_response_callback (GtkDialog *dialog,
int response_id,
ActivateParametersDesktop *parameters)
{
GdkScreen *screen;
char *uri;
GFile *file;
switch (response_id)
{
case RESPONSE_RUN:
{
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
uri = nautilus_file_get_uri (parameters->file);
DEBUG ("Launching untrusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
break;
case RESPONSE_MARK_TRUSTED:
{
file = nautilus_file_get_location (parameters->file);
nautilus_file_mark_desktop_file_trusted (file,
parameters->parent_window,
TRUE,
NULL, NULL);
g_object_unref (file);
}
break;
default:
{
/* Just destroy dialog */
}
break;
}
gtk_widget_destroy (GTK_WIDGET (dialog));
activate_parameters_desktop_free (parameters);
}
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: 1
Example 2:
Code: int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
/* force to stop the timer */
snd_timer_stop(timeri);
timer = timeri->timer;
if (timer) {
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
/* remove slave links */
spin_lock_irq(&slave_active_lock);
spin_lock(&timer->lock);
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
list_del_init(&slave->ack_list);
list_del_init(&slave->active_list);
}
spin_unlock(&timer->lock);
spin_unlock_irq(&slave_active_lock);
/* slave doesn't need to release timer resources below */
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
timer = NULL;
}
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer) {
if (list_empty(&timer->open_list_head) && timer->hw.close)
timer->hw.close(timer);
/* release a card refcount for safe disconnection */
if (timer->card)
put_device(&timer->card->card_dev);
module_put(timer->module);
}
mutex_unlock(®ister_mutex);
return 0;
}
Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt
The stack object “r1” has a total size of 32 bytes. Its field
“event” and “val” both contain 4 bytes padding. These 8 bytes
padding bytes are sent to user without being initialized.
Signed-off-by: Kangjie Lu <[email protected]>
Signed-off-by: Takashi Iwai <[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: static NTSTATUS smb1cli_conn_dispatch_incoming(struct smbXcli_conn *conn,
TALLOC_CTX *tmp_mem,
uint8_t *inbuf)
{
struct tevent_req *req;
struct smbXcli_req_state *state;
NTSTATUS status;
size_t num_pending;
size_t i;
uint8_t cmd;
uint16_t mid;
bool oplock_break;
uint8_t *inhdr = inbuf + NBT_HDR_SIZE;
size_t len = smb_len_tcp(inbuf);
struct iovec *iov = NULL;
int num_iov = 0;
struct tevent_req **chain = NULL;
size_t num_chained = 0;
size_t num_responses = 0;
if (conn->smb1.read_braw_req != NULL) {
req = conn->smb1.read_braw_req;
conn->smb1.read_braw_req = NULL;
state = tevent_req_data(req, struct smbXcli_req_state);
smbXcli_req_unset_pending(req);
if (state->smb1.recv_iov == NULL) {
/*
* For requests with more than
* one response, we have to readd the
* recv_iov array.
*/
state->smb1.recv_iov = talloc_zero_array(state,
struct iovec,
3);
if (tevent_req_nomem(state->smb1.recv_iov, req)) {
return NT_STATUS_OK;
}
}
state->smb1.recv_iov[0].iov_base = (void *)(inhdr);
state->smb1.recv_iov[0].iov_len = len;
ZERO_STRUCT(state->smb1.recv_iov[1]);
ZERO_STRUCT(state->smb1.recv_iov[2]);
state->smb1.recv_cmd = SMBreadBraw;
state->smb1.recv_status = NT_STATUS_OK;
state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
tevent_req_done(req);
return NT_STATUS_OK;
}
if ((IVAL(inhdr, 0) != SMB_MAGIC) /* 0xFF"SMB" */
&& (SVAL(inhdr, 0) != 0x45ff)) /* 0xFF"E" */ {
DEBUG(10, ("Got non-SMB PDU\n"));
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
/*
* If we supported multiple encrytion contexts
* here we'd look up based on tid.
*/
if (common_encryption_on(conn->smb1.trans_enc)
&& (CVAL(inbuf, 0) == 0)) {
uint16_t enc_ctx_num;
status = get_enc_ctx_num(inbuf, &enc_ctx_num);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("get_enc_ctx_num returned %s\n",
nt_errstr(status)));
return status;
}
if (enc_ctx_num != conn->smb1.trans_enc->enc_ctx_num) {
DEBUG(10, ("wrong enc_ctx %d, expected %d\n",
enc_ctx_num,
conn->smb1.trans_enc->enc_ctx_num));
return NT_STATUS_INVALID_HANDLE;
}
status = common_decrypt_buffer(conn->smb1.trans_enc,
(char *)inbuf);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10, ("common_decrypt_buffer returned %s\n",
nt_errstr(status)));
return status;
}
inhdr = inbuf + NBT_HDR_SIZE;
len = smb_len_nbt(inbuf);
}
mid = SVAL(inhdr, HDR_MID);
num_pending = talloc_array_length(conn->pending);
for (i=0; i<num_pending; i++) {
if (mid == smb1cli_req_mid(conn->pending[i])) {
break;
}
}
if (i == num_pending) {
/* Dump unexpected reply */
return NT_STATUS_RETRY;
}
oplock_break = false;
if (mid == 0xffff) {
/*
* Paranoia checks that this is really an oplock break request.
*/
oplock_break = (len == 51); /* hdr + 8 words */
oplock_break &= ((CVAL(inhdr, HDR_FLG) & FLAG_REPLY) == 0);
oplock_break &= (CVAL(inhdr, HDR_COM) == SMBlockingX);
oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(6)) == 0);
oplock_break &= (SVAL(inhdr, HDR_VWV+VWV(7)) == 0);
if (!oplock_break) {
/* Dump unexpected reply */
return NT_STATUS_RETRY;
}
}
req = conn->pending[i];
state = tevent_req_data(req, struct smbXcli_req_state);
if (!oplock_break /* oplock breaks are not signed */
&& !smb_signing_check_pdu(conn->smb1.signing,
inhdr, len, state->smb1.seqnum+1)) {
DEBUG(10, ("cli_check_sign_mac failed\n"));
return NT_STATUS_ACCESS_DENIED;
}
status = smb1cli_inbuf_parse_chain(inbuf, tmp_mem,
&iov, &num_iov);
if (!NT_STATUS_IS_OK(status)) {
DEBUG(10,("smb1cli_inbuf_parse_chain - %s\n",
nt_errstr(status)));
return status;
}
cmd = CVAL(inhdr, HDR_COM);
status = smb1cli_pull_raw_error(inhdr);
if (NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_SESSION_EXPIRED) &&
(state->session != NULL) && state->session->disconnect_expired)
{
/*
* this should be a short term hack
* until the upper layers have implemented
* re-authentication.
*/
return status;
}
if (state->smb1.chained_requests == NULL) {
if (num_iov != 3) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
smbXcli_req_unset_pending(req);
if (state->smb1.recv_iov == NULL) {
/*
* For requests with more than
* one response, we have to readd the
* recv_iov array.
*/
state->smb1.recv_iov = talloc_zero_array(state,
struct iovec,
3);
if (tevent_req_nomem(state->smb1.recv_iov, req)) {
return NT_STATUS_OK;
}
}
state->smb1.recv_cmd = cmd;
state->smb1.recv_status = status;
state->inbuf = talloc_move(state->smb1.recv_iov, &inbuf);
state->smb1.recv_iov[0] = iov[0];
state->smb1.recv_iov[1] = iov[1];
state->smb1.recv_iov[2] = iov[2];
if (talloc_array_length(conn->pending) == 0) {
tevent_req_done(req);
return NT_STATUS_OK;
}
tevent_req_defer_callback(req, state->ev);
tevent_req_done(req);
return NT_STATUS_RETRY;
}
chain = talloc_move(tmp_mem, &state->smb1.chained_requests);
num_chained = talloc_array_length(chain);
num_responses = (num_iov - 1)/2;
if (num_responses > num_chained) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
for (i=0; i<num_chained; i++) {
size_t iov_idx = 1 + (i*2);
struct iovec *cur = &iov[iov_idx];
uint8_t *inbuf_ref;
req = chain[i];
state = tevent_req_data(req, struct smbXcli_req_state);
smbXcli_req_unset_pending(req);
/*
* as we finish multiple requests here
* we need to defer the callbacks as
* they could destroy our current stack state.
*/
tevent_req_defer_callback(req, state->ev);
if (i >= num_responses) {
tevent_req_nterror(req, NT_STATUS_REQUEST_ABORTED);
continue;
}
if (state->smb1.recv_iov == NULL) {
/*
* For requests with more than
* one response, we have to readd the
* recv_iov array.
*/
state->smb1.recv_iov = talloc_zero_array(state,
struct iovec,
3);
if (tevent_req_nomem(state->smb1.recv_iov, req)) {
continue;
}
}
state->smb1.recv_cmd = cmd;
if (i == (num_responses - 1)) {
/*
* The last request in the chain gets the status
*/
state->smb1.recv_status = status;
} else {
cmd = CVAL(cur[0].iov_base, 0);
state->smb1.recv_status = NT_STATUS_OK;
}
state->inbuf = inbuf;
/*
* Note: here we use talloc_reference() in a way
* that does not expose it to the caller.
*/
inbuf_ref = talloc_reference(state->smb1.recv_iov, inbuf);
if (tevent_req_nomem(inbuf_ref, req)) {
continue;
}
/* copy the related buffers */
state->smb1.recv_iov[0] = iov[0];
state->smb1.recv_iov[1] = cur[0];
state->smb1.recv_iov[2] = cur[1];
tevent_req_done(req);
}
return NT_STATUS_RETRY;
}
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 FrameSelection::DocumentAttached(Document* document) {
DCHECK(document);
use_secure_keyboard_entry_when_active_ = false;
selection_editor_->DocumentAttached(document);
SetContext(document);
}
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: 1
Example 2:
Code: static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
int nr_exclusive, int wake_flags, void *key)
{
wait_queue_t *curr, *next;
list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
unsigned flags = curr->flags;
if (curr->func(curr, mode, wake_flags, key) &&
(flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
break;
}
}
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: CastRtpStream* CastStreamingNativeHandler::GetRtpStreamOrThrow(
int transport_id) const {
RtpStreamMap::const_iterator iter = rtp_stream_map_.find(
transport_id);
if (iter != rtp_stream_map_.end())
return iter->second.get();
v8::Isolate* isolate = context()->v8_context()->GetIsolate();
isolate->ThrowException(v8::Exception::RangeError(v8::String::NewFromUtf8(
isolate, kRtpStreamNotFound)));
return NULL;
}
Commit Message: [Extensions] Add more bindings access checks
BUG=598165
Review URL: https://codereview.chromium.org/1854983002
Cr-Commit-Position: refs/heads/master@{#385282}
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: bool AXNodeObject::isPressed() const {
if (!isButton())
return false;
Node* node = this->getNode();
if (!node)
return false;
if (ariaRoleAttribute() == ToggleButtonRole) {
if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true") ||
equalIgnoringCase(getAttribute(aria_pressedAttr), "mixed"))
return true;
return false;
}
return node->isActive();
}
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: 1
Example 2:
Code: void RenderBox::setOverrideLogicalContentHeight(LayoutUnit height)
{
ASSERT(height >= 0);
ensureRareData().m_overrideLogicalContentHeight = height;
}
Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1)
Previously StyleDifference was an enum that proximately bigger values
imply smaller values (e.g. StyleDifferenceLayout implies
StyleDifferenceRepaint). This causes unnecessary repaints in some cases
on layout change.
Convert StyleDifference to a structure containing relatively independent
flags.
This change doesn't directly improve the result, but can make further
repaint optimizations possible.
Step 1 doesn't change any functionality. RenderStyle still generate the
legacy StyleDifference enum when comparing styles and convert the result
to the new StyleDifference. Implicit requirements are not handled during
the conversion.
Converted call sites to use the new StyleDifference according to the
following conversion rules:
- diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange()
- diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly()
- diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer()
- diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout()
- diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout()
- diff > StyleDifferenceRepaintLayer => diff.needsLayout()
- diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly()
- diff == StyleDifferenceLayout => diff.needsFullLayout()
BUG=358460
TEST=All existing layout tests.
[email protected], [email protected], [email protected]
Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983
Review URL: https://codereview.chromium.org/236203020
git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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 fixup_bug(struct pt_regs *regs, int trapnr)
{
if (trapnr != X86_TRAP_UD)
return 0;
switch (report_bug(regs->ip, regs)) {
case BUG_TRAP_TYPE_NONE:
case BUG_TRAP_TYPE_BUG:
break;
case BUG_TRAP_TYPE_WARN:
regs->ip += LEN_UD2;
return 1;
}
return 0;
}
Commit Message: x86/entry/64: Don't use IST entry for #BP stack
There's nothing IST-worthy about #BP/int3. We don't allow kprobes
in the small handful of places in the kernel that run at CPL0 with
an invalid stack, and 32-bit kernels have used normal interrupt
gates for #BP forever.
Furthermore, we don't allow kprobes in places that have usergs while
in kernel mode, so "paranoid" is also unnecessary.
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
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: PassRefPtr<DocumentFragment> Range::createDocumentFragmentForElement(const String& markup, Element* element, FragmentScriptingPermission scriptingPermission)
{
ASSERT(element);
HTMLElement* htmlElement = toHTMLElement(element);
if (htmlElement->ieForbidsInsertHTML())
return 0;
if (htmlElement->hasLocalName(colTag) || htmlElement->hasLocalName(colgroupTag) || htmlElement->hasLocalName(framesetTag)
|| htmlElement->hasLocalName(headTag) || htmlElement->hasLocalName(styleTag) || htmlElement->hasLocalName(titleTag))
return 0;
RefPtr<DocumentFragment> fragment = element->document()->createDocumentFragment();
if (element->document()->isHTMLDocument())
fragment->parseHTML(markup, element, scriptingPermission);
else if (!fragment->parseXML(markup, element, scriptingPermission))
return 0; // FIXME: We should propagate a syntax error exception out here.
RefPtr<Node> nextNode;
for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
nextNode = node->nextSibling();
if (node->hasTagName(htmlTag) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
HTMLElement* element = toHTMLElement(node.get());
if (Node* firstChild = element->firstChild())
nextNode = firstChild;
removeElementPreservingChildren(fragment, element);
}
}
return fragment.release();
}
Commit Message: There are too many poorly named functions to create a fragment from markup
https://bugs.webkit.org/show_bug.cgi?id=87339
Reviewed by Eric Seidel.
Source/WebCore:
Moved all functions that create a fragment from markup to markup.h/cpp.
There should be no behavioral change.
* dom/Range.cpp:
(WebCore::Range::createContextualFragment):
* dom/Range.h: Removed createDocumentFragmentForElement.
* dom/ShadowRoot.cpp:
(WebCore::ShadowRoot::setInnerHTML):
* editing/markup.cpp:
(WebCore::createFragmentFromMarkup):
(WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource.
(WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor.
(WebCore::removeElementPreservingChildren): Moved from Range.
(WebCore::createContextualFragment): Ditto.
* editing/markup.h:
* html/HTMLElement.cpp:
(WebCore::HTMLElement::setInnerHTML):
(WebCore::HTMLElement::setOuterHTML):
(WebCore::HTMLElement::insertAdjacentHTML):
* inspector/DOMPatchSupport.cpp:
(WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using
one of the functions listed in markup.h
* xml/XSLTProcessor.cpp:
(WebCore::XSLTProcessor::transformToFragment):
Source/WebKit/qt:
Replace calls to Range::createDocumentFragmentForElement by calls to
createContextualDocumentFragment.
* Api/qwebelement.cpp:
(QWebElement::appendInside):
(QWebElement::prependInside):
(QWebElement::prependOutside):
(QWebElement::appendOutside):
(QWebElement::encloseContentsWith):
(QWebElement::encloseWith):
git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int cm_alloc_id(struct cm_id_private *cm_id_priv)
{
unsigned long flags;
int id;
idr_preload(GFP_KERNEL);
spin_lock_irqsave(&cm.lock, flags);
id = idr_alloc_cyclic(&cm.local_id_table, cm_id_priv, 0, 0, GFP_NOWAIT);
spin_unlock_irqrestore(&cm.lock, flags);
idr_preload_end();
cm_id_priv->id.local_id = (__force __be32)id ^ cm.random_id_operand;
return id < 0 ? id : 0;
}
Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler
The code that resolves the passive side source MAC within the rdma_cm
connection request handler was both redundant and buggy, so remove it.
It was redundant since later, when an RC QP is modified to RTR state,
the resolution will take place in the ib_core module. It was buggy
because this callback also deals with UD SIDR exchange, for which we
incorrectly looked at the REQ member of the CM event and dereferenced
a random value.
Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures")
Signed-off-by: Moni Shoua <[email protected]>
Signed-off-by: Or Gerlitz <[email protected]>
Signed-off-by: Roland Dreier <[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: set_interface_var(const char *iface,
const char *var, const char *name,
uint32_t val)
{
FILE *fp;
char spath[64+IFNAMSIZ]; /* XXX: magic constant */
if (snprintf(spath, sizeof(spath), var, iface) >= sizeof(spath))
return -1;
if (access(spath, F_OK) != 0)
return -1;
fp = fopen(spath, "w");
if (!fp) {
if (name)
flog(LOG_ERR, "failed to set %s (%u) for %s: %s",
name, val, iface, strerror(errno));
return -1;
}
fprintf(fp, "%u", val);
fclose(fp);
return 0;
}
Commit Message: set_interface_var() doesn't check interface name and blindly does
fopen(path "/" ifname, "w") on it. As "ifname" is an untrusted input, it
should be checked for ".." and/or "/" in it. Otherwise, an infected
unprivileged daemon may overwrite contents of file named "mtu",
"hoplimit", etc. in arbitrary location with arbitrary 32-bit value in
decimal representation ("%d"). If an attacker has a local account or
may create arbitrary symlinks with these names in any location (e.g.
/tmp), any file may be overwritten with a decimal value.
CWE ID: CWE-22
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: read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss,
struct _7z_folder *f, size_t numFolders)
{
const unsigned char *p;
uint64_t *usizes;
size_t unpack_streams;
int type;
unsigned i;
uint32_t numDigests;
memset(ss, 0, sizeof(*ss));
for (i = 0; i < numFolders; i++)
f[i].numUnpackStreams = 1;
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
if (type == kNumUnPackStream) {
unpack_streams = 0;
for (i = 0; i < numFolders; i++) {
if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0)
return (-1);
if (UMAX_ENTRY < f[i].numUnpackStreams)
return (-1);
unpack_streams += (size_t)f[i].numUnpackStreams;
}
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
} else
unpack_streams = numFolders;
ss->unpack_streams = unpack_streams;
if (unpack_streams) {
ss->unpackSizes = calloc(unpack_streams,
sizeof(*ss->unpackSizes));
ss->digestsDefined = calloc(unpack_streams,
sizeof(*ss->digestsDefined));
ss->digests = calloc(unpack_streams,
sizeof(*ss->digests));
if (ss->unpackSizes == NULL || ss->digestsDefined == NULL ||
ss->digests == NULL)
return (-1);
}
usizes = ss->unpackSizes;
for (i = 0; i < numFolders; i++) {
unsigned pack;
uint64_t sum;
if (f[i].numUnpackStreams == 0)
continue;
sum = 0;
if (type == kSize) {
for (pack = 1; pack < f[i].numUnpackStreams; pack++) {
if (parse_7zip_uint64(a, usizes) < 0)
return (-1);
sum += *usizes++;
}
}
*usizes++ = folder_uncompressed_size(&f[i]) - sum;
}
if (type == kSize) {
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
}
for (i = 0; i < unpack_streams; i++) {
ss->digestsDefined[i] = 0;
ss->digests[i] = 0;
}
numDigests = 0;
for (i = 0; i < numFolders; i++) {
if (f[i].numUnpackStreams != 1 || !f[i].digest_defined)
numDigests += (uint32_t)f[i].numUnpackStreams;
}
if (type == kCRC) {
struct _7z_digests tmpDigests;
unsigned char *digestsDefined = ss->digestsDefined;
uint32_t * digests = ss->digests;
int di = 0;
memset(&tmpDigests, 0, sizeof(tmpDigests));
if (read_Digests(a, &(tmpDigests), numDigests) < 0) {
free_Digest(&tmpDigests);
return (-1);
}
for (i = 0; i < numFolders; i++) {
if (f[i].numUnpackStreams == 1 && f[i].digest_defined) {
*digestsDefined++ = 1;
*digests++ = f[i].digest;
} else {
unsigned j;
for (j = 0; j < f[i].numUnpackStreams;
j++, di++) {
*digestsDefined++ =
tmpDigests.defineds[di];
*digests++ =
tmpDigests.digests[di];
}
}
}
free_Digest(&tmpDigests);
if ((p = header_bytes(a, 1)) == NULL)
return (-1);
type = *p;
}
/*
* Must be kEnd.
*/
if (type != kEnd)
return (-1);
return (0);
}
Commit Message: Issue #718: Fix TALOS-CAN-152
If a 7-Zip archive declares a rediculously large number of substreams,
it can overflow an internal counter, leading a subsequent memory
allocation to be too small for the substream data.
Thanks to the Open Source and Threat Intelligence project at Cisco
for reporting this issue.
CWE ID: CWE-190
Target: 1
Example 2:
Code: void Resource::FinishPendingClients() {
HeapVector<Member<ResourceClient>> clients_to_notify;
CopyToVector(clients_awaiting_callback_, clients_to_notify);
for (const auto& client : clients_to_notify) {
if (!clients_awaiting_callback_.erase(client))
continue;
clients_.insert(client);
if (!is_revalidating_)
DidAddClient(client);
}
bool scheduled = async_finish_pending_clients_task_.IsActive();
if (scheduled && clients_awaiting_callback_.IsEmpty())
async_finish_pending_clients_task_.Cancel();
DCHECK(clients_awaiting_callback_.IsEmpty() || scheduled);
}
Commit Message: Check CORS using PassesAccessControlCheck() with supplied SecurityOrigin
Partial revert of https://chromium-review.googlesource.com/535694.
Bug: 799477
Change-Id: I878bb9bcb83afaafe8601293db9aa644fc5929b3
Reviewed-on: https://chromium-review.googlesource.com/898427
Commit-Queue: Hiroshige Hayashizaki <[email protected]>
Reviewed-by: Kouhei Ueno <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Takeshi Yoshino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#535176}
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: blink::WebMediaPlayer* RenderFrameImpl::createMediaPlayer(
blink::WebLocalFrame* frame,
const blink::WebURL& url,
blink::WebMediaPlayerClient* client) {
WebMediaPlayer* player = CreateWebMediaPlayerForMediaStream(url, client);
if (player)
return player;
#if defined(OS_ANDROID)
return CreateAndroidWebMediaPlayer(url, client);
#else
WebMediaPlayerParams params(
base::Bind(&ContentRendererClient::DeferMediaLoad,
base::Unretained(GetContentClient()->renderer()),
static_cast<RenderFrame*>(this)),
RenderThreadImpl::current()->GetAudioRendererMixerManager()->CreateInput(
render_view_->routing_id_, routing_id_));
return new WebMediaPlayerImpl(frame, client, weak_factory_.GetWeakPtr(),
params);
#endif // defined(OS_ANDROID)
}
Commit Message: Add logging to figure out which IPC we're failing to deserialize in RenderFrame.
BUG=369553
[email protected]
Review URL: https://codereview.chromium.org/263833020
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268565 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: int main(int argc, char **argv)
{
int i, n_valid, do_write, do_scrub;
char *c, *dname, *name;
DIR *dir;
FILE *fp;
pdf_t *pdf;
pdf_flag_t flags;
if (argc < 2)
usage();
/* Args */
do_write = do_scrub = flags = 0;
name = NULL;
for (i=1; i<argc; i++)
{
if (strncmp(argv[i], "-w", 2) == 0)
do_write = 1;
else if (strncmp(argv[i], "-i", 2) == 0)
flags |= PDF_FLAG_DISP_CREATOR;
else if (strncmp(argv[i], "-q", 2) == 0)
flags |= PDF_FLAG_QUIET;
else if (strncmp(argv[i], "-s", 2) == 0)
do_scrub = 1;
else if (argv[i][0] != '-')
name = argv[i];
else if (argv[i][0] == '-')
usage();
}
if (!name)
usage();
if (!(fp = fopen(name, "r")))
{
ERR("Could not open file '%s'\n", argv[1]);
return -1;
}
else if (!pdf_is_pdf(fp))
{
ERR("'%s' specified is not a valid PDF\n", name);
fclose(fp);
return -1;
}
/* Load PDF */
if (!(pdf = init_pdf(fp, name)))
{
fclose(fp);
return -1;
}
/* Count valid xrefs */
for (i=0, n_valid=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
++n_valid;
/* Bail if we only have 1 valid */
if (n_valid < 2)
{
if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR)))
printf("%s: There is only one version of this PDF\n", pdf->name);
if (do_write)
{
fclose(fp);
pdf_delete(pdf);
return 0;
}
}
dname = NULL;
if (do_write)
{
/* Create directory to place the various versions in */
if ((c = strrchr(name, '/')))
name = c + 1;
if ((c = strrchr(name, '.')))
*c = '\0';
dname = malloc(strlen(name) + 16);
sprintf(dname, "%s-versions", name);
if (!(dir = opendir(dname)))
mkdir(dname, S_IRWXU);
else
{
ERR("This directory already exists, PDF version extraction will "
"not occur.\n");
fclose(fp);
closedir(dir);
free(dname);
pdf_delete(pdf);
return -1;
}
/* Write the pdf as a pervious version */
for (i=0; i<pdf->n_xrefs; i++)
if (pdf->xrefs[i].version)
write_version(fp, name, dname, &pdf->xrefs[i]);
}
/* Generate a per-object summary */
pdf_summarize(fp, pdf, dname, flags);
/* Have we been summoned to scrub history from this PDF */
if (do_scrub)
scrub_document(fp, pdf);
/* Display extra information */
if (flags & PDF_FLAG_DISP_CREATOR)
display_creator(fp, pdf);
fclose(fp);
free(dname);
pdf_delete(pdf);
return 0;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787
Target: 1
Example 2:
Code: void InFlightBackendIO::DoomEntryImpl(EntryImpl* entry) {
scoped_refptr<BackendIO> operation(
new BackendIO(this, backend_, net::CompletionCallback()));
operation->DoomEntryImpl(entry);
PostOperation(FROM_HERE, operation.get());
}
Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem
Thanks to nedwilliamson@ (on gmail) for an alternative perspective
plus a reduction to make fixing this much easier.
Bug: 826626, 518908, 537063, 802886
Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f
Reviewed-on: https://chromium-review.googlesource.com/985052
Reviewed-by: Matt Menke <[email protected]>
Commit-Queue: Maks Orlovich <[email protected]>
Cr-Commit-Position: refs/heads/master@{#547103}
CWE ID: CWE-20
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 __dwc3_gadget_kick_transfer(struct dwc3_ep *dep)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3_request *req;
int starting;
int ret;
u32 cmd;
if (!dwc3_calc_trbs_left(dep))
return 0;
starting = !(dep->flags & DWC3_EP_BUSY);
dwc3_prepare_trbs(dep);
req = next_request(&dep->started_list);
if (!req) {
dep->flags |= DWC3_EP_PENDING_REQUEST;
return 0;
}
memset(¶ms, 0, sizeof(params));
if (starting) {
params.param0 = upper_32_bits(req->trb_dma);
params.param1 = lower_32_bits(req->trb_dma);
cmd = DWC3_DEPCMD_STARTTRANSFER;
if (usb_endpoint_xfer_isoc(dep->endpoint.desc))
cmd |= DWC3_DEPCMD_PARAM(dep->frame_number);
} else {
cmd = DWC3_DEPCMD_UPDATETRANSFER |
DWC3_DEPCMD_PARAM(dep->resource_index);
}
ret = dwc3_send_gadget_ep_cmd(dep, cmd, ¶ms);
if (ret < 0) {
/*
* FIXME we need to iterate over the list of requests
* here and stop, unmap, free and del each of the linked
* requests instead of what we do now.
*/
if (req->trb)
memset(req->trb, 0, sizeof(struct dwc3_trb));
dep->queued_requests--;
dwc3_gadget_giveback(dep, req, ret);
return ret;
}
dep->flags |= DWC3_EP_BUSY;
if (starting) {
dep->resource_index = dwc3_gadget_ep_get_transfer_index(dep);
WARN_ON_ONCE(!dep->resource_index);
}
return 0;
}
Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue()
This is a requirement which has always existed but, somehow, wasn't
reflected in the documentation and problems weren't found until now
when Tuba Yavuz found a possible deadlock happening between dwc3 and
f_hid. She described the situation as follows:
spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire
/* we our function has been disabled by host */
if (!hidg->req) {
free_ep_req(hidg->in_ep, hidg->req);
goto try_again;
}
[...]
status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
=>
[...]
=> usb_gadget_giveback_request
=>
f_hidg_req_complete
=>
spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire
Note that this happens because dwc3 would call ->complete() on a
failed usb_ep_queue() due to failed Start Transfer command. This is,
anyway, a theoretical situation because dwc3 currently uses "No
Response Update Transfer" command for Bulk and Interrupt endpoints.
It's still good to make this case impossible to happen even if the "No
Reponse Update Transfer" command is changed.
Reported-by: Tuba Yavuz <[email protected]>
Signed-off-by: Felipe Balbi <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-189
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: lmp_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lmp_common_header *lmp_com_header;
const struct lmp_object_header *lmp_obj_header;
const u_char *tptr,*obj_tptr;
int tlen,lmp_obj_len,lmp_obj_ctype,obj_tlen;
int hexdump;
int offset,subobj_type,subobj_len,total_subobj_len;
int link_type;
union { /* int to float conversion buffer */
float f;
uint32_t i;
} bw;
tptr=pptr;
lmp_com_header = (const struct lmp_common_header *)pptr;
ND_TCHECK(*lmp_com_header);
/*
* Sanity checking of the header.
*/
if (LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]) != LMP_VERSION) {
ND_PRINT((ndo, "LMP version %u packet not supported",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LMPv%u %s Message, length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown (%u)",lmp_com_header->msg_type),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=EXTRACT_16BITS(lmp_com_header->length);
ND_PRINT((ndo, "\n\tLMPv%u, msg-type: %s, Flags: [%s], length: %u",
LMP_EXTRACT_VERSION(lmp_com_header->version_res[0]),
tok2str(lmp_msg_type_values, "unknown, type: %u",lmp_com_header->msg_type),
bittok2str(lmp_header_flag_values,"none",lmp_com_header->flags),
tlen));
tptr+=sizeof(const struct lmp_common_header);
tlen-=sizeof(const struct lmp_common_header);
while(tlen>0) {
/* did we capture enough for fully decoding the object header ? */
ND_TCHECK2(*tptr, sizeof(struct lmp_object_header));
lmp_obj_header = (const struct lmp_object_header *)tptr;
lmp_obj_len=EXTRACT_16BITS(lmp_obj_header->length);
lmp_obj_ctype=(lmp_obj_header->ctype)&0x7f;
if(lmp_obj_len % 4 || lmp_obj_len < 4)
return;
ND_PRINT((ndo, "\n\t %s Object (%u), Class-Type: %s (%u) Flags: [%snegotiable], length: %u",
tok2str(lmp_obj_values,
"Unknown",
lmp_obj_header->class_num),
lmp_obj_header->class_num,
tok2str(lmp_ctype_values,
"Unknown",
((lmp_obj_header->class_num)<<8)+lmp_obj_ctype),
lmp_obj_ctype,
(lmp_obj_header->ctype)&0x80 ? "" : "non-",
lmp_obj_len));
obj_tptr=tptr+sizeof(struct lmp_object_header);
obj_tlen=lmp_obj_len-sizeof(struct lmp_object_header);
/* did we capture enough for fully decoding the object ? */
ND_TCHECK2(*tptr, lmp_obj_len);
hexdump=FALSE;
switch(lmp_obj_header->class_num) {
case LMP_OBJ_CC_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
ND_PRINT((ndo, "\n\t Control Channel ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_LINK_ID:
case LMP_OBJ_INTERFACE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4_LOC:
case LMP_CTYPE_IPV4_RMT:
ND_PRINT((ndo, "\n\t IPv4 Link ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_IPV6_LOC:
case LMP_CTYPE_IPV6_RMT:
ND_PRINT((ndo, "\n\t IPv6 Link ID: %s (0x%08x)",
ip6addr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_UNMD_LOC:
case LMP_CTYPE_UNMD_RMT:
ND_PRINT((ndo, "\n\t Link ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_MESSAGE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Message ID: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
case LMP_CTYPE_2:
ND_PRINT((ndo, "\n\t Message ID Ack: %u (0x%08x)",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_NODE_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_LOC:
case LMP_CTYPE_RMT:
ND_PRINT((ndo, "\n\t Node ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr),
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CONFIG:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO_CONFIG:
ND_PRINT((ndo, "\n\t Hello Interval: %u\n\t Hello Dead Interval: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_HELLO:
switch(lmp_obj_ctype) {
case LMP_CTYPE_HELLO:
ND_PRINT((ndo, "\n\t Tx Seq: %u, Rx Seq: %u",
EXTRACT_32BITS(obj_tptr),
EXTRACT_32BITS(obj_tptr+4)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_TE_LINK:
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_te_link_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
ND_PRINT((ndo, "\n\t Local Link-ID: %s (0x%08x)"
"\n\t Remote Link-ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
break;
case LMP_CTYPE_IPV6:
case LMP_CTYPE_UNMD:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_DATA_LINK:
ND_PRINT((ndo, "\n\t Flags: [%s]",
bittok2str(lmp_obj_data_link_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)"
"\n\t Remote Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+4),
EXTRACT_32BITS(obj_tptr+4),
ipaddr_string(ndo, obj_tptr+8),
EXTRACT_32BITS(obj_tptr+8)));
total_subobj_len = lmp_obj_len - 16;
offset = 12;
while (total_subobj_len > 0 && hexdump == FALSE ) {
subobj_type = EXTRACT_16BITS(obj_tptr+offset)>>8;
subobj_len = EXTRACT_16BITS(obj_tptr+offset)&0x00FF;
ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u",
tok2str(lmp_data_link_subobj,
"Unknown",
subobj_type),
subobj_type,
subobj_len));
switch(subobj_type) {
case INT_SWITCHING_TYPE_SUBOBJ:
ND_PRINT((ndo, "\n\t Switching Type: %s (%u)",
tok2str(gmpls_switch_cap_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+offset+2)>>8),
EXTRACT_16BITS(obj_tptr+offset+2)>>8));
ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)",
tok2str(gmpls_encoding_values,
"Unknown",
EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF),
EXTRACT_16BITS(obj_tptr+offset+2)&0x00FF));
bw.i = EXTRACT_32BITS(obj_tptr+offset+4);
ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
bw.i = EXTRACT_32BITS(obj_tptr+offset+8);
ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case WAVELENGTH_SUBOBJ:
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+offset+4)));
break;
default:
/* Any Unknown Subobject ==> Exit loop */
hexdump=TRUE;
break;
}
total_subobj_len-=subobj_len;
offset+=subobj_len;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_begin_verify_flag_values,
"none",
EXTRACT_16BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t Verify Interval: %u",
EXTRACT_16BITS(obj_tptr+2)));
ND_PRINT((ndo, "\n\t Data links: %u",
EXTRACT_32BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Encoding type: %s",
tok2str(gmpls_encoding_values, "Unknown", *(obj_tptr+8))));
ND_PRINT((ndo, "\n\t Verify Transport Mechanism: %u (0x%x)%s",
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10),
EXTRACT_16BITS(obj_tptr+10)&8000 ? " (Payload test messages capable)" : ""));
bw.i = EXTRACT_32BITS(obj_tptr+12);
ND_PRINT((ndo, "\n\t Transmission Rate: %.3f Mbps",bw.f*8/1000000));
ND_PRINT((ndo, "\n\t Wavelength: %u",
EXTRACT_32BITS(obj_tptr+16)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_BEGIN_ACK:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Verify Dead Interval: %u"
"\n\t Verify Transport Response: %u",
EXTRACT_16BITS(obj_tptr),
EXTRACT_16BITS(obj_tptr+2)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_VERIFY_ID:
switch(lmp_obj_ctype) {
case LMP_CTYPE_1:
ND_PRINT((ndo, "\n\t Verify ID: %u",
EXTRACT_32BITS(obj_tptr)));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
offset = 0;
/* Decode pairs: <Interface_ID (4 bytes), Channel_status (4 bytes)> */
while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
ND_PRINT((ndo, "\n\t\t Active: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>31) ?
"Allocated" : "Non-allocated",
(EXTRACT_32BITS(obj_tptr+offset+4)>>31)));
ND_PRINT((ndo, "\n\t\t Direction: %s (%u)", (EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1 ?
"Transmit" : "Receive",
(EXTRACT_32BITS(obj_tptr+offset+4)>>30)&0x1));
ND_PRINT((ndo, "\n\t\t Channel Status: %s (%u)",
tok2str(lmp_obj_channel_status_values,
"Unknown",
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF),
EXTRACT_32BITS(obj_tptr+offset+4)&0x3FFFFFF));
offset+=8;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_CHANNEL_STATUS_REQ:
switch(lmp_obj_ctype) {
case LMP_CTYPE_IPV4:
case LMP_CTYPE_UNMD:
offset = 0;
while (offset < (lmp_obj_len-(int)sizeof(struct lmp_object_header)) ) {
ND_PRINT((ndo, "\n\t Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+offset),
EXTRACT_32BITS(obj_tptr+offset)));
offset+=4;
}
break;
case LMP_CTYPE_IPV6:
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_ERROR_CODE:
switch(lmp_obj_ctype) {
case LMP_CTYPE_BEGIN_VERIFY_ERROR:
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_begin_verify_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
case LMP_CTYPE_LINK_SUMMARY_ERROR:
ND_PRINT((ndo, "\n\t Error Code: %s",
bittok2str(lmp_obj_link_summary_error_values,
"none",
EXTRACT_32BITS(obj_tptr))));
break;
default:
hexdump=TRUE;
}
break;
case LMP_OBJ_SERVICE_CONFIG:
switch (lmp_obj_ctype) {
case LMP_CTYPE_SERVICE_CONFIG_SP:
ND_PRINT((ndo, "\n\t Flags: %s",
bittok2str(lmp_obj_service_config_sp_flag_values,
"none",
EXTRACT_16BITS(obj_tptr)>>8)));
ND_PRINT((ndo, "\n\t UNI Version: %u",
EXTRACT_16BITS(obj_tptr) & 0x00FF));
break;
case LMP_CTYPE_SERVICE_CONFIG_CPSA:
link_type = EXTRACT_16BITS(obj_tptr)>>8;
ND_PRINT((ndo, "\n\t Link Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_link_type_values,
"Unknown", link_type),
link_type));
if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SDH) {
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sdh_values,
"Unknown",
EXTRACT_16BITS(obj_tptr) & 0x00FF),
EXTRACT_16BITS(obj_tptr) & 0x00FF));
}
if (link_type == LMP_SD_SERVICE_CONFIG_CPSA_LINK_TYPE_SONET) {
ND_PRINT((ndo, "\n\t Signal Type: %s (%u)",
tok2str(lmp_sd_service_config_cpsa_signal_type_sonet_values,
"Unknown",
EXTRACT_16BITS(obj_tptr) & 0x00FF),
EXTRACT_16BITS(obj_tptr) & 0x00FF));
}
ND_PRINT((ndo, "\n\t Transparency: %s",
bittok2str(lmp_obj_service_config_cpsa_tp_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2)>>8)));
ND_PRINT((ndo, "\n\t Contiguous Concatenation Types: %s",
bittok2str(lmp_obj_service_config_cpsa_cct_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2)>>8 & 0x00FF)));
ND_PRINT((ndo, "\n\t Minimum NCC: %u",
EXTRACT_16BITS(obj_tptr+4)));
ND_PRINT((ndo, "\n\t Maximum NCC: %u",
EXTRACT_16BITS(obj_tptr+6)));
ND_PRINT((ndo, "\n\t Minimum NVC:%u",
EXTRACT_16BITS(obj_tptr+8)));
ND_PRINT((ndo, "\n\t Maximum NVC:%u",
EXTRACT_16BITS(obj_tptr+10)));
ND_PRINT((ndo, "\n\t Local Interface ID: %s (0x%08x)",
ipaddr_string(ndo, obj_tptr+12),
EXTRACT_32BITS(obj_tptr+12)));
break;
case LMP_CTYPE_SERVICE_CONFIG_TRANSPARENCY_TCM:
ND_PRINT((ndo, "\n\t Transparency Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_transparency_flag_values,
"none",
EXTRACT_32BITS(obj_tptr))));
ND_PRINT((ndo, "\n\t TCM Monitoring Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_tcm_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+6) & 0x00FF)));
break;
case LMP_CTYPE_SERVICE_CONFIG_NETWORK_DIVERSITY:
ND_PRINT((ndo, "\n\t Diversity: Flags: %s",
bittok2str(
lmp_obj_service_config_nsa_network_diversity_flag_values,
"none",
EXTRACT_16BITS(obj_tptr+2) & 0x00FF)));
break;
default:
hexdump = TRUE;
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,obj_tptr,"\n\t ",obj_tlen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag > 1 || hexdump==TRUE)
print_unknown_data(ndo,tptr+sizeof(struct lmp_object_header),"\n\t ",
lmp_obj_len-sizeof(struct lmp_object_header));
tptr+=lmp_obj_len;
tlen-=lmp_obj_len;
}
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
}
Commit Message: CVE-2017-13003/Clean up the LMP dissector.
Do a lot more bounds and length checks.
Add a EXTRACT_8BITS() macro, for completeness, and so as not to confuse
people into thinking that, to fetch a 1-byte value from a packet, they
need to use EXTRACT_16BITS() to fetch a 2-byte value and then use
shifting and masking to extract the desired byte. Use that rather than
using EXTRACT_16BITS() to fetch a 2-byte value and then shifting and
masking to extract the desired byte.
Don't treat IPv4 addresses and unnumbered interface IDs the same; the
first should be printed as an IPv4 address but the latter should just be
printed as numbers. Handle IPv6 addresses in more object types while
we're at it.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125
Target: 1
Example 2:
Code: void Browser::TabStripEmpty() {
MessageLoop::current()->PostTask(
FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr()));
}
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: static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
/* if img->y0 is odd, then first line shall use Cb/Cr = 0 */
offy = img->y0 & 1U;
loopmaxh = maxh - offy;
if (offy > 0U) {
size_t j;
for(j=0; j < maxw; ++j)
{
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
}
for(i=0U; i < (loopmaxh & ~(size_t)1U); i += 2U)
{
size_t j;
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
}
for(j=0; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < loopmaxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < loopmaxh)
{
size_t j;
for(j=0U; j < (maxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc420_to_rgb() */
Commit Message: Fix Heap Buffer Overflow in function color_cmyk_to_rgb
Fix uclouvain/openjpeg#774
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: FT_Stream_EnterFrame( FT_Stream stream,
FT_ULong count )
{
FT_Error error = FT_Err_Ok;
FT_ULong read_bytes;
/* check for nested frame access */
FT_ASSERT( stream && stream->cursor == 0 );
if ( stream->read )
{
/* allocate the frame in memory */
FT_Memory memory = stream->memory;
/* simple sanity check */
if ( count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" frame size (%lu) larger than stream size (%lu)\n",
count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
#ifdef FT_DEBUG_MEMORY
/* assume _ft_debug_file and _ft_debug_lineno are already set */
stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error );
if ( error )
goto Exit;
#else
if ( FT_QALLOC( stream->base, count ) )
goto Exit;
#endif
/* read it */
read_bytes = stream->read( stream, stream->pos,
stream->base, count );
if ( read_bytes < count )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid read; expected %lu bytes, got %lu\n",
count, read_bytes ));
FT_FREE( stream->base );
error = FT_Err_Invalid_Stream_Operation;
}
stream->cursor = stream->base;
stream->limit = stream->cursor + count;
stream->pos += read_bytes;
}
else
{
/* check current and new position */
if ( stream->pos >= stream->size ||
stream->pos + count > stream->size )
{
FT_ERROR(( "FT_Stream_EnterFrame:"
" invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n",
stream->pos, count, stream->size ));
error = FT_Err_Invalid_Stream_Operation;
goto Exit;
}
/* set cursor */
stream->cursor = stream->base + stream->pos;
stream->limit = stream->cursor + count;
stream->pos += count;
}
Exit:
return error;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnStart(
content::NavigationHandle* navigation_handle,
const GURL& currently_committed_url,
bool started_in_foreground) {
if (!started_in_foreground) {
was_hidden_ = true;
return CONTINUE_OBSERVING;
}
effective_connection_type_ =
network_quality_tracker_->GetEffectiveConnectionType();
http_rtt_estimate_ = network_quality_tracker_->GetHttpRTT();
transport_rtt_estimate_ = network_quality_tracker_->GetTransportRTT();
downstream_kbps_estimate_ =
network_quality_tracker_->GetDownstreamThroughputKbps();
page_transition_ = navigation_handle->GetPageTransition();
return CONTINUE_OBSERVING;
}
Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation.
Also refactor UkmPageLoadMetricsObserver to use this new boolean to
report the user initiated metric in RecordPageLoadExtraInfoMetrics, so
that it works correctly in the case when the page load failed.
Bug: 925104
Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff
Reviewed-on: https://chromium-review.googlesource.com/c/1450460
Commit-Queue: Annie Sullivan <[email protected]>
Reviewed-by: Bryan McQuade <[email protected]>
Cr-Commit-Position: refs/heads/master@{#630870}
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: application_unhandled_file_install (GtkDialog *dialog,
gint response_id,
ActivateParametersInstall *parameters_install)
{
char *mime_type;
gtk_widget_destroy (GTK_WIDGET (dialog));
parameters_install->dialog = NULL;
if (response_id == GTK_RESPONSE_YES)
{
mime_type = nautilus_file_get_mime_type (parameters_install->file);
search_for_application_mime_type (parameters_install, mime_type);
g_free (mime_type);
}
else
{
/* free as we're not going to get the async dbus callback */
activate_parameters_install_free (parameters_install);
}
}
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
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 http_end_txn_clean_session(struct session *s)
{
int prev_status = s->txn.status;
/* FIXME: We need a more portable way of releasing a backend's and a
* server's connections. We need a safer way to reinitialize buffer
* flags. We also need a more accurate method for computing per-request
* data.
*/
/* unless we're doing keep-alive, we want to quickly close the connection
* to the server.
*/
if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
!si_conn_ready(s->req->cons)) {
s->req->cons->flags |= SI_FL_NOLINGER | SI_FL_NOHALF;
si_shutr(s->req->cons);
si_shutw(s->req->cons);
}
if (s->flags & SN_BE_ASSIGNED) {
s->be->beconn--;
if (unlikely(s->srv_conn))
sess_change_server(s, NULL);
}
s->logs.t_close = tv_ms_elapsed(&s->logs.tv_accept, &now);
session_process_counters(s);
if (s->txn.status) {
int n;
n = s->txn.status / 100;
if (n < 1 || n > 5)
n = 0;
if (s->fe->mode == PR_MODE_HTTP) {
s->fe->fe_counters.p.http.rsp[n]++;
if (s->comp_algo && (s->flags & SN_COMP_READY))
s->fe->fe_counters.p.http.comp_rsp++;
}
if ((s->flags & SN_BE_ASSIGNED) &&
(s->be->mode == PR_MODE_HTTP)) {
s->be->be_counters.p.http.rsp[n]++;
s->be->be_counters.p.http.cum_req++;
if (s->comp_algo && (s->flags & SN_COMP_READY))
s->be->be_counters.p.http.comp_rsp++;
}
}
/* don't count other requests' data */
s->logs.bytes_in -= s->req->buf->i;
s->logs.bytes_out -= s->rep->buf->i;
/* let's do a final log if we need it */
if (!LIST_ISEMPTY(&s->fe->logformat) && s->logs.logwait &&
!(s->flags & SN_MONITOR) &&
(!(s->fe->options & PR_O_NULLNOLOG) || s->req->total)) {
s->do_log(s);
}
/* stop tracking content-based counters */
session_stop_content_counters(s);
session_update_time_stats(s);
s->logs.accept_date = date; /* user-visible date for logging */
s->logs.tv_accept = now; /* corrected date for internal use */
tv_zero(&s->logs.tv_request);
s->logs.t_queue = -1;
s->logs.t_connect = -1;
s->logs.t_data = -1;
s->logs.t_close = 0;
s->logs.prx_queue_size = 0; /* we get the number of pending conns before us */
s->logs.srv_queue_size = 0; /* we will get this number soon */
s->logs.bytes_in = s->req->total = s->req->buf->i;
s->logs.bytes_out = s->rep->total = s->rep->buf->i;
if (s->pend_pos)
pendconn_free(s->pend_pos);
if (objt_server(s->target)) {
if (s->flags & SN_CURR_SESS) {
s->flags &= ~SN_CURR_SESS;
objt_server(s->target)->cur_sess--;
}
if (may_dequeue_tasks(objt_server(s->target), s->be))
process_srv_queue(objt_server(s->target));
}
s->target = NULL;
/* only release our endpoint if we don't intend to reuse the
* connection.
*/
if (((s->txn.flags & TX_CON_WANT_MSK) != TX_CON_WANT_KAL) ||
!si_conn_ready(s->req->cons)) {
si_release_endpoint(s->req->cons);
}
s->req->cons->state = s->req->cons->prev_state = SI_ST_INI;
s->req->cons->err_type = SI_ET_NONE;
s->req->cons->conn_retries = 0; /* used for logging too */
s->req->cons->exp = TICK_ETERNITY;
s->req->cons->flags &= SI_FL_DONT_WAKE; /* we're in the context of process_session */
s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT);
s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT);
s->flags &= ~(SN_DIRECT|SN_ASSIGNED|SN_ADDR_SET|SN_BE_ASSIGNED|SN_FORCE_PRST|SN_IGNORE_PRST);
s->flags &= ~(SN_CURR_SESS|SN_REDIRECTABLE|SN_SRV_REUSED);
s->txn.meth = 0;
http_reset_txn(s);
s->txn.flags |= TX_NOT_FIRST | TX_WAIT_NEXT_RQ;
if (prev_status == 401 || prev_status == 407) {
/* In HTTP keep-alive mode, if we receive a 401, we still have
* a chance of being able to send the visitor again to the same
* server over the same connection. This is required by some
* broken protocols such as NTLM, and anyway whenever there is
* an opportunity for sending the challenge to the proper place,
* it's better to do it (at least it helps with debugging).
*/
s->txn.flags |= TX_PREFER_LAST;
}
if (s->fe->options2 & PR_O2_INDEPSTR)
s->req->cons->flags |= SI_FL_INDEP_STR;
if (s->fe->options2 & PR_O2_NODELAY) {
s->req->flags |= CF_NEVER_WAIT;
s->rep->flags |= CF_NEVER_WAIT;
}
/* if the request buffer is not empty, it means we're
* about to process another request, so send pending
* data with MSG_MORE to merge TCP packets when possible.
* Just don't do this if the buffer is close to be full,
* because the request will wait for it to flush a little
* bit before proceeding.
*/
if (s->req->buf->i) {
if (s->rep->buf->o &&
!buffer_full(s->rep->buf, global.tune.maxrewrite) &&
bi_end(s->rep->buf) <= s->rep->buf->data + s->rep->buf->size - global.tune.maxrewrite)
s->rep->flags |= CF_EXPECT_MORE;
}
/* we're removing the analysers, we MUST re-enable events detection */
channel_auto_read(s->req);
channel_auto_close(s->req);
channel_auto_read(s->rep);
channel_auto_close(s->rep);
/* we're in keep-alive with an idle connection, monitor it */
si_idle_conn(s->req->cons);
s->req->analysers = s->listener->analysers;
s->rep->analysers = 0;
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: void ChromePluginServiceFilter::AuthorizeAllPlugins(int render_process_id) {
AuthorizePlugin(render_process_id, FilePath());
}
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: 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 blkcg_init_queue(struct request_queue *q)
{
struct blkcg_gq *new_blkg, *blkg;
bool preloaded;
int ret;
new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL);
if (!new_blkg)
return -ENOMEM;
preloaded = !radix_tree_preload(GFP_KERNEL);
/*
* Make sure the root blkg exists and count the existing blkgs. As
* @q is bypassing at this point, blkg_lookup_create() can't be
* used. Open code insertion.
*/
rcu_read_lock();
spin_lock_irq(q->queue_lock);
blkg = blkg_create(&blkcg_root, q, new_blkg);
spin_unlock_irq(q->queue_lock);
rcu_read_unlock();
if (preloaded)
radix_tree_preload_end();
if (IS_ERR(blkg)) {
blkg_free(new_blkg);
return PTR_ERR(blkg);
}
q->root_blkg = blkg;
q->root_rl.blkg = blkg;
ret = blk_throtl_init(q);
if (ret) {
spin_lock_irq(q->queue_lock);
blkg_destroy_all(q);
spin_unlock_irq(q->queue_lock);
}
return ret;
}
Commit Message: blkcg: fix double free of new_blkg in blkcg_init_queue
If blkg_create fails, new_blkg passed as an argument will
be freed by blkg_create, so there is no need to free it again.
Signed-off-by: Hou Tao <[email protected]>
Signed-off-by: Jens Axboe <[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: int libevt_record_values_read_event(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
uint8_t strict_mode,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_event";
size_t record_data_offset = 0;
size_t strings_data_offset = 0;
ssize_t value_data_size = 0;
uint32_t data_offset = 0;
uint32_t data_size = 0;
uint32_t members_data_size = 0;
uint32_t size = 0;
uint32_t size_copy = 0;
uint32_t strings_offset = 0;
uint32_t strings_size = 0;
uint32_t user_sid_offset = 0;
uint32_t user_sid_size = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
uint16_t value_16bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->record_number,
record_values->number );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->creation_time,
record_values->creation_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->written_time,
record_values->written_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->event_identifier,
record_values->event_identifier );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_type,
record_values->event_type );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_category,
record_values->event_category );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->strings_offset,
strings_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_size,
user_sid_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_offset,
user_sid_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_size,
data_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_offset,
data_offset );
byte_stream_copy_to_uint32_little_endian(
&( record_data[ record_data_size - 4 ] ),
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t\t: %" PRIu32 "\n",
function,
size );
libcnotify_printf(
"%s: signature\t\t\t\t: %c%c%c%c\n",
function,
( (evt_record_event_header_t *) record_data )->signature[ 0 ],
( (evt_record_event_header_t *) record_data )->signature[ 1 ],
( (evt_record_event_header_t *) record_data )->signature[ 2 ],
( (evt_record_event_header_t *) record_data )->signature[ 3 ] );
libcnotify_printf(
"%s: record number\t\t\t\t: %" PRIu32 "\n",
function,
record_values->number );
if( libevt_debug_print_posix_time_value(
function,
"creation time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->creation_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
if( libevt_debug_print_posix_time_value(
function,
"written time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->written_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
libcnotify_printf(
"%s: event identifier\t\t\t: 0x%08" PRIx32 "\n",
function,
record_values->event_identifier );
libcnotify_printf(
"%s: event identifier: code\t\t\t: %" PRIu32 "\n",
function,
record_values->event_identifier & 0x0000ffffUL );
libcnotify_printf(
"%s: event identifier: facility\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x0fff0000UL ) >> 16 );
libcnotify_printf(
"%s: event identifier: reserved\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x10000000UL ) >> 28 );
libcnotify_printf(
"%s: event identifier: customer flags\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x20000000UL ) >> 29 );
libcnotify_printf(
"%s: event identifier: severity\t\t: %" PRIu32 " (",
function,
( record_values->event_identifier & 0xc0000000UL ) >> 30 );
libevt_debug_print_event_identifier_severity(
record_values->event_identifier );
libcnotify_printf(
")\n" );
libcnotify_printf(
"%s: event type\t\t\t\t: %" PRIu16 " (",
function,
record_values->event_type );
libevt_debug_print_event_type(
record_values->event_type );
libcnotify_printf(
")\n" );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->number_of_strings,
value_16bit );
libcnotify_printf(
"%s: number of strings\t\t\t: %" PRIu16 "\n",
function,
value_16bit );
libcnotify_printf(
"%s: event category\t\t\t\t: %" PRIu16 "\n",
function,
record_values->event_category );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_flags,
value_16bit );
libcnotify_printf(
"%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n",
function,
value_16bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->closing_record_number,
value_32bit );
libcnotify_printf(
"%s: closing record values number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: strings offset\t\t\t\t: %" PRIu32 "\n",
function,
strings_offset );
libcnotify_printf(
"%s: user security identifier (SID) size\t: %" PRIu32 "\n",
function,
user_sid_size );
libcnotify_printf(
"%s: user security identifier (SID) offset\t: %" PRIu32 "\n",
function,
user_sid_offset );
libcnotify_printf(
"%s: data size\t\t\t\t: %" PRIu32 "\n",
function,
data_size );
libcnotify_printf(
"%s: data offset\t\t\t\t: %" PRIu32 "\n",
function,
data_offset );
}
#endif
record_data_offset = sizeof( evt_record_event_header_t );
if( ( user_sid_offset == 0 )
&& ( user_sid_size != 0 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset or size value out of bounds.",
function );
goto on_error;
}
if( user_sid_offset != 0 )
{
if( ( (size_t) user_sid_offset < record_data_offset )
|| ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset value out of bounds.",
function );
goto on_error;
}
if( user_sid_size != 0 )
{
if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID size value out of bounds.",
function );
goto on_error;
}
}
}
/* If the strings offset is points at the offset at record data size - 4
* the strings are empty. For this to be sane the data offset should
* be the same as the strings offset or the data size 0.
*/
if( ( (size_t) strings_offset < user_sid_offset )
|| ( (size_t) strings_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( ( (size_t) data_offset < strings_offset )
|| ( (size_t) data_offset >= ( record_data_size - 4 ) ) )
{
if( data_size != 0 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data offset value out of bounds.",
function );
goto on_error;
}
data_offset = (uint32_t) record_data_size - 4;
}
if( ( (size_t) strings_offset >= ( record_data_size - 4 ) )
&& ( strings_offset != data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( strings_offset != 0 )
{
if( strings_offset < record_data_offset )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
}
if( user_sid_offset != 0 )
{
members_data_size = user_sid_offset - (uint32_t) record_data_offset;
}
else if( strings_offset != 0 )
{
members_data_size = strings_offset - (uint32_t) record_data_offset;
}
if( strings_offset != 0 )
{
strings_size = data_offset - strings_offset;
}
if( data_size != 0 )
{
if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
}
if( members_data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->source_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create source name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->source_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of source name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: source name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->source_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print source name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( libfvalue_value_type_initialize(
&( record_values->computer_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create computer name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->computer_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of computer name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: computer name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->computer_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print computer name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( members_data_size > 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members trailing data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
record_data_offset += members_data_size;
}
}
if( user_sid_size != 0 )
{
if( libfvalue_value_type_initialize(
&( record_values->user_security_identifier ),
LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create user security identifier (SID) value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->user_security_identifier,
&( record_data[ user_sid_offset ] ),
(size_t) user_sid_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of user security identifier (SID) value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: user security identifier (SID)\t\t: ",
function );
if( libfvalue_value_print(
record_values->user_security_identifier,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print user security identifier (SID) value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += user_sid_size;
}
if( strings_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: strings data:\n",
function );
libcnotify_print_data(
&( record_data[ strings_offset ] ),
strings_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( size_copy == 0 )
{
/* If the strings data is truncated
*/
strings_data_offset = strings_offset + strings_size - 2;
while( strings_data_offset > strings_offset )
{
if( ( record_data[ strings_data_offset ] != 0 )
|| ( record_data[ strings_data_offset + 1 ] != 0 ) )
{
strings_size += 2;
break;
}
strings_data_offset -= 2;
strings_size -= 2;
}
}
if( libfvalue_value_type_initialize(
&( record_values->strings ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create strings value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_strings_array(
record_values->strings,
&( record_data[ strings_offset ] ),
strings_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of strings value.",
function );
goto on_error;
}
record_data_offset += strings_size;
}
if( data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: data:\n",
function );
libcnotify_print_data(
&( record_data[ data_offset ] ),
(size_t) data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->data ),
LIBFVALUE_VALUE_TYPE_BINARY_DATA,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create data value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->data,
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of data value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
record_data_offset += data_size;
#endif
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
if( record_data_offset < ( record_data_size - 4 ) )
{
libcnotify_printf(
"%s: padding:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) record_data_size - record_data_offset - 4,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
libcnotify_printf(
"%s: size copy\t\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( ( strict_mode == 0 )
&& ( size_copy == 0 ) )
{
size_copy = size;
}
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
goto on_error;
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record_values data size and size.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values->data != NULL )
{
libfvalue_value_free(
&( record_values->data ),
NULL );
}
if( record_values->strings != NULL )
{
libfvalue_value_free(
&( record_values->strings ),
NULL );
}
if( record_values->user_security_identifier != NULL )
{
libfvalue_value_free(
&( record_values->user_security_identifier ),
NULL );
}
if( record_values->computer_name != NULL )
{
libfvalue_value_free(
&( record_values->computer_name ),
NULL );
}
if( record_values->source_name != NULL )
{
libfvalue_value_free(
&( record_values->source_name ),
NULL );
}
return( -1 );
}
Commit Message: Applied updates and addition boundary checks for corrupted data
CWE ID: CWE-125
Target: 1
Example 2:
Code: void EndSplitView() { split_view_controller()->EndSplitView(); }
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: void RenderThreadImpl::SetResourceDispatcherDelegate(
ResourceDispatcherDelegate* delegate) {
resource_dispatcher()->set_delegate(delegate);
}
Commit Message: Suspend shared timers while blockingly closing databases
BUG=388771
[email protected]
Review URL: https://codereview.chromium.org/409863002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284785 0039d316-1c4b-4281-b951-d872f2087c98
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: static int mem_cgroup_count_precharge_pte_range(pmd_t *pmd,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->private;
pte_t *pte;
spinlock_t *ptl;
split_huge_page_pmd(walk->mm, pmd);
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
if (is_target_pte_for_mc(vma, addr, *pte, NULL))
mc.precharge++; /* increment precharge temporarily */
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 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
Target: 1
Example 2:
Code: run_err(const char *fmt,...)
{
static FILE *fp;
va_list ap;
++errs;
if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
(void) fprintf(fp, "%c", 0x01);
(void) fprintf(fp, "scp: ");
va_start(ap, fmt);
(void) vfprintf(fp, fmt, ap);
va_end(ap);
(void) fprintf(fp, "\n");
(void) fflush(fp);
}
if (!iamremote) {
va_start(ap, fmt);
vfmprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
Commit Message: upstream: disallow empty incoming filename or ones that refer to the
current directory; based on report/patch from Harry Sintonen
OpenBSD-Commit-ID: f27651b30eaee2df49540ab68d030865c04f6de9
CWE ID: CWE-706
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: WorkerProcessLauncher::Core::Core(
scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
scoped_ptr<WorkerProcessLauncher::Delegate> launcher_delegate,
WorkerProcessIpcDelegate* worker_delegate)
: caller_task_runner_(caller_task_runner),
launcher_delegate_(launcher_delegate.Pass()),
worker_delegate_(worker_delegate),
ipc_enabled_(false),
launch_backoff_(&kDefaultBackoffPolicy),
stopping_(false) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
ipc_error_timer_.reset(new base::OneShotTimer<Core>());
launch_success_timer_.reset(new base::OneShotTimer<Core>());
launch_timer_.reset(new base::OneShotTimer<Core>());
}
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: bool config_save(const config_t *config, const char *filename) {
assert(config != NULL);
assert(filename != NULL);
assert(*filename != '\0');
char *temp_filename = osi_calloc(strlen(filename) + 5);
if (!temp_filename) {
LOG_ERROR("%s unable to allocate memory for filename.", __func__);
return false;
}
strcpy(temp_filename, filename);
strcat(temp_filename, ".new");
FILE *fp = fopen(temp_filename, "wt");
if (!fp) {
LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno));
goto error;
}
for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) {
const section_t *section = (const section_t *)list_node(node);
fprintf(fp, "[%s]\n", section->name);
for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) {
const entry_t *entry = (const entry_t *)list_node(enode);
fprintf(fp, "%s = %s\n", entry->key, entry->value);
}
if (list_next(node) != list_end(config->sections))
fputc('\n', fp);
}
fflush(fp);
fclose(fp);
if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) {
LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno));
goto error;
}
if (rename(temp_filename, filename) == -1) {
LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno));
goto error;
}
osi_free(temp_filename);
return true;
error:;
unlink(temp_filename);
osi_free(temp_filename);
return false;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284
Target: 1
Example 2:
Code: void ExtensionOptionsGuest::CloseContents(WebContents* source) {
DispatchEventToView(make_scoped_ptr(
new GuestViewEvent(extension_options_internal::OnClose::kEventName,
make_scoped_ptr(new base::DictionaryValue()))));
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
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 TestClearTwoSections(const char* html, bool unowned) {
LoadHTML(html);
WebLocalFrame* web_frame = GetMainFrame();
ASSERT_NE(nullptr, web_frame);
FormCache form_cache(web_frame);
std::vector<FormData> forms = form_cache.ExtractNewForms();
ASSERT_EQ(1U, forms.size());
WebInputElement firstname_shipping =
GetInputElementById("firstname-shipping");
firstname_shipping.SetAutofillValue("John");
firstname_shipping.SetAutofillState(WebAutofillState::kAutofilled);
firstname_shipping.SetAutofillSection("shipping");
WebInputElement lastname_shipping =
GetInputElementById("lastname-shipping");
lastname_shipping.SetAutofillValue("Smith");
lastname_shipping.SetAutofillState(WebAutofillState::kAutofilled);
lastname_shipping.SetAutofillSection("shipping");
WebInputElement city_shipping = GetInputElementById("city-shipping");
city_shipping.SetAutofillValue("Montreal");
city_shipping.SetAutofillState(WebAutofillState::kAutofilled);
city_shipping.SetAutofillSection("shipping");
WebInputElement firstname_billing =
GetInputElementById("firstname-billing");
firstname_billing.SetAutofillValue("John");
firstname_billing.SetAutofillState(WebAutofillState::kAutofilled);
firstname_billing.SetAutofillSection("billing");
WebInputElement lastname_billing = GetInputElementById("lastname-billing");
lastname_billing.SetAutofillValue("Smith");
lastname_billing.SetAutofillState(WebAutofillState::kAutofilled);
lastname_billing.SetAutofillSection("billing");
WebInputElement city_billing = GetInputElementById("city-billing");
city_billing.SetAutofillValue("Paris");
city_billing.SetAutofillState(WebAutofillState::kAutofilled);
city_billing.SetAutofillSection("billing");
EXPECT_TRUE(form_cache.ClearSectionWithElement(firstname_shipping));
EXPECT_FALSE(firstname_shipping.IsAutofilled());
EXPECT_FALSE(lastname_shipping.IsAutofilled());
EXPECT_FALSE(city_shipping.IsAutofilled());
EXPECT_TRUE(firstname_billing.IsAutofilled());
EXPECT_TRUE(lastname_billing.IsAutofilled());
EXPECT_TRUE(city_billing.IsAutofilled());
FormData form;
FormFieldData field;
EXPECT_TRUE(FindFormAndFieldForFormControlElement(firstname_shipping, &form,
&field));
EXPECT_EQ(GetCanonicalOriginForDocument(web_frame->GetDocument()),
form.origin);
EXPECT_FALSE(form.origin.is_empty());
if (!unowned) {
EXPECT_EQ(ASCIIToUTF16("TestForm"), form.name);
EXPECT_EQ(GURL("http://abc.com"), form.action);
}
const std::vector<FormFieldData>& fields = form.fields;
ASSERT_EQ(6U, fields.size());
FormFieldData expected;
expected.form_control_type = "text";
expected.max_length = WebInputElement::DefaultMaxLength();
expected.is_autofilled = false;
expected.id_attribute = ASCIIToUTF16("firstname-shipping");
expected.name = expected.id_attribute;
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[0]);
expected.id_attribute = ASCIIToUTF16("lastname-shipping");
expected.name = expected.id_attribute;
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[1]);
expected.id_attribute = ASCIIToUTF16("city-shipping");
expected.name = expected.id_attribute;
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[2]);
expected.is_autofilled = true;
expected.id_attribute = ASCIIToUTF16("firstname-billing");
expected.name = expected.id_attribute;
expected.value = ASCIIToUTF16("John");
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[3]);
expected.id_attribute = ASCIIToUTF16("lastname-billing");
expected.name = expected.id_attribute;
expected.value = ASCIIToUTF16("Smith");
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[4]);
expected.id_attribute = ASCIIToUTF16("city-billing");
expected.name = expected.id_attribute;
expected.value = ASCIIToUTF16("Paris");
EXPECT_FORM_FIELD_DATA_EQUALS(expected, fields[5]);
EXPECT_EQ(0, firstname_shipping.SelectionStart());
EXPECT_EQ(0, firstname_shipping.SelectionEnd());
}
Commit Message: [autofill] Pin preview font-family to a system font
Bug: 916838
Change-Id: I4e874105262f2e15a11a7a18a7afd204e5827400
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1423109
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Koji Ishii <[email protected]>
Commit-Queue: Roger McFarlane <[email protected]>
Cr-Commit-Position: refs/heads/master@{#640884}
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: char **XGetFontPath(
register Display *dpy,
int *npaths) /* RETURN */
{
xGetFontPathReply rep;
unsigned long nbytes = 0;
char **flist = NULL;
char *ch = NULL;
char *chend;
int count = 0;
register unsigned i;
register int length;
_X_UNUSED register xReq *req;
LockDisplay(dpy);
GetEmptyReq (GetFontPath, req);
(void) _XReply (dpy, (xReply *) &rep, 0, xFalse);
if (rep.nPaths) {
flist = Xmalloc(rep.nPaths * sizeof (char *));
if (rep.length < (INT_MAX >> 2)) {
nbytes = (unsigned long) rep.length << 2;
ch = Xmalloc (nbytes + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, nbytes);
/*
* unpack into null terminated strings.
*/
chend = ch + nbytes;
length = *ch;
for (i = 0; i < rep.nPaths; i++) {
if (ch + length < chend) {
flist[i] = ch+1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else
flist[i] = NULL;
}
}
*npaths = count;
UnlockDisplay(dpy);
SyncHandle();
return (flist);
}
Commit Message:
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int nfs4_xdr_enc_server_caps(struct rpc_rqst *req, __be32 *p, const struct nfs_fh *fhandle)
{
struct xdr_stream xdr;
struct compound_hdr hdr = {
.nops = 2,
};
int status;
xdr_init_encode(&xdr, &req->rq_snd_buf, p);
encode_compound_hdr(&xdr, &hdr);
status = encode_putfh(&xdr, fhandle);
if (status == 0)
status = encode_getattr_one(&xdr, FATTR4_WORD0_SUPPORTED_ATTRS|
FATTR4_WORD0_LINK_SUPPORT|
FATTR4_WORD0_SYMLINK_SUPPORT|
FATTR4_WORD0_ACLSUPPORT);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
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: virtual ~BrowserCommandControllerFullscreenTest() {}
Commit Message: Fix OS_MACOS typos. Should be OS_MACOSX.
BUG=163208
TEST=none
Review URL: https://codereview.chromium.org/12829005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@189130 0039d316-1c4b-4281-b951-d872f2087c98
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 SpdyWriteQueue::RemovePendingWritesForStream(
const base::WeakPtr<SpdyStream>& stream) {
CHECK(!removing_writes_);
removing_writes_ = true;
RequestPriority priority = stream->priority();
CHECK_GE(priority, MINIMUM_PRIORITY);
CHECK_LE(priority, MAXIMUM_PRIORITY);
DCHECK(stream.get());
#if DCHECK_IS_ON
for (int i = MINIMUM_PRIORITY; i <= MAXIMUM_PRIORITY; ++i) {
if (priority == i)
continue;
for (std::deque<PendingWrite>::const_iterator it = queue_[i].begin();
it != queue_[i].end(); ++it) {
DCHECK_NE(it->stream.get(), stream.get());
}
}
#endif
std::deque<PendingWrite>* queue = &queue_[priority];
std::deque<PendingWrite>::iterator out_it = queue->begin();
for (std::deque<PendingWrite>::const_iterator it = queue->begin();
it != queue->end(); ++it) {
if (it->stream.get() == stream.get()) {
delete it->frame_producer;
} else {
*out_it = *it;
++out_it;
}
}
queue->erase(out_it, queue->end());
removing_writes_ = false;
}
Commit Message: These can post callbacks which re-enter into SpdyWriteQueue.
BUG=369539
Review URL: https://codereview.chromium.org/265933007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268730 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
Target: 1
Example 2:
Code: e1000e_set_gcr(E1000ECore *core, int index, uint32_t val)
{
uint32_t ro_bits = core->mac[GCR] & E1000_GCR_RO_BITS;
core->mac[GCR] = (val & ~E1000_GCR_RO_BITS) | ro_bits;
}
Commit Message:
CWE ID: CWE-835
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: ModuleExport size_t RegisterFAXImage(void)
{
MagickInfo
*entry;
static const char
*Note=
{
"FAX machines use non-square pixels which are 1.5 times wider than\n"
"they are tall but computer displays use square pixels, therefore\n"
"FAX images may appear to be narrow unless they are explicitly\n"
"resized using a geometry of \"150x100%\".\n"
};
entry=SetMagickInfo("FAX");
entry->decoder=(DecodeImageHandler *) ReadFAXImage;
entry->encoder=(EncodeImageHandler *) WriteFAXImage;
entry->magick=(IsImageFormatHandler *) IsFAX;
entry->description=ConstantString("Group 3 FAX");
entry->note=ConstantString(Note);
entry->module=ConstantString("FAX");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("G3");
entry->decoder=(DecodeImageHandler *) ReadFAXImage;
entry->encoder=(EncodeImageHandler *) WriteFAXImage;
entry->magick=(IsImageFormatHandler *) IsFAX;
entry->adjoin=MagickFalse;
entry->description=ConstantString("Group 3 FAX");
entry->module=ConstantString("FAX");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
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 int snd_timer_user_release(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
if (file->private_data) {
tu = file->private_data;
file->private_data = NULL;
if (tu->timeri)
snd_timer_close(tu->timeri);
kfree(tu->queue);
kfree(tu->tqueue);
kfree(tu);
}
return 0;
}
Commit Message: ALSA: timer: Fix race among timer ioctls
ALSA timer ioctls have an open race and this may lead to a
use-after-free of timer instance object. A simplistic fix is to make
each ioctl exclusive. We have already tread_sem for controlling the
tread, and extend this as a global mutex to be applied to each ioctl.
The downside is, of course, the worse concurrency. But these ioctls
aren't to be parallel accessible, in anyway, so it should be fine to
serialize there.
Reported-by: Dmitry Vyukov <[email protected]>
Tested-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: void btrfs_put_tree_mod_seq(struct btrfs_fs_info *fs_info,
struct seq_list *elem)
{
struct rb_root *tm_root;
struct rb_node *node;
struct rb_node *next;
struct seq_list *cur_elem;
struct tree_mod_elem *tm;
u64 min_seq = (u64)-1;
u64 seq_putting = elem->seq;
if (!seq_putting)
return;
spin_lock(&fs_info->tree_mod_seq_lock);
list_del(&elem->list);
elem->seq = 0;
list_for_each_entry(cur_elem, &fs_info->tree_mod_seq_list, list) {
if (cur_elem->seq < min_seq) {
if (seq_putting > cur_elem->seq) {
/*
* blocker with lower sequence number exists, we
* cannot remove anything from the log
*/
spin_unlock(&fs_info->tree_mod_seq_lock);
return;
}
min_seq = cur_elem->seq;
}
}
spin_unlock(&fs_info->tree_mod_seq_lock);
/*
* anything that's lower than the lowest existing (read: blocked)
* sequence number can be removed from the tree.
*/
tree_mod_log_write_lock(fs_info);
tm_root = &fs_info->tree_mod_log;
for (node = rb_first(tm_root); node; node = next) {
next = rb_next(node);
tm = container_of(node, struct tree_mod_elem, node);
if (tm->seq > min_seq)
continue;
rb_erase(node, tm_root);
kfree(tm);
}
tree_mod_log_write_unlock(fs_info);
}
Commit Message: Btrfs: make xattr replace operations atomic
Replacing a xattr consists of doing a lookup for its existing value, delete
the current value from the respective leaf, release the search path and then
finally insert the new value. This leaves a time window where readers (getxattr,
listxattrs) won't see any value for the xattr. Xattrs are used to store ACLs,
so this has security implications.
This change also fixes 2 other existing issues which were:
*) Deleting the old xattr value without verifying first if the new xattr will
fit in the existing leaf item (in case multiple xattrs are packed in the
same item due to name hash collision);
*) Returning -EEXIST when the flag XATTR_CREATE is given and the xattr doesn't
exist but we have have an existing item that packs muliple xattrs with
the same name hash as the input xattr. In this case we should return ENOSPC.
A test case for xfstests follows soon.
Thanks to Alexandre Oliva for reporting the non-atomicity of the xattr replace
implementation.
Reported-by: Alexandre Oliva <[email protected]>
Signed-off-by: Filipe Manana <[email protected]>
Signed-off-by: Chris Mason <[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: int FLTIsNumeric(const char *pszValue)
{
if (pszValue != NULL && *pszValue != '\0' && !isspace(*pszValue)) {
/*the regex seems to have a problem on windows when mapserver is built using
PHP regex*/
#if defined(_WIN32) && !defined(__CYGWIN__)
int i = 0, nLength=0, bString=0;
nLength = strlen(pszValue);
for (i=0; i<nLength; i++) {
if (i == 0) {
if (!isdigit(pszValue[i]) && pszValue[i] != '-') {
bString = 1;
break;
}
} else if (!isdigit(pszValue[i]) && pszValue[i] != '.') {
bString = 1;
break;
}
}
if (!bString)
return MS_TRUE;
#else
char * p;
strtod(pszValue, &p);
if ( p != pszValue && *p == '\0') return MS_TRUE;
#endif
}
return MS_FALSE;
}
Commit Message: security fix (patch by EvenR)
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 CoordinatorImpl::RequestGlobalMemoryDumpAndAppendToTrace(
MemoryDumpType dump_type,
MemoryDumpLevelOfDetail level_of_detail,
const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback) {
auto adapter =
[](const RequestGlobalMemoryDumpAndAppendToTraceCallback& callback,
bool success, uint64_t dump_guid,
mojom::GlobalMemoryDumpPtr) { callback.Run(success, dump_guid); };
QueuedRequest::Args args(dump_type, level_of_detail, {},
true /* add_to_trace */, base::kNullProcessId);
RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, 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: static int ipv4_sysctl_rtcache_flush(ctl_table *__ctl, int write,
void __user *buffer,
size_t *lenp, loff_t *ppos)
{
if (write) {
int flush_delay;
ctl_table ctl;
struct net *net;
memcpy(&ctl, __ctl, sizeof(ctl));
ctl.data = &flush_delay;
proc_dointvec(&ctl, write, buffer, lenp, ppos);
net = (struct net *)__ctl->extra1;
rt_cache_flush(net, flush_delay);
return 0;
}
return -EINVAL;
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[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 FlagsState::SetExperimentEnabled(FlagsStorage* flags_storage,
const std::string& internal_name,
bool enable) {
size_t at_index = internal_name.find(testing::kMultiSeparator);
if (at_index != std::string::npos) {
DCHECK(enable);
DCHECK_NE(at_index, 0u);
const std::string experiment_name = internal_name.substr(0, at_index);
SetExperimentEnabled(flags_storage, experiment_name, false);
if (internal_name != experiment_name + "@0") {
std::set<std::string> enabled_experiments;
GetSanitizedEnabledFlags(flags_storage, &enabled_experiments);
needs_restart_ |= enabled_experiments.insert(internal_name).second;
flags_storage->SetFlags(enabled_experiments);
}
return;
}
std::set<std::string> enabled_experiments;
GetSanitizedEnabledFlags(flags_storage, &enabled_experiments);
const Experiment* e = NULL;
for (size_t i = 0; i < num_experiments; ++i) {
if (experiments[i].internal_name == internal_name) {
e = experiments + i;
break;
}
}
DCHECK(e);
if (e->type == Experiment::SINGLE_VALUE) {
if (enable)
needs_restart_ |= enabled_experiments.insert(internal_name).second;
else
needs_restart_ |= (enabled_experiments.erase(internal_name) > 0);
} else {
if (enable) {
needs_restart_ |= enabled_experiments.insert(e->NameForChoice(0)).second;
} else {
for (int i = 0; i < e->num_choices; ++i) {
std::string choice_name = e->NameForChoice(i);
if (enabled_experiments.find(choice_name) !=
enabled_experiments.end()) {
needs_restart_ = true;
enabled_experiments.erase(choice_name);
}
}
}
}
flags_storage->SetFlags(enabled_experiments);
}
Commit Message: Remove --disable-app-shims.
App shims have been enabled by default for 3 milestones
(since r242711).
BUG=350161
Review URL: https://codereview.chromium.org/298953002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@272786 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: pdf_load_xobject(fz_context *ctx, pdf_document *doc, pdf_obj *dict)
{
pdf_xobject *form;
if ((form = pdf_find_item(ctx, pdf_drop_xobject_imp, dict)) != NULL)
return form;
form->iteration = 0;
/* Store item immediately, to avoid possible recursion if objects refer back to this one */
pdf_store_item(ctx, dict, form, pdf_xobject_size(form));
form->obj = pdf_keep_obj(ctx, dict);
return form;
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: double GetAverageMismatchPsnr() const {
if (mismatch_nframes_)
return mismatch_psnr_ / mismatch_nframes_;
return 0.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: 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 lg_ultrax_remote_mapping(struct hid_input *hi,
struct hid_usage *usage, unsigned long **bit, int *max)
{
if ((usage->hid & HID_USAGE_PAGE) != HID_UP_LOGIVENDOR)
return 0;
set_bit(EV_REP, hi->input->evbit);
switch (usage->hid & HID_USAGE) {
/* Reported on Logitech Ultra X Media Remote */
case 0x004: lg_map_key_clear(KEY_AGAIN); break;
case 0x00d: lg_map_key_clear(KEY_HOME); break;
case 0x024: lg_map_key_clear(KEY_SHUFFLE); break;
case 0x025: lg_map_key_clear(KEY_TV); break;
case 0x026: lg_map_key_clear(KEY_MENU); break;
case 0x031: lg_map_key_clear(KEY_AUDIO); break;
case 0x032: lg_map_key_clear(KEY_TEXT); break;
case 0x033: lg_map_key_clear(KEY_LAST); break;
case 0x047: lg_map_key_clear(KEY_MP3); break;
case 0x048: lg_map_key_clear(KEY_DVD); break;
case 0x049: lg_map_key_clear(KEY_MEDIA); break;
case 0x04a: lg_map_key_clear(KEY_VIDEO); break;
case 0x04b: lg_map_key_clear(KEY_ANGLE); break;
case 0x04c: lg_map_key_clear(KEY_LANGUAGE); break;
case 0x04d: lg_map_key_clear(KEY_SUBTITLE); break;
case 0x051: lg_map_key_clear(KEY_RED); break;
case 0x052: lg_map_key_clear(KEY_CLOSE); break;
default:
return 0;
}
return 1;
}
Commit Message: HID: fix a couple of off-by-ones
There are a few very theoretical off-by-one bugs in report descriptor size
checking when performing a pre-parsing fixup. Fix those.
Cc: [email protected]
Reported-by: Ben Hawkes <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[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: void unix_inflight(struct file *fp)
{
struct sock *s = unix_get_socket(fp);
spin_lock(&unix_gc_lock);
if (s) {
struct unix_sock *u = unix_sk(s);
if (atomic_long_inc_return(&u->inflight) == 1) {
BUG_ON(!list_empty(&u->link));
list_add_tail(&u->link, &gc_inflight_list);
} else {
BUG_ON(list_empty(&u->link));
}
unix_tot_inflight++;
}
fp->f_cred->user->unix_inflight++;
spin_unlock(&unix_gc_lock);
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399
Target: 1
Example 2:
Code: __acquires(nl_table_lock)
{
read_lock(&nl_table_lock);
return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
Commit Message: af_netlink: force credentials passing [CVE-2012-3520]
Pablo Neira Ayuso discovered that avahi and
potentially NetworkManager accept spoofed Netlink messages because of a
kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data
to the receiver if the sender did not provide such data, instead of not
including any such data at all or including the correct data from the
peer (as it is the case with AF_UNIX).
This bug was introduced in commit 16e572626961
(af_unix: dont send SCM_CREDENTIALS by default)
This patch forces passing credentials for netlink, as
before the regression.
Another fix would be to not add SCM_CREDENTIALS in
netlink messages if not provided by the sender, but it
might break some programs.
With help from Florian Weimer & Petr Matousek
This issue is designated as CVE-2012-3520
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Petr Matousek <[email protected]>
Cc: Florian Weimer <[email protected]>
Cc: Pablo Neira Ayuso <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-287
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: SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24,
const struct nls_table *codepage)
{
int rc;
unsigned char p16[16], p21[21];
memset(p16, '\0', 16);
memset(p21, '\0', 21);
rc = E_md4hash(passwd, p16, codepage);
if (rc) {
cifs_dbg(FYI, "%s Can't generate NT hash, error: %d\n",
__func__, rc);
return rc;
}
memcpy(p21, p16, 16);
rc = E_P24(p21, c8, p24);
return rc;
}
Commit Message: cifs: Fix smbencrypt() to stop pointing a scatterlist at the stack
smbencrypt() points a scatterlist to the stack, which is breaks if
CONFIG_VMAP_STACK=y.
Fix it by switching to crypto_cipher_encrypt_one(). The new code
should be considerably faster as an added benefit.
This code is nearly identical to some code that Eric Biggers
suggested.
Cc: [email protected] # 4.9 only
Reported-by: Eric Biggers <[email protected]>
Signed-off-by: Andy Lutomirski <[email protected]>
Acked-by: Jeff Layton <[email protected]>
Signed-off-by: Steve French <[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: void DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected();
}
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
Target: 1
Example 2:
Code: void bdt_dut_mode_configure(char *p)
{
int32_t mode = -1;
bdt_log("BT DUT MODE CONFIGURE");
if (!bt_enabled) {
bdt_log("Bluetooth must be enabled for test_mode to work.");
return;
}
mode = get_signed_int(&p, mode);
if ((mode != 0) && (mode != 1)) {
bdt_log("Please specify mode: 1 to enter, 0 to exit");
return;
}
status = sBtInterface->dut_mode_configure(mode);
check_return_status(status);
}
Commit Message: Add guest mode functionality (2/3)
Add a flag to enable() to start Bluetooth in restricted
mode. In restricted mode, all devices that are paired during
restricted mode are deleted upon leaving restricted mode.
Right now restricted mode is only entered while a guest
user is active.
Bug: 27410683
Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19
CWE ID: CWE-20
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 ghash_final(struct shash_desc *desc, u8 *dst)
{
struct ghash_desc_ctx *dctx = shash_desc_ctx(desc);
struct ghash_ctx *ctx = crypto_shash_ctx(desc->tfm);
u8 *buf = dctx->buffer;
if (!ctx->gf128)
return -ENOKEY;
ghash_flush(ctx, dctx);
memcpy(dst, buf, GHASH_BLOCK_SIZE);
return 0;
}
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
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 AppListController::Init(Profile* initial_profile) {
if (win8::IsSingleWindowMetroMode())
return;
PrefService* prefs = g_browser_process->local_state();
if (prefs->HasPrefPath(prefs::kRestartWithAppList) &&
prefs->GetBoolean(prefs::kRestartWithAppList)) {
prefs->SetBoolean(prefs::kRestartWithAppList, false);
AppListController::GetInstance()->
ShowAppListDuringModeSwitch(initial_profile);
}
AppListController::GetInstance();
ScheduleWarmup();
MigrateAppLauncherEnabledPref();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList))
EnableAppList();
if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList))
DisableAppList();
}
Commit Message: Upgrade old app host to new app launcher on startup
This patch is a continuation of https://codereview.chromium.org/16805002/.
BUG=248825
Review URL: https://chromiumcodereview.appspot.com/17022015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
const CameraMetadata &request) {
status_t res;
if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
res = configureStreamsLocked();
if (res == BAD_VALUE && mStatus == STATUS_UNCONFIGURED) {
CLOGE("No streams configured");
return NULL;
}
if (res != OK) {
SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res);
return NULL;
}
if (mStatus == STATUS_UNCONFIGURED) {
CLOGE("No streams configured");
return NULL;
}
}
sp<CaptureRequest> newRequest = createCaptureRequest(request);
return newRequest;
}
Commit Message: Camera3Device: Validate template ID
Validate template ID before creating a default request.
Bug: 26866110
Bug: 27568958
Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d
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: PHP_FUNCTION(snmp_set_enum_print)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, (int) a1);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-416
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 AppCacheHost::MarkAsForeignEntry(const GURL& document_url,
int64 cache_document_was_loaded_from) {
storage()->MarkEntryAsForeign(
main_resource_was_namespace_entry_ ? namespace_entry_url_ : document_url,
cache_document_was_loaded_from);
SelectCache(document_url, kAppCacheNoCacheId, GURL());
}
Commit Message: Fix possible map::end() dereference in AppCacheUpdateJob triggered by a compromised renderer.
BUG=551044
Review URL: https://codereview.chromium.org/1418783005
Cr-Commit-Position: refs/heads/master@{#358815}
CWE ID:
Target: 1
Example 2:
Code: xmlNsWarn(xmlParserCtxtPtr ctxt, xmlParserErrors error,
const char *msg,
const xmlChar * info1, const xmlChar * info2,
const xmlChar * info3)
{
if ((ctxt != NULL) && (ctxt->disableSAX != 0) &&
(ctxt->instate == XML_PARSER_EOF))
return;
__xmlRaiseError(NULL, NULL, NULL, ctxt, NULL, XML_FROM_NAMESPACE, error,
XML_ERR_WARNING, NULL, 0, (const char *) info1,
(const char *) info2, (const char *) info3, 0, 0, msg,
info1, info2, info3);
}
Commit Message: Detect infinite recursion in parameter entities
When expanding a parameter entity in a DTD, infinite recursion could
lead to an infinite loop or memory exhaustion.
Thanks to Wei Lei for the first of many reports.
Fixes bug 759579.
CWE ID: CWE-835
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 virtnet_fail_on_feature(struct virtio_device *vdev,
unsigned int fbit,
const char *fname, const char *dname)
{
if (!virtio_has_feature(vdev, fbit))
return false;
dev_err(&vdev->dev, "device advertises feature %s but not %s",
fname, dname);
return true;
}
Commit Message: virtio-net: drop NETIF_F_FRAGLIST
virtio declares support for NETIF_F_FRAGLIST, but assumes
that there are at most MAX_SKB_FRAGS + 2 fragments which isn't
always true with a fraglist.
A longer fraglist in the skb will make the call to skb_to_sgvec overflow
the sg array, leading to memory corruption.
Drop NETIF_F_FRAGLIST so we only get what we can handle.
Cc: Michael S. Tsirkin <[email protected]>
Signed-off-by: Jason Wang <[email protected]>
Acked-by: Michael S. Tsirkin <[email protected]>
Signed-off-by: David S. Miller <[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 pppol2tp_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int val, len;
int err;
struct pppol2tp_session *ps;
if (level != SOL_PPPOL2TP)
return udp_prot.getsockopt(sk, level, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
err = -ENOTCONN;
if (sk->sk_user_data == NULL)
goto end;
/* Get the session context */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel */
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val);
sock_put(ps->tunnel_sock);
} else
err = pppol2tp_session_getsockopt(sk, session, optname, &val);
err = -EFAULT;
if (put_user(len, optlen))
goto end_put_sess;
if (copy_to_user((void __user *) optval, &val, len))
goto end_put_sess;
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
Commit Message: net/l2tp: don't fall back on UDP [get|set]sockopt
The l2tp [get|set]sockopt() code has fallen back to the UDP functions
for socket option levels != SOL_PPPOL2TP since day one, but that has
never actually worked, since the l2tp socket isn't an inet socket.
As David Miller points out:
"If we wanted this to work, it'd have to look up the tunnel and then
use tunnel->sk, but I wonder how useful that would be"
Since this can never have worked so nobody could possibly have depended
on that functionality, just remove the broken code and return -EINVAL.
Reported-by: Sasha Levin <[email protected]>
Acked-by: James Chapman <[email protected]>
Acked-by: David Miller <[email protected]>
Cc: Phil Turnbull <[email protected]>
Cc: Vegard Nossum <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
Target: 1
Example 2:
Code: bool ShouldRespondToRequest(blink::WebLocalFrame** frame_ptr,
RenderFrame** render_frame_ptr) {
blink::WebLocalFrame* frame = blink::WebLocalFrame::FrameForCurrentContext();
if (!frame || !frame->View())
return false;
GURL frame_url = frame->GetDocument().Url();
RenderFrame* render_frame = RenderFrame::FromWebFrame(frame);
if (!render_frame)
return false;
bool webui_enabled =
(render_frame->GetEnabledBindings() & BINDINGS_POLICY_WEB_UI) &&
(frame_url.SchemeIs(kChromeUIScheme) ||
frame_url.SchemeIs(url::kDataScheme));
if (!webui_enabled)
return false;
*frame_ptr = frame;
*render_frame_ptr = render_frame;
return true;
}
Commit Message: Validate frame after conversion in chrome.send
BUG=797511
TEST=Manually, see https://crbug.com/797511#c1
Change-Id: Ib1a99db4d7648fb1325eb6d7af4ef111d6dda4cb
Reviewed-on: https://chromium-review.googlesource.com/844076
Commit-Queue: Rob Wu <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#526197}
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: find_insert(png_const_charp what, png_charp param)
{
png_uint_32 chunk = 0;
png_charp parameter_list[1024];
int i, nparams;
/* Assemble the chunk name */
for (i=0; i<4; ++i)
{
char ch = what[i];
if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122))
chunk = (chunk << 8) + what[i];
else
break;
}
if (i < 4 || what[4] != 0)
{
fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what);
exit(1);
}
/* Assemble the parameter list. */
nparams = find_parameters(what, param, parameter_list, 1024);
# define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d))
switch (chunk)
{
case CHUNK(105,67,67,80): /* iCCP */
if (nparams == 2)
return make_insert(what, insert_iCCP, nparams, parameter_list);
break;
case CHUNK(116,69,88,116): /* tEXt */
if (nparams == 2)
return make_insert(what, insert_tEXt, nparams, parameter_list);
break;
case CHUNK(122,84,88,116): /* zTXt */
if (nparams == 2)
return make_insert(what, insert_zTXt, nparams, parameter_list);
break;
case CHUNK(105,84,88,116): /* iTXt */
if (nparams == 4)
return make_insert(what, insert_iTXt, nparams, parameter_list);
break;
case CHUNK(104,73,83,84): /* hIST */
if (nparams <= 256)
return make_insert(what, insert_hIST, nparams, parameter_list);
break;
#if 0
case CHUNK(115,80,76,84): /* sPLT */
return make_insert(what, insert_sPLT, nparams, parameter_list);
#endif
default:
fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n",
what);
exit(1);
}
bad_parameter_count(what, nparams);
return NULL;
}
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: Segment::Segment(
IMkvReader* pReader,
long long elem_start,
long long start,
long long size) :
m_pReader(pReader),
m_element_start(elem_start),
m_start(start),
m_size(size),
m_pos(start),
m_pUnknownSize(0),
m_pSeekHead(NULL),
m_pInfo(NULL),
m_pTracks(NULL),
m_pCues(NULL),
m_pChapters(NULL),
m_clusters(NULL),
m_clusterCount(0),
m_clusterPreloadCount(0),
m_clusterSize(0)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: void kgdb_arch_exit(void)
{
int i;
for (i = 0; i < 4; i++) {
if (breakinfo[i].pev) {
unregister_wide_hw_breakpoint(breakinfo[i].pev);
breakinfo[i].pev = NULL;
}
}
unregister_die_notifier(&kgdb_notifier);
}
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: int udhcpd_main(int argc UNUSED_PARAM, char **argv)
{
int server_socket = -1, retval;
uint8_t *state;
unsigned timeout_end;
unsigned num_ips;
unsigned opt;
struct option_set *option;
char *str_I = str_I;
const char *str_a = "2000";
unsigned arpping_ms;
IF_FEATURE_UDHCP_PORT(char *str_P;)
setup_common_bufsiz();
IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
opt = getopt32(argv, "^"
"fSI:va:"IF_FEATURE_UDHCP_PORT("P:")
"\0"
#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
"vv"
#endif
, &str_I
, &str_a
IF_FEATURE_UDHCP_PORT(, &str_P)
IF_UDHCP_VERBOSE(, &dhcp_verbose)
);
if (!(opt & 1)) { /* no -f */
bb_daemonize_or_rexec(0, argv);
logmode = LOGMODE_NONE;
}
/* update argv after the possible vfork+exec in daemonize */
argv += optind;
if (opt & 2) { /* -S */
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode |= LOGMODE_SYSLOG;
}
if (opt & 4) { /* -I */
len_and_sockaddr *lsa = xhost_and_af2sockaddr(str_I, 0, AF_INET);
server_config.server_nip = lsa->u.sin.sin_addr.s_addr;
free(lsa);
}
#if ENABLE_FEATURE_UDHCP_PORT
if (opt & 32) { /* -P */
SERVER_PORT = xatou16(str_P);
CLIENT_PORT = SERVER_PORT + 1;
}
#endif
arpping_ms = xatou(str_a);
/* Would rather not do read_config before daemonization -
* otherwise NOMMU machines will parse config twice */
read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
/* prevent poll timeout overflow */
if (server_config.auto_time > INT_MAX / 1000)
server_config.auto_time = INT_MAX / 1000;
/* Make sure fd 0,1,2 are open */
bb_sanitize_stdio();
/* Create pidfile */
write_pidfile(server_config.pidfile);
/* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
bb_error_msg("started, v"BB_VER);
option = udhcp_find_option(server_config.options, DHCP_LEASE_TIME);
server_config.max_lease_sec = DEFAULT_LEASE_TIME;
if (option) {
move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
}
/* Sanity check */
num_ips = server_config.end_ip - server_config.start_ip + 1;
if (server_config.max_leases > num_ips) {
bb_error_msg("max_leases=%u is too big, setting to %u",
(unsigned)server_config.max_leases, num_ips);
server_config.max_leases = num_ips;
}
/* this sets g_leases */
SET_PTR_TO_GLOBALS(xzalloc(server_config.max_leases * sizeof(g_leases[0])));
read_leases(server_config.lease_file);
if (udhcp_read_interface(server_config.interface,
&server_config.ifindex,
(server_config.server_nip == 0 ? &server_config.server_nip : NULL),
server_config.server_mac)
) {
retval = 1;
goto ret;
}
/* Setup the signal pipe */
udhcp_sp_setup();
continue_with_autotime:
timeout_end = monotonic_sec() + server_config.auto_time;
while (1) { /* loop until universe collapses */
struct pollfd pfds[2];
struct dhcp_packet packet;
int bytes;
int tv;
uint8_t *server_id_opt;
uint8_t *requested_ip_opt;
uint32_t requested_nip = requested_nip; /* for compiler */
uint32_t static_lease_nip;
struct dyn_lease *lease, fake_lease;
if (server_socket < 0) {
server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
server_config.interface);
}
udhcp_sp_fd_set(pfds, server_socket);
new_tv:
tv = -1;
if (server_config.auto_time) {
tv = timeout_end - monotonic_sec();
if (tv <= 0) {
write_leases:
write_leases();
goto continue_with_autotime;
}
tv *= 1000;
}
/* Block here waiting for either signal or packet */
retval = poll(pfds, 2, tv);
if (retval <= 0) {
if (retval == 0)
goto write_leases;
if (errno == EINTR)
goto new_tv;
/* < 0 and not EINTR: should not happen */
bb_perror_msg_and_die("poll");
}
if (pfds[0].revents) switch (udhcp_sp_read()) {
case SIGUSR1:
bb_error_msg("received %s", "SIGUSR1");
write_leases();
/* why not just reset the timeout, eh */
goto continue_with_autotime;
case SIGTERM:
bb_error_msg("received %s", "SIGTERM");
write_leases();
goto ret0;
}
/* Is it a packet? */
if (!pfds[1].revents)
continue; /* no */
/* Note: we do not block here, we block on poll() instead.
* Blocking here would prevent SIGTERM from working:
* socket read inside this call is restarted on caught signals.
*/
bytes = udhcp_recv_kernel_packet(&packet, server_socket);
if (bytes < 0) {
/* bytes can also be -2 ("bad packet data") */
if (bytes == -1 && errno != EINTR) {
log1("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
close(server_socket);
server_socket = -1;
}
continue;
}
if (packet.hlen != 6) {
bb_error_msg("MAC length != 6, ignoring packet");
continue;
}
if (packet.op != BOOTREQUEST) {
bb_error_msg("not a REQUEST, ignoring packet");
continue;
}
state = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE);
if (state == NULL || state[0] < DHCP_MINTYPE || state[0] > DHCP_MAXTYPE) {
bb_error_msg("no or bad message type option, ignoring packet");
continue;
}
/* Get SERVER_ID if present */
server_id_opt = udhcp_get_option(&packet, DHCP_SERVER_ID);
if (server_id_opt) {
uint32_t server_id_network_order;
move_from_unaligned32(server_id_network_order, server_id_opt);
if (server_id_network_order != server_config.server_nip) {
/* client talks to somebody else */
log1("server ID doesn't match, ignoring");
continue;
}
}
/* Look for a static/dynamic lease */
static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
if (static_lease_nip) {
bb_error_msg("found static lease: %x", static_lease_nip);
memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
fake_lease.lease_nip = static_lease_nip;
fake_lease.expires = 0;
lease = &fake_lease;
} else {
lease = find_lease_by_mac(packet.chaddr);
}
/* Get REQUESTED_IP if present */
requested_ip_opt = udhcp_get_option(&packet, DHCP_REQUESTED_IP);
if (requested_ip_opt) {
move_from_unaligned32(requested_nip, requested_ip_opt);
}
switch (state[0]) {
case DHCPDISCOVER:
log1("received %s", "DISCOVER");
send_offer(&packet, static_lease_nip, lease, requested_ip_opt, arpping_ms);
break;
case DHCPREQUEST:
log1("received %s", "REQUEST");
/* RFC 2131:
o DHCPREQUEST generated during SELECTING state:
Client inserts the address of the selected server in 'server
identifier', 'ciaddr' MUST be zero, 'requested IP address' MUST be
filled in with the yiaddr value from the chosen DHCPOFFER.
Note that the client may choose to collect several DHCPOFFER
messages and select the "best" offer. The client indicates its
selection by identifying the offering server in the DHCPREQUEST
message. If the client receives no acceptable offers, the client
may choose to try another DHCPDISCOVER message. Therefore, the
servers may not receive a specific DHCPREQUEST from which they can
decide whether or not the client has accepted the offer.
o DHCPREQUEST generated during INIT-REBOOT state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST be filled in with client's notion of its previously
assigned address. 'ciaddr' MUST be zero. The client is seeking to
verify a previously allocated, cached configuration. Server SHOULD
send a DHCPNAK message to the client if the 'requested IP address'
is incorrect, or is on the wrong network.
Determining whether a client in the INIT-REBOOT state is on the
correct network is done by examining the contents of 'giaddr', the
'requested IP address' option, and a database lookup. If the DHCP
server detects that the client is on the wrong net (i.e., the
result of applying the local subnet mask or remote subnet mask (if
'giaddr' is not zero) to 'requested IP address' option value
doesn't match reality), then the server SHOULD send a DHCPNAK
message to the client.
If the network is correct, then the DHCP server should check if
the client's notion of its IP address is correct. If not, then the
server SHOULD send a DHCPNAK message to the client. If the DHCP
server has no record of this client, then it MUST remain silent,
and MAY output a warning to the network administrator. This
behavior is necessary for peaceful coexistence of non-
communicating DHCP servers on the same wire.
If 'giaddr' is 0x0 in the DHCPREQUEST message, the client is on
the same subnet as the server. The server MUST broadcast the
DHCPNAK message to the 0xffffffff broadcast address because the
client may not have a correct network address or subnet mask, and
the client may not be answering ARP requests.
If 'giaddr' is set in the DHCPREQUEST message, the client is on a
different subnet. The server MUST set the broadcast bit in the
DHCPNAK, so that the relay agent will broadcast the DHCPNAK to the
client, because the client may not have a correct network address
or subnet mask, and the client may not be answering ARP requests.
o DHCPREQUEST generated during RENEWING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message will
be unicast, so no relay agents will be involved in its
transmission. Because 'giaddr' is therefore not filled in, the
DHCP server will trust the value in 'ciaddr', and use it when
replying to the client.
A client MAY choose to renew or extend its lease prior to T1. The
server may choose not to extend the lease (as a policy decision by
the network administrator), but should return a DHCPACK message
regardless.
o DHCPREQUEST generated during REBINDING state:
'server identifier' MUST NOT be filled in, 'requested IP address'
option MUST NOT be filled in, 'ciaddr' MUST be filled in with
client's IP address. In this situation, the client is completely
configured, and is trying to extend its lease. This message MUST
be broadcast to the 0xffffffff IP broadcast address. The DHCP
server SHOULD check 'ciaddr' for correctness before replying to
the DHCPREQUEST.
The DHCPREQUEST from a REBINDING client is intended to accommodate
sites that have multiple DHCP servers and a mechanism for
maintaining consistency among leases managed by multiple servers.
A DHCP server MAY extend a client's lease only if it has local
administrative authority to do so.
*/
if (!requested_ip_opt) {
requested_nip = packet.ciaddr;
if (requested_nip == 0) {
log1("no requested IP and no ciaddr, ignoring");
break;
}
}
if (lease && requested_nip == lease->lease_nip) {
/* client requested or configured IP matches the lease.
* ACK it, and bump lease expiration time. */
send_ACK(&packet, lease->lease_nip);
break;
}
/* No lease for this MAC, or lease IP != requested IP */
if (server_id_opt /* client is in SELECTING state */
|| requested_ip_opt /* client is in INIT-REBOOT state */
) {
/* "No, we don't have this IP for you" */
send_NAK(&packet);
} /* else: client is in RENEWING or REBINDING, do not answer */
break;
case DHCPDECLINE:
/* RFC 2131:
* "If the server receives a DHCPDECLINE message,
* the client has discovered through some other means
* that the suggested network address is already
* in use. The server MUST mark the network address
* as not available and SHOULD notify the local
* sysadmin of a possible configuration problem."
*
* SERVER_ID must be present,
* REQUESTED_IP must be present,
* chaddr must be filled in,
* ciaddr must be 0 (we do not check this)
*/
log1("received %s", "DECLINE");
if (server_id_opt
&& requested_ip_opt
&& lease /* chaddr matches this lease */
&& requested_nip == lease->lease_nip
) {
memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
lease->expires = time(NULL) + server_config.decline_time;
}
break;
case DHCPRELEASE:
/* "Upon receipt of a DHCPRELEASE message, the server
* marks the network address as not allocated."
*
* SERVER_ID must be present,
* REQUESTED_IP must not be present (we do not check this),
* chaddr must be filled in,
* ciaddr must be filled in
*/
log1("received %s", "RELEASE");
if (server_id_opt
&& lease /* chaddr matches this lease */
&& packet.ciaddr == lease->lease_nip
) {
lease->expires = time(NULL);
}
break;
case DHCPINFORM:
log1("received %s", "INFORM");
send_inform(&packet);
break;
}
}
ret0:
retval = 0;
ret:
/*if (server_config.pidfile) - server_config.pidfile is never NULL */
remove_pidfile(server_config.pidfile);
return retval;
}
Commit Message:
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 Maybe<int64_t> IndexOfValueImpl(Isolate* isolate,
Handle<JSObject> object,
Handle<Object> value,
uint32_t start_from, uint32_t length) {
DCHECK(JSObject::PrototypeHasNoElements(isolate, *object));
Handle<Map> original_map = handle(object->map(), isolate);
Handle<FixedArray> parameter_map(FixedArray::cast(object->elements()),
isolate);
for (uint32_t k = start_from; k < length; ++k) {
uint32_t entry = GetEntryForIndexImpl(isolate, *object, *parameter_map, k,
ALL_PROPERTIES);
if (entry == kMaxUInt32) {
continue;
}
Handle<Object> element_k =
Subclass::GetImpl(isolate, *parameter_map, entry);
if (element_k->IsAccessorPair()) {
LookupIterator it(isolate, object, k, LookupIterator::OWN);
DCHECK(it.IsFound());
DCHECK_EQ(it.state(), LookupIterator::ACCESSOR);
ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, element_k,
Object::GetPropertyWithAccessor(&it),
Nothing<int64_t>());
if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
if (object->map() != *original_map) {
return IndexOfValueSlowPath(isolate, object, value, k + 1, length);
}
} else if (value->StrictEquals(*element_k)) {
return Just<int64_t>(k);
}
}
return Just<int64_t>(-1);
}
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: static int snd_seq_open(struct inode *inode, struct file *file)
{
int c, mode; /* client id */
struct snd_seq_client *client;
struct snd_seq_user_client *user;
int err;
err = nonseekable_open(inode, file);
if (err < 0)
return err;
if (mutex_lock_interruptible(®ister_mutex))
return -ERESTARTSYS;
client = seq_create_client1(-1, SNDRV_SEQ_DEFAULT_EVENTS);
if (client == NULL) {
mutex_unlock(®ister_mutex);
return -ENOMEM; /* failure code */
}
mode = snd_seq_file_flags(file);
if (mode & SNDRV_SEQ_LFLG_INPUT)
client->accept_input = 1;
if (mode & SNDRV_SEQ_LFLG_OUTPUT)
client->accept_output = 1;
user = &client->data.user;
user->fifo = NULL;
user->fifo_pool_size = 0;
if (mode & SNDRV_SEQ_LFLG_INPUT) {
user->fifo_pool_size = SNDRV_SEQ_DEFAULT_CLIENT_EVENTS;
user->fifo = snd_seq_fifo_new(user->fifo_pool_size);
if (user->fifo == NULL) {
seq_free_client1(client);
kfree(client);
mutex_unlock(®ister_mutex);
return -ENOMEM;
}
}
usage_alloc(&client_usage, 1);
client->type = USER_CLIENT;
mutex_unlock(®ister_mutex);
c = client->number;
file->private_data = client;
/* fill client data */
user->file = file;
sprintf(client->name, "Client-%d", c);
client->data.user.owner = get_pid(task_pid(current));
/* make others aware this new client */
snd_seq_system_client_ev_client_start(c);
return 0;
}
Commit Message: ALSA: seq: Fix use-after-free at creating a port
There is a potential race window opened at creating and deleting a
port via ioctl, as spotted by fuzzing. snd_seq_create_port() creates
a port object and returns its pointer, but it doesn't take the
refcount, thus it can be deleted immediately by another thread.
Meanwhile, snd_seq_ioctl_create_port() still calls the function
snd_seq_system_client_ev_port_start() with the created port object
that is being deleted, and this triggers use-after-free like:
BUG: KASAN: use-after-free in snd_seq_ioctl_create_port+0x504/0x630 [snd_seq] at addr ffff8801f2241cb1
=============================================================================
BUG kmalloc-512 (Tainted: G B ): kasan: bad access detected
-----------------------------------------------------------------------------
INFO: Allocated in snd_seq_create_port+0x94/0x9b0 [snd_seq] age=1 cpu=3 pid=4511
___slab_alloc+0x425/0x460
__slab_alloc+0x20/0x40
kmem_cache_alloc_trace+0x150/0x190
snd_seq_create_port+0x94/0x9b0 [snd_seq]
snd_seq_ioctl_create_port+0xd1/0x630 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
INFO: Freed in port_delete+0x136/0x1a0 [snd_seq] age=1 cpu=2 pid=4717
__slab_free+0x204/0x310
kfree+0x15f/0x180
port_delete+0x136/0x1a0 [snd_seq]
snd_seq_delete_port+0x235/0x350 [snd_seq]
snd_seq_ioctl_delete_port+0xc8/0x180 [snd_seq]
snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
snd_seq_ioctl+0x40/0x80 [snd_seq]
do_vfs_ioctl+0x54b/0xda0
SyS_ioctl+0x79/0x90
entry_SYSCALL_64_fastpath+0x16/0x75
Call Trace:
[<ffffffff81b03781>] dump_stack+0x63/0x82
[<ffffffff81531b3b>] print_trailer+0xfb/0x160
[<ffffffff81536db4>] object_err+0x34/0x40
[<ffffffff815392d3>] kasan_report.part.2+0x223/0x520
[<ffffffffa07aadf4>] ? snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffff815395fe>] __asan_report_load1_noabort+0x2e/0x30
[<ffffffffa07aadf4>] snd_seq_ioctl_create_port+0x504/0x630 [snd_seq]
[<ffffffffa07aa8f0>] ? snd_seq_ioctl_delete_port+0x180/0x180 [snd_seq]
[<ffffffff8136be50>] ? taskstats_exit+0xbc0/0xbc0
[<ffffffffa07abc5c>] snd_seq_do_ioctl+0x11c/0x190 [snd_seq]
[<ffffffffa07abd10>] snd_seq_ioctl+0x40/0x80 [snd_seq]
[<ffffffff8136d433>] ? acct_account_cputime+0x63/0x80
[<ffffffff815b515b>] do_vfs_ioctl+0x54b/0xda0
.....
We may fix this in a few different ways, and in this patch, it's fixed
simply by taking the refcount properly at snd_seq_create_port() and
letting the caller unref the object after use. Also, there is another
potential use-after-free by sprintf() call in snd_seq_create_port(),
and this is moved inside the lock.
This fix covers CVE-2017-15265.
Reported-and-tested-by: Michael23 Yu <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[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: static struct vrend_linked_shader_program *add_shader_program(struct vrend_context *ctx,
struct vrend_shader *vs,
struct vrend_shader *fs,
struct vrend_shader *gs)
{
struct vrend_linked_shader_program *sprog = CALLOC_STRUCT(vrend_linked_shader_program);
char name[16];
int i;
GLuint prog_id;
GLint lret;
int id;
int last_shader;
if (!sprog)
return NULL;
/* need to rewrite VS code to add interpolation params */
if ((gs && gs->compiled_fs_id != fs->id) ||
(!gs && vs->compiled_fs_id != fs->id)) {
bool ret;
if (gs)
vrend_patch_vertex_shader_interpolants(gs->glsl_prog,
&gs->sel->sinfo,
&fs->sel->sinfo, true, fs->key.flatshade);
else
vrend_patch_vertex_shader_interpolants(vs->glsl_prog,
&vs->sel->sinfo,
&fs->sel->sinfo, false, fs->key.flatshade);
ret = vrend_compile_shader(ctx, gs ? gs : vs);
if (ret == false) {
glDeleteShader(gs ? gs->id : vs->id);
free(sprog);
return NULL;
}
if (gs)
gs->compiled_fs_id = fs->id;
else
vs->compiled_fs_id = fs->id;
}
prog_id = glCreateProgram();
glAttachShader(prog_id, vs->id);
if (gs) {
if (gs->id > 0)
glAttachShader(prog_id, gs->id);
set_stream_out_varyings(prog_id, &gs->sel->sinfo);
}
else
set_stream_out_varyings(prog_id, &vs->sel->sinfo);
glAttachShader(prog_id, fs->id);
if (fs->sel->sinfo.num_outputs > 1) {
if (util_blend_state_is_dual(&ctx->sub->blend_state, 0)) {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 0, 1, "fsout_c1");
sprog->dual_src_linked = true;
} else {
glBindFragDataLocationIndexed(prog_id, 0, 0, "fsout_c0");
glBindFragDataLocationIndexed(prog_id, 1, 0, "fsout_c1");
sprog->dual_src_linked = false;
}
} else
sprog->dual_src_linked = false;
if (vrend_state.have_vertex_attrib_binding) {
uint32_t mask = vs->sel->sinfo.attrib_input_mask;
while (mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "in_%d", i);
glBindAttribLocation(prog_id, i, name);
}
}
glLinkProgram(prog_id);
glGetProgramiv(prog_id, GL_LINK_STATUS, &lret);
if (lret == GL_FALSE) {
char infolog[65536];
int len;
glGetProgramInfoLog(prog_id, 65536, &len, infolog);
fprintf(stderr,"got error linking\n%s\n", infolog);
/* dump shaders */
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_SHADER, 0);
fprintf(stderr,"vert shader: %d GLSL\n%s\n", vs->id, vs->glsl_prog);
if (gs)
fprintf(stderr,"geom shader: %d GLSL\n%s\n", gs->id, gs->glsl_prog);
fprintf(stderr,"frag shader: %d GLSL\n%s\n", fs->id, fs->glsl_prog);
glDeleteProgram(prog_id);
return NULL;
}
sprog->ss[PIPE_SHADER_FRAGMENT] = fs;
sprog->ss[PIPE_SHADER_GEOMETRY] = gs;
list_add(&sprog->sl[PIPE_SHADER_VERTEX], &vs->programs);
list_add(&sprog->sl[PIPE_SHADER_FRAGMENT], &fs->programs);
if (gs)
list_add(&sprog->sl[PIPE_SHADER_GEOMETRY], &gs->programs);
last_shader = gs ? PIPE_SHADER_GEOMETRY : PIPE_SHADER_FRAGMENT;
sprog->id = prog_id;
list_addtail(&sprog->head, &ctx->sub->programs);
if (fs->key.pstipple_tex)
sprog->fs_stipple_loc = glGetUniformLocation(prog_id, "pstipple_sampler");
else
sprog->fs_stipple_loc = -1;
sprog->vs_ws_adjust_loc = glGetUniformLocation(prog_id, "winsys_adjust");
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.samplers_used_mask) {
uint32_t mask = sprog->ss[id]->sel->sinfo.samplers_used_mask;
int nsamp = util_bitcount(sprog->ss[id]->sel->sinfo.samplers_used_mask);
int index;
sprog->shadow_samp_mask[id] = sprog->ss[id]->sel->sinfo.shadow_samp_mask;
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask) {
sprog->shadow_samp_mask_locs[id] = calloc(nsamp, sizeof(uint32_t));
sprog->shadow_samp_add_locs[id] = calloc(nsamp, sizeof(uint32_t));
} else {
sprog->shadow_samp_mask_locs[id] = sprog->shadow_samp_add_locs[id] = NULL;
}
sprog->samp_locs[id] = calloc(nsamp, sizeof(uint32_t));
if (sprog->samp_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
index = 0;
while(mask) {
i = u_bit_scan(&mask);
snprintf(name, 10, "%ssamp%d", prefix, i);
sprog->samp_locs[id][index] = glGetUniformLocation(prog_id, name);
if (sprog->ss[id]->sel->sinfo.shadow_samp_mask & (1 << i)) {
snprintf(name, 14, "%sshadmask%d", prefix, i);
sprog->shadow_samp_mask_locs[id][index] = glGetUniformLocation(prog_id, name);
snprintf(name, 14, "%sshadadd%d", prefix, i);
sprog->shadow_samp_add_locs[id][index] = glGetUniformLocation(prog_id, name);
}
index++;
}
}
} else {
sprog->samp_locs[id] = NULL;
sprog->shadow_samp_mask_locs[id] = NULL;
sprog->shadow_samp_add_locs[id] = NULL;
sprog->shadow_samp_mask[id] = 0;
}
sprog->samplers_used_mask[id] = sprog->ss[id]->sel->sinfo.samplers_used_mask;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_consts) {
sprog->const_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_consts, sizeof(uint32_t));
if (sprog->const_locs[id]) {
const char *prefix = pipe_shader_to_prefix(id);
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_consts; i++) {
snprintf(name, 16, "%sconst0[%d]", prefix, i);
sprog->const_locs[id][i] = glGetUniformLocation(prog_id, name);
}
}
} else
sprog->const_locs[id] = NULL;
}
if (!vrend_state.have_vertex_attrib_binding) {
if (vs->sel->sinfo.num_inputs) {
sprog->attrib_locs = calloc(vs->sel->sinfo.num_inputs, sizeof(uint32_t));
if (sprog->attrib_locs) {
for (i = 0; i < vs->sel->sinfo.num_inputs; i++) {
snprintf(name, 10, "in_%d", i);
sprog->attrib_locs[i] = glGetAttribLocation(prog_id, name);
}
}
} else
sprog->attrib_locs = NULL;
}
for (id = PIPE_SHADER_VERTEX; id <= last_shader; id++) {
if (sprog->ss[id]->sel->sinfo.num_ubos) {
const char *prefix = pipe_shader_to_prefix(id);
sprog->ubo_locs[id] = calloc(sprog->ss[id]->sel->sinfo.num_ubos, sizeof(uint32_t));
for (i = 0; i < sprog->ss[id]->sel->sinfo.num_ubos; i++) {
snprintf(name, 16, "%subo%d", prefix, i + 1);
sprog->ubo_locs[id][i] = glGetUniformBlockIndex(prog_id, name);
}
} else
sprog->ubo_locs[id] = NULL;
}
if (vs->sel->sinfo.num_ucp) {
for (i = 0; i < vs->sel->sinfo.num_ucp; i++) {
snprintf(name, 10, "clipp[%d]", i);
sprog->clip_locs[i] = glGetUniformLocation(prog_id, name);
}
}
return sprog;
}
Commit Message:
CWE ID: CWE-772
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: SoftAACEncoder::~SoftAACEncoder() {
delete[] mInputFrame;
mInputFrame = NULL;
if (mEncoderHandle) {
CHECK_EQ(VO_ERR_NONE, mApiHandle->Uninit(mEncoderHandle));
mEncoderHandle = NULL;
}
delete mApiHandle;
mApiHandle = NULL;
delete mMemOperator;
mMemOperator = NULL;
}
Commit Message: codecs: handle onReset() for a few encoders
Test: Run PoC binaries
Bug: 34749392
Bug: 34705519
Change-Id: I3356eb615b0e79272d71d72578d363671038c6dd
CWE ID:
Target: 1
Example 2:
Code: struct sk_buff *napi_frags_skb(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
struct ethhdr *eth;
unsigned int hlen;
unsigned int off;
napi->skb = NULL;
skb_reset_mac_header(skb);
skb_gro_reset_offset(skb);
off = skb_gro_offset(skb);
hlen = off + sizeof(*eth);
eth = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
eth = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!eth)) {
napi_reuse_skb(napi, skb);
skb = NULL;
goto out;
}
}
skb_gro_pull(skb, sizeof(*eth));
/*
* This works because the only protocols we care about don't require
* special handling. We'll fix it up properly at the end.
*/
skb->protocol = eth->h_proto;
out:
return skb;
}
Commit Message: veth: Dont kfree_skb() after dev_forward_skb()
In case of congestion, netif_rx() frees the skb, so we must assume
dev_forward_skb() also consume skb.
Bug introduced by commit 445409602c092
(veth: move loopback logic to common location)
We must change dev_forward_skb() to always consume skb, and veth to not
double free it.
Bug report : http://marc.info/?l=linux-netdev&m=127310770900442&w=3
Reported-by: Martín Ferrari <[email protected]>
Signed-off-by: Eric Dumazet <[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: unsigned int count_swap_pages(int type, int free)
{
unsigned int n = 0;
spin_lock(&swap_lock);
if ((unsigned int)type < nr_swapfiles) {
struct swap_info_struct *sis = swap_info[type];
if (sis->flags & SWP_WRITEOK) {
n = sis->pages;
if (free)
n -= sis->inuse_pages;
}
}
spin_unlock(&swap_lock);
return n;
}
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: void WebGL2RenderingContextBase::texSubImage3D(
GLenum target,
GLint level,
GLint xoffset,
GLint yoffset,
GLint zoffset,
GLsizei width,
GLsizei height,
GLsizei depth,
GLenum format,
GLenum type,
MaybeShared<DOMArrayBufferView> pixels,
GLuint src_offset) {
if (isContextLost())
return;
if (bound_pixel_unpack_buffer_) {
SynthesizeGLError(GL_INVALID_OPERATION, "texSubImage3D",
"a buffer is bound to PIXEL_UNPACK_BUFFER");
return;
}
TexImageHelperDOMArrayBufferView(
kTexSubImage3D, target, level, 0, width, height, depth, 0, format, type,
xoffset, yoffset, zoffset, pixels.View(), kNullNotReachable, src_offset);
}
Commit Message: Implement 2D texture uploading from client array with FLIP_Y or PREMULTIPLY_ALPHA.
BUG=774174
TEST=https://github.com/KhronosGroup/WebGL/pull/2555
[email protected]
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2;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: I4f4e7636314502451104730501a5048a5d7b9f3f
Reviewed-on: https://chromium-review.googlesource.com/808665
Commit-Queue: Zhenyao Mo <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522003}
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void swaplist(node_t *node1, node_t *node2) {
node_t *par1;
par1 = node1->next;
node1->next = node2->next;
node2->next = par1;
par1 = node1->prev;
node1->prev = node2->prev;
node2->prev = par1;
if (node1->next == node1) {
node1->next = node2;
}
if (node2->next == node2) {
node2->next = node1;
}
if (node1->next) {
node1->next->prev = node1;
}
if (node2->next) {
node2->next->prev = node2;
}
if (node1->prev) {
node1->prev->next = node1;
}
if (node2->prev) {
node2->prev->next = node2;
}
}
Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits
Prevent reading past end of message in MSG_ReadBits. If read past
end of msg->data buffer (16348 bytes) the engine could SEGFAULT.
Make MSG_WriteBits use an exact buffer overflow check instead of
possibly failing with a few bytes left.
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 suffix_object( cJSON *prev, cJSON *item )
{
prev->next = item;
item->prev = prev;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
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 ResourceDispatcherHostImpl::BeginRequest(
int request_id,
const ResourceHostMsg_Request& request_data,
IPC::Message* sync_result, // only valid for sync
int route_id) {
int process_type = filter_->process_type();
int child_id = filter_->child_id();
if (IsBrowserSideNavigationEnabled() &&
IsResourceTypeFrame(request_data.resource_type) &&
!request_data.url.SchemeIs(url::kBlobScheme)) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_URL);
return;
}
if (request_data.priority < net::MINIMUM_PRIORITY ||
request_data.priority > net::MAXIMUM_PRIORITY) {
bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY);
return;
}
char url_buf[128];
base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf));
base::debug::Alias(url_buf);
LoaderMap::iterator it = pending_loaders_.find(
GlobalRequestID(request_data.transferred_request_child_id,
request_data.transferred_request_request_id));
if (it != pending_loaders_.end()) {
if (it->second->is_transferring()) {
ResourceLoader* deferred_loader = it->second.get();
UpdateRequestForTransfer(child_id, route_id, request_id,
request_data, it);
deferred_loader->CompleteTransfer();
} else {
bad_message::ReceivedBadMessage(
filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING);
}
return;
}
ResourceContext* resource_context = NULL;
net::URLRequestContext* request_context = NULL;
filter_->GetContexts(request_data.resource_type, request_data.origin_pid,
&resource_context, &request_context);
CHECK(ContainsKey(active_resource_contexts_, resource_context));
net::HttpRequestHeaders headers;
headers.AddHeadersFromString(request_data.headers);
if (is_shutdown_ ||
!ShouldServiceRequest(process_type, child_id, request_data, headers,
filter_, resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method,
request_data.url,
request_data.resource_type,
resource_context)) {
AbortRequestBeforeItStarts(filter_, sync_result, request_id);
return;
}
scoped_ptr<net::URLRequest> new_request = request_context->CreateRequest(
request_data.url, request_data.priority, NULL);
new_request->set_method(request_data.method);
new_request->set_first_party_for_cookies(
request_data.first_party_for_cookies);
new_request->set_initiator(request_data.request_initiator);
if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) {
new_request->set_first_party_url_policy(
net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
}
const Referrer referrer(request_data.referrer, request_data.referrer_policy);
SetReferrerForRequest(new_request.get(), referrer);
new_request->SetExtraRequestHeaders(headers);
storage::BlobStorageContext* blob_context =
GetBlobStorageContext(filter_->blob_storage_context());
if (request_data.request_body.get()) {
if (blob_context) {
AttachRequestBodyBlobDataHandles(
request_data.request_body.get(),
blob_context);
}
new_request->set_upload(UploadDataStreamBuilder::Build(
request_data.request_body.get(),
blob_context,
filter_->file_system_context(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE)
.get()));
}
bool allow_download = request_data.allow_download &&
IsResourceTypeFrame(request_data.resource_type);
bool do_not_prompt_for_login = request_data.do_not_prompt_for_login;
bool is_sync_load = sync_result != NULL;
ChildProcessSecurityPolicyImpl* policy =
ChildProcessSecurityPolicyImpl::GetInstance();
bool report_raw_headers = request_data.report_raw_headers;
if (report_raw_headers && !policy->CanReadRawCookies(child_id)) {
VLOG(1) << "Denied unauthorized request for raw headers";
report_raw_headers = false;
}
int load_flags =
BuildLoadFlagsForRequest(request_data, child_id, is_sync_load);
if (request_data.resource_type == RESOURCE_TYPE_PREFETCH ||
request_data.resource_type == RESOURCE_TYPE_FAVICON) {
do_not_prompt_for_login = true;
}
if (request_data.resource_type == RESOURCE_TYPE_IMAGE &&
HTTP_AUTH_RELATION_BLOCKED_CROSS ==
HttpAuthRelationTypeOf(request_data.url,
request_data.first_party_for_cookies)) {
do_not_prompt_for_login = true;
load_flags |= net::LOAD_DO_NOT_USE_EMBEDDED_IDENTITY;
}
bool support_async_revalidation =
!is_sync_load && async_revalidation_manager_ &&
AsyncRevalidationManager::QualifiesForAsyncRevalidation(request_data);
if (support_async_revalidation)
load_flags |= net::LOAD_SUPPORT_ASYNC_REVALIDATION;
if (is_sync_load) {
DCHECK_EQ(request_data.priority, net::MAXIMUM_PRIORITY);
DCHECK_NE(load_flags & net::LOAD_IGNORE_LIMITS, 0);
} else {
DCHECK_EQ(load_flags & net::LOAD_IGNORE_LIMITS, 0);
}
new_request->SetLoadFlags(load_flags);
ResourceRequestInfoImpl* extra_info = new ResourceRequestInfoImpl(
process_type, child_id, route_id,
-1, // frame_tree_node_id
request_data.origin_pid, request_id, request_data.render_frame_id,
request_data.is_main_frame, request_data.parent_is_main_frame,
request_data.resource_type, request_data.transition_type,
request_data.should_replace_current_entry,
false, // is download
false, // is stream
allow_download, request_data.has_user_gesture,
request_data.enable_load_timing, request_data.enable_upload_progress,
do_not_prompt_for_login, request_data.referrer_policy,
request_data.visiblity_state, resource_context, filter_->GetWeakPtr(),
report_raw_headers, !is_sync_load,
IsUsingLoFi(request_data.lofi_state, delegate_, *new_request,
resource_context,
request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME),
support_async_revalidation ? request_data.headers : std::string());
extra_info->AssociateWithRequest(new_request.get());
if (new_request->url().SchemeIs(url::kBlobScheme)) {
storage::BlobProtocolHandler::SetRequestedBlobDataHandle(
new_request.get(),
filter_->blob_storage_context()->context()->GetBlobDataFromPublicURL(
new_request->url()));
}
const bool should_skip_service_worker =
request_data.skip_service_worker || is_sync_load;
ServiceWorkerRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures)) {
ForeignFetchRequestHandler::InitializeHandler(
new_request.get(), filter_->service_worker_context(), blob_context,
child_id, request_data.service_worker_provider_id,
should_skip_service_worker,
request_data.fetch_request_mode, request_data.fetch_credentials_mode,
request_data.fetch_redirect_mode, request_data.resource_type,
request_data.fetch_request_context_type, request_data.fetch_frame_type,
request_data.request_body);
}
AppCacheInterceptor::SetExtraRequestInfo(
new_request.get(), filter_->appcache_service(), child_id,
request_data.appcache_host_id, request_data.resource_type,
request_data.should_reset_appcache);
scoped_ptr<ResourceHandler> handler(
CreateResourceHandler(
new_request.get(),
request_data, sync_result, route_id, process_type, child_id,
resource_context));
if (handler)
BeginRequestInternal(std::move(new_request), std::move(handler));
}
Commit Message: Block a compromised renderer from reusing request ids.
BUG=578882
Review URL: https://codereview.chromium.org/1608573002
Cr-Commit-Position: refs/heads/master@{#372547}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static void update_avg(u64 *avg, u64 sample)
{
s64 diff = sample - *avg;
*avg += diff >> 3;
}
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: static struct task_struct *find_new_reaper(struct task_struct *father,
struct task_struct *child_reaper)
{
struct task_struct *thread, *reaper;
thread = find_alive_thread(father);
if (thread)
return thread;
if (father->signal->has_child_subreaper) {
unsigned int ns_level = task_pid(father)->level;
/*
* Find the first ->is_child_subreaper ancestor in our pid_ns.
* We can't check reaper != child_reaper to ensure we do not
* cross the namespaces, the exiting parent could be injected
* by setns() + fork().
* We check pid->level, this is slightly more efficient than
* task_active_pid_ns(reaper) != task_active_pid_ns(father).
*/
for (reaper = father->real_parent;
task_pid(reaper)->level == ns_level;
reaper = reaper->real_parent) {
if (reaper == &init_task)
break;
if (!reaper->signal->is_child_subreaper)
continue;
thread = find_alive_thread(reaper);
if (thread)
return thread;
}
}
return child_reaper;
}
Commit Message: fix infoleak in waitid(2)
kernel_waitid() can return a PID, an error or 0. rusage is filled in the first
case and waitid(2) rusage should've been copied out exactly in that case, *not*
whenever kernel_waitid() has not returned an error. Compat variant shares that
braino; none of kernel_wait4() callers do, so the below ought to fix it.
Reported-and-tested-by: Alexander Potapenko <[email protected]>
Fixes: ce72a16fa705 ("wait4(2)/waitid(2): separate copying rusage to userland")
Cc: [email protected] # v4.13
Signed-off-by: Al Viro <[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: GDataDirectory::GDataDirectory(GDataDirectory* parent,
GDataDirectoryService* directory_service)
: GDataEntry(parent, directory_service) {
file_info_.is_directory = true;
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int parse_number_sign(const char *input, char **endptr, int *sign)
{
int sign_ = 1;
while (i_isspace(*input))
input++;
if (*input == '-') {
sign_ = -sign_;
input++;
}
*sign = sign_;
*endptr = (char *) input;
return TRUE;
}
Commit Message: Merge branch 'security' into 'master'
Security
Closes #10
See merge request !17
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 struct node* acquire_or_create_child_locked(
struct fuse* fuse, struct node* parent,
const char* name, const char* actual_name)
{
struct node* child = lookup_child_by_name_locked(parent, name);
if (child) {
acquire_node_locked(child);
} else {
child = create_node_locked(fuse, parent, name, actual_name);
}
return child;
}
Commit Message: Fix overflow in path building
An incorrect size was causing an unsigned value
to wrap, causing it to write past the end of
the buffer.
Bug: 28085658
Change-Id: Ie9625c729cca024d514ba2880ff97209d435a165
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: v8::Local<v8::Value> PrivateScriptRunner::runDOMMethod(ScriptState* scriptState, ScriptState* scriptStateInUserScript, const char* className, const char* methodName, v8::Local<v8::Value> holder, int argc, v8::Local<v8::Value> argv[])
{
v8::Local<v8::Object> classObject = classObjectOfPrivateScript(scriptState, className);
v8::Local<v8::Value> method;
if (!classObject->Get(scriptState->context(), v8String(scriptState->isolate(), methodName)).ToLocal(&method) || !method->IsFunction()) {
fprintf(stderr, "Private script error: Target DOM method was not found. (Class name = %s, Method name = %s)\n", className, methodName);
RELEASE_NOTREACHED();
}
initializeHolderIfNeeded(scriptState, classObject, holder);
v8::TryCatch block(scriptState->isolate());
v8::Local<v8::Value> result;
if (!V8ScriptRunner::callFunction(v8::Local<v8::Function>::Cast(method), scriptState->getExecutionContext(), holder, argc, argv, scriptState->isolate()).ToLocal(&result)) {
rethrowExceptionInPrivateScript(scriptState->isolate(), block, scriptStateInUserScript, ExceptionState::ExecutionContext, methodName, className);
block.ReThrow();
return v8::Local<v8::Value>();
}
return result;
}
Commit Message: Blink-in-JS should not run micro tasks
If Blink-in-JS runs micro tasks, there's a risk of causing a UXSS bug
(see 645211 for concrete steps).
This CL makes Blink-in-JS use callInternalFunction (instead of callFunction)
to avoid running micro tasks after Blink-in-JS' callbacks.
BUG=645211
Review-Url: https://codereview.chromium.org/2330843002
Cr-Commit-Position: refs/heads/master@{#417874}
CWE ID: CWE-79
Target: 1
Example 2:
Code: static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert)
{
int dashStep = *dashStepP;
int on = *onP;
int w, wstart;
dashStep++;
if (dashStep == gdDashSize) {
dashStep = 0;
on = !on;
}
if (on) {
if (vert) {
wstart = y - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, x, w, color);
}
} else {
wstart = x - wid / 2;
for (w = wstart; w < wstart + wid; w++) {
gdImageSetPixel(im, w, y, color);
}
}
}
*dashStepP = dashStep;
*onP = on;
}
Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow
CWE ID: CWE-190
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: ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
{
trace_sched_wakeup(p, true);
check_preempt_curr(rq, p, wake_flags);
p->state = TASK_RUNNING;
#ifdef CONFIG_SMP
if (p->sched_class->task_woken)
p->sched_class->task_woken(rq, p);
if (unlikely(rq->idle_stamp)) {
u64 delta = rq->clock - rq->idle_stamp;
u64 max = 2*sysctl_sched_migration_cost;
if (delta > max)
rq->avg_idle = max;
else
update_avg(&rq->avg_idle, delta);
rq->idle_stamp = 0;
}
#endif
}
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
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 *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image *image, *image2=NULL,
*rotated_image;
PixelPacket *q;
unsigned int status;
MATHeader MATLAB_HDR;
size_t size;
size_t CellType;
QuantumInfo *quantum_info;
ImageInfo *clone_info;
int i;
ssize_t ldblk;
unsigned char *BImgBuff = NULL;
double MinVal, MaxVal;
size_t Unknown6;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
BlobInfo *blob;
size_t one;
unsigned int (*ReadBlobXXXLong)(Image *image);
unsigned short (*ReadBlobXXXShort)(Image *image);
void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data);
void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data);
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info);
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
clone_info=CloneImageInfo(image_info);
if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image2=ReadMATImageV4(image_info,image,exception);
if (image2 == NULL)
goto MATLAB_KO;
image=image2;
goto END_OF_READING;
}
MATLAB_HDR.Version = ReadBlobLSBShort(image);
if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c",
MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]);
if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2))
{
ReadBlobXXXLong = ReadBlobLSBLong;
ReadBlobXXXShort = ReadBlobLSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesLSB;
ReadBlobFloatsXXX = ReadBlobFloatsLSB;
image->endian = LSBEndian;
}
else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2))
{
ReadBlobXXXLong = ReadBlobMSBLong;
ReadBlobXXXShort = ReadBlobMSBShort;
ReadBlobDoublesXXX = ReadBlobDoublesMSB;
ReadBlobFloatsXXX = ReadBlobFloatsMSB;
image->endian = MSBEndian;
}
else
goto MATLAB_KO; /* unsupported endian */
if (strncmp(MATLAB_HDR.identific, "MATLAB", 6))
MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader");
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
(void) SeekBlob(image,filepos,SEEK_SET);
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
filepos += MATLAB_HDR.ObjectSize + 4 + 4;
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception);
if(image2==NULL) continue;
MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */
}
#endif
if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */
MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2);
MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2);
MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF;
MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF;
MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2);
if(image!=image2)
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */
MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2);
MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeX = ReadBlobXXXLong(image2);
MATLAB_HDR.SizeY = ReadBlobXXXLong(image2);
switch(MATLAB_HDR.DimFlag)
{
case 8: z2=z=1; break; /* 2D matrix*/
case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/
Unknown6 = ReadBlobXXXLong(image2);
(void) Unknown6;
if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
Frames = ReadBlobXXXLong(image2);
break;
default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported");
}
MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2);
MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2);
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass);
if (MATLAB_HDR.StructureClass != mxCHAR_CLASS &&
MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */
MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */
MATLAB_HDR.StructureClass != mxINT8_CLASS &&
MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */
MATLAB_HDR.StructureClass != mxINT16_CLASS &&
MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */
MATLAB_HDR.StructureClass != mxINT32_CLASS &&
MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */
MATLAB_HDR.StructureClass != mxINT64_CLASS &&
MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (ssize_t) ((size + 3 + 1) / 4);
(void) SeekBlob(image2, size, SEEK_CUR);
break;
case 1:
case 2:
case 3:
case 4:
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */
break;
default:
goto MATLAB_KO;
}
CellType = ReadBlobXXXLong(image2); /* Additional object type */
if (logging)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"MATLAB_HDR.CellType: %.20g",(double) CellType);
(void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */
NEXT_FRAME:
switch (CellType)
{
case miINT8:
case miUINT8:
sample_size = 8;
if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL)
image->depth = 1;
else
image->depth = 8; /* Byte type cell */
ldblk = (ssize_t) MATLAB_HDR.SizeX;
break;
case miINT16:
case miUINT16:
sample_size = 16;
image->depth = 16; /* Word type cell */
ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX);
break;
case miINT32:
case miUINT32:
sample_size = 32;
image->depth = 32; /* Dword type cell */
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miINT64:
case miUINT64:
sample_size = 64;
image->depth = 64; /* Qword type cell */
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
case miSINGLE:
sample_size = 32;
image->depth = 32; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex float type cell */
}
ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX);
break;
case miDOUBLE:
sample_size = 64;
image->depth = 64; /* double type cell */
(void) SetImageOption(clone_info,"quantum:format","floating-point");
DisableMSCWarning(4127)
if (sizeof(double) != 8)
RestoreMSCWarning
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
one=1;
image->colors = one << image->depth;
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
/* Image is gray when no complex flag is set and 2D Matrix */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
{
SetImageColorspace(image,GRAYColorspace);
image->type=GrayscaleType;
}
/*
If ping is true, then only set image size and colors without
reading any image data.
*/
if (image_info->ping)
{
size_t temp = image->columns;
image->columns = image->rows;
image->rows = temp;
goto done_reading; /* !!!!!! BAD !!!! */
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
MinVal = 0;
MaxVal = 0;
if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum);
}
/* Main loop for reading all scanlines */
if(z==1) z=0; /* read grey scanlines */
/* else read color scanlines */
do
{
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto done_reading; /* Skip image rotation, when cannot set image pixels */
}
if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk)
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))
{
FixLogical((unsigned char *)BImgBuff,ldblk);
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
{
ImportQuantumPixelsFailed:
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
break;
}
}
else
{
if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0)
goto ImportQuantumPixelsFailed;
if (z<=1 && /* fix only during a last pass z==0 || z==1 */
(CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64))
FixSignedValues(q,MATLAB_HDR.SizeX);
}
if (!SyncAuthenticPixels(image,exception))
{
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),
" MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1));
goto ExitLoop;
}
}
} while(z-- >= 2);
quantum_info=DestroyQuantumInfo(quantum_info);
ExitLoop:
/* Read complex part of numbers here */
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* Find Min and Max Values for complex parts of floats */
CellType = ReadBlobXXXLong(image2); /* Additional object type */
i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/
if (CellType==miDOUBLE || CellType==miSINGLE)
{
CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal);
}
if (CellType==miDOUBLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff);
InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal);
}
}
/* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */
if ((MATLAB_HDR.DimFlag == 8) &&
((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0))
image->type=GrayscaleType;
if (image->depth == 1)
image->type=BilevelType;
if(image2==image)
image2 = NULL; /* Remove shadow copy to an image before rotation. */
/* Rotate image. */
rotated_image = RotateImage(image, 90.0, exception);
if (rotated_image != (Image *) NULL)
{
/* Remove page offsets added by RotateImage */
rotated_image->page.x=0;
rotated_image->page.y=0;
blob = rotated_image->blob;
rotated_image->blob = image->blob;
rotated_image->colors = image->colors;
image->blob = blob;
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
done_reading:
if(image2!=NULL)
if(image2!=image)
{
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
if (image->next == (Image *) NULL) break;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
/* row scan buffer is no longer needed */
RelinquishMagickMemory(BImgBuff);
BImgBuff = NULL;
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
goto NEXT_FRAME;
}
if(image2!=NULL)
if(image2!=image) /* Does shadow temporary decompressed image exist? */
{
/* CloseBlob(image2); */
DeleteImageFromList(&image2);
if(clone_info)
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) unlink(clone_info->filename);
}
}
}
}
RelinquishMagickMemory(BImgBuff);
END_OF_READING:
clone_info=DestroyImageInfo(clone_info);
CloseBlob(image);
{
Image *p;
ssize_t scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=scene++;
}
if(clone_info != NULL) /* cleanup garbage file from compression */
{
if(clone_info->file)
{
fclose(clone_info->file);
clone_info->file = NULL;
(void) remove_utf8(clone_info->filename);
}
DestroyImageInfo(clone_info);
clone_info = NULL;
}
if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return");
if(image==NULL)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
return (image);
}
Commit Message: Added check for invalid number of frames.
CWE ID: CWE-20
Target: 1
Example 2:
Code: struct sctp_chunk *sctp_make_abort_user(const struct sctp_association *asoc,
const struct msghdr *msg,
size_t paylen)
{
struct sctp_chunk *retval;
void *payload = NULL;
int err;
retval = sctp_make_abort(asoc, NULL, sizeof(sctp_errhdr_t) + paylen);
if (!retval)
goto err_chunk;
if (paylen) {
/* Put the msg_iov together into payload. */
payload = kmalloc(paylen, GFP_KERNEL);
if (!payload)
goto err_payload;
err = memcpy_fromiovec(payload, msg->msg_iov, paylen);
if (err < 0)
goto err_copy;
}
sctp_init_cause(retval, SCTP_ERROR_USER_ABORT, paylen);
sctp_addto_chunk(retval, paylen, payload);
if (paylen)
kfree(payload);
return retval;
err_copy:
kfree(payload);
err_payload:
sctp_chunk_free(retval);
retval = NULL;
err_chunk:
return retval;
}
Commit Message: net: sctp: fix NULL pointer dereference in af->from_addr_param on malformed packet
An SCTP server doing ASCONF will panic on malformed INIT ping-of-death
in the form of:
------------ INIT[PARAM: SET_PRIMARY_IP] ------------>
While the INIT chunk parameter verification dissects through many things
in order to detect malformed input, it misses to actually check parameters
inside of parameters. E.g. RFC5061, section 4.2.4 proposes a 'set primary
IP address' parameter in ASCONF, which has as a subparameter an address
parameter.
So an attacker may send a parameter type other than SCTP_PARAM_IPV4_ADDRESS
or SCTP_PARAM_IPV6_ADDRESS, param_type2af() will subsequently return 0
and thus sctp_get_af_specific() returns NULL, too, which we then happily
dereference unconditionally through af->from_addr_param().
The trace for the log:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000078
IP: [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
PGD 0
Oops: 0000 [#1] SMP
[...]
Pid: 0, comm: swapper Not tainted 2.6.32-504.el6.x86_64 #1 Bochs Bochs
RIP: 0010:[<ffffffffa01e9c62>] [<ffffffffa01e9c62>] sctp_process_init+0x492/0x990 [sctp]
[...]
Call Trace:
<IRQ>
[<ffffffffa01f2add>] ? sctp_bind_addr_copy+0x5d/0xe0 [sctp]
[<ffffffffa01e1fcb>] sctp_sf_do_5_1B_init+0x21b/0x340 [sctp]
[<ffffffffa01e3751>] sctp_do_sm+0x71/0x1210 [sctp]
[<ffffffffa01e5c09>] ? sctp_endpoint_lookup_assoc+0xc9/0xf0 [sctp]
[<ffffffffa01e61f6>] sctp_endpoint_bh_rcv+0x116/0x230 [sctp]
[<ffffffffa01ee986>] sctp_inq_push+0x56/0x80 [sctp]
[<ffffffffa01fcc42>] sctp_rcv+0x982/0xa10 [sctp]
[<ffffffffa01d5123>] ? ipt_local_in_hook+0x23/0x28 [iptable_filter]
[<ffffffff8148bdc9>] ? nf_iterate+0x69/0xb0
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148bf86>] ? nf_hook_slow+0x76/0x120
[<ffffffff81496d10>] ? ip_local_deliver_finish+0x0/0x2d0
[...]
A minimal way to address this is to check for NULL as we do on all
other such occasions where we know sctp_get_af_specific() could
possibly return with NULL.
Fixes: d6de3097592b ("[SCTP]: Add the handling of "Set Primary IP Address" parameter to INIT")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Neil Horman <[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: main(int argc, char *argv[])
{
OM_uint32 minor, major;
gss_ctx_id_t context;
gss_union_ctx_id_desc uctx;
krb5_gss_ctx_id_rec kgctx;
krb5_key k1, k2;
krb5_keyblock kb1, kb2;
gss_buffer_desc in, out;
unsigned char k1buf[32], k2buf[32], outbuf[44];
size_t i;
/*
* Fake up just enough of a krb5 GSS context to make gss_pseudo_random
* work, with chosen subkeys and acceptor subkeys. If we implement
* gss_import_lucid_sec_context, we can rewrite this to use public
* interfaces and stop using private headers and internal knowledge of the
* implementation.
*/
context = (gss_ctx_id_t)&uctx;
uctx.mech_type = &mech_krb5;
uctx.internal_ctx_id = (gss_ctx_id_t)&kgctx;
kgctx.k5_context = NULL;
kgctx.have_acceptor_subkey = 1;
kb1.contents = k1buf;
kb2.contents = k2buf;
for (i = 0; i < sizeof(tests) / sizeof(*tests); i++) {
/* Set up the keys for this test. */
kb1.enctype = tests[i].enctype;
kb1.length = fromhex(tests[i].key1, k1buf);
check_k5err(NULL, "create_key", krb5_k_create_key(NULL, &kb1, &k1));
kgctx.subkey = k1;
kb2.enctype = tests[i].enctype;
kb2.length = fromhex(tests[i].key2, k2buf);
check_k5err(NULL, "create_key", krb5_k_create_key(NULL, &kb2, &k2));
kgctx.acceptor_subkey = k2;
/* Generate a PRF value with the subkey and an empty input, and compare
* it to the first expected output. */
in.length = 0;
in.value = NULL;
major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_PARTIAL, &in,
44, &out);
check_gsserr("gss_pseudo_random", major, minor);
(void)fromhex(tests[i].out1, outbuf);
assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0);
(void)gss_release_buffer(&minor, &out);
/* Generate a PRF value with the acceptor subkey and the 61-byte input
* string, and compare it to the second expected output. */
in.length = strlen(inputstr);
in.value = (char *)inputstr;
major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 44,
&out);
check_gsserr("gss_pseudo_random", major, minor);
(void)fromhex(tests[i].out2, outbuf);
assert(out.length == 44 && memcmp(out.value, outbuf, 44) == 0);
(void)gss_release_buffer(&minor, &out);
/* Also check that generating zero bytes of output works. */
major = gss_pseudo_random(&minor, context, GSS_C_PRF_KEY_FULL, &in, 0,
&out);
check_gsserr("gss_pseudo_random", major, minor);
assert(out.length == 0);
(void)gss_release_buffer(&minor, &out);
krb5_k_free_key(NULL, k1);
krb5_k_free_key(NULL, k2);
}
return 0;
}
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:
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 Image *ReadPDBImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
unsigned char
attributes,
tag[3];
Image
*image;
IndexPacket
index;
MagickBooleanType
status;
PDBImage
pdb_image;
PDBInfo
pdb_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
size_t
bits_per_pixel,
num_pad_bytes,
one,
packets;
ssize_t
count,
img_offset,
comment_offset = 0,
y;
unsigned char
*pixels;
/*
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);
}
/*
Determine if this a PDB image file.
*/
count=ReadBlob(image,sizeof(pdb_info.name),(unsigned char *) pdb_info.name);
if (count != sizeof(pdb_info.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_info.attributes=(short) ReadBlobMSBShort(image);
pdb_info.version=(short) ReadBlobMSBShort(image);
pdb_info.create_time=ReadBlobMSBLong(image);
pdb_info.modify_time=ReadBlobMSBLong(image);
pdb_info.archive_time=ReadBlobMSBLong(image);
pdb_info.modify_number=ReadBlobMSBLong(image);
pdb_info.application_info=ReadBlobMSBLong(image);
pdb_info.sort_info=ReadBlobMSBLong(image);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.type);
(void) ReadBlob(image,4,(unsigned char *) pdb_info.id);
pdb_info.seed=ReadBlobMSBLong(image);
pdb_info.next_record=ReadBlobMSBLong(image);
pdb_info.number_records=(short) ReadBlobMSBShort(image);
if ((memcmp(pdb_info.type,"vIMG",4) != 0) ||
(memcmp(pdb_info.id,"View",4) != 0))
if (pdb_info.next_record != 0)
ThrowReaderException(CoderError,"MultipleRecordListNotSupported");
/*
Read record header.
*/
img_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
(void) attributes;
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x00",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
if (pdb_info.number_records > 1)
{
comment_offset=(ssize_t) ((int) ReadBlobMSBLong(image));
attributes=(unsigned char) ((int) ReadBlobByte(image));
count=ReadBlob(image,3,(unsigned char *) tag);
if (count != 3 || memcmp(tag,"\x6f\x80\x01",3) != 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
}
num_pad_bytes = (size_t) (img_offset - TellBlob( image ));
while (num_pad_bytes-- != 0)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
/*
Read image header.
*/
count=ReadBlob(image,sizeof(pdb_image.name),(unsigned char *) pdb_image.name);
if (count != sizeof(pdb_image.name))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
pdb_image.version=ReadBlobByte(image);
pdb_image.type=(unsigned char) ReadBlobByte(image);
pdb_image.reserved_1=ReadBlobMSBLong(image);
pdb_image.note=ReadBlobMSBLong(image);
pdb_image.x_last=(short) ReadBlobMSBShort(image);
pdb_image.y_last=(short) ReadBlobMSBShort(image);
pdb_image.reserved_2=ReadBlobMSBLong(image);
pdb_image.x_anchor=ReadBlobMSBShort(image);
pdb_image.y_anchor=ReadBlobMSBShort(image);
pdb_image.width=(short) ReadBlobMSBShort(image);
pdb_image.height=(short) ReadBlobMSBShort(image);
/*
Initialize image structure.
*/
image->columns=(size_t) pdb_image.width;
image->rows=(size_t) pdb_image.height;
image->depth=8;
image->storage_class=PseudoClass;
bits_per_pixel=pdb_image.type == 0 ? 2UL : pdb_image.type == 2 ? 4UL : 1UL;
one=1;
if (AcquireImageColormap(image,one << bits_per_pixel) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
packets=(bits_per_pixel*image->columns+7)/8;
pixels=(unsigned char *) AcquireQuantumMemory(packets+256UL,image->rows*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
switch (pdb_image.version & 0x07)
{
case 0:
{
image->compression=NoCompression;
count=(ssize_t) ReadBlob(image, packets * image -> rows, pixels);
break;
}
case 1:
{
image->compression=RLECompression;
if (!DecodeImage(image, pixels, packets * image -> rows))
ThrowReaderException( CorruptImageError, "RLEDecoderError" );
break;
}
default:
ThrowReaderException(CorruptImageError,
"UnrecognizedImageCompressionType" );
}
p=pixels;
switch (bits_per_pixel)
{
case 1:
{
int
bit;
/*
Read 1-bit PDB image.
*/
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-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=(IndexPacket) (*p & (0x80 >> bit) ? 0x00 : 0x01);
SetPixelIndex(indexes+x+bit,index);
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 2:
{
/*
Read 2-bit PDB image.
*/
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-3; x+=4)
{
index=ConstrainColormapIndex(image,3UL-((*p >> 6) & 0x03));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 4) & 0x03));
SetPixelIndex(indexes+x+1,index);
index=ConstrainColormapIndex(image,3UL-((*p >> 2) & 0x03));
SetPixelIndex(indexes+x+2,index);
index=ConstrainColormapIndex(image,3UL-((*p) & 0x03));
SetPixelIndex(indexes+x+3,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
case 4:
{
/*
Read 4-bit PDB image.
*/
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-1; x+=2)
{
index=ConstrainColormapIndex(image,15UL-((*p >> 4) & 0x0f));
SetPixelIndex(indexes+x,index);
index=ConstrainColormapIndex(image,15UL-((*p) & 0x0f));
SetPixelIndex(indexes+x+1,index);
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
(void) SyncImage(image);
break;
}
default:
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
if (pdb_info.number_records > 1)
{
char
*comment;
int
c;
register char
*p;
size_t
length;
num_pad_bytes = (size_t) (comment_offset - TellBlob( image ));
while (num_pad_bytes--) ReadBlobByte( image );
/*
Read comment.
*/
c=ReadBlobByte(image);
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; c != EOF; p++)
{
if ((size_t) (p-comment+MaxTextExtent) >= length)
{
*p='\0';
length<<=1;
length+=MaxTextExtent;
comment=(char *) ResizeQuantumMemory(comment,length+MaxTextExtent,
sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=c;
c=ReadBlobByte(image);
}
*p='\0';
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/143
CWE ID: CWE-125
Target: 1
Example 2:
Code: base::FilePath GetSetupExeForInstallationLevel(InstallationLevel level) {
base::FilePath setup_exe_path(
GetSetupExeFromRegistry(level, kBinariesAppGuid));
if (setup_exe_path.empty())
setup_exe_path = GetSetupExeFromRegistry(level, kBrowserAppGuid);
return setup_exe_path;
}
Commit Message: Upgrade old app host to new app launcher on startup
This patch is a continuation of https://codereview.chromium.org/16805002/.
BUG=248825
Review URL: https://chromiumcodereview.appspot.com/17022015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 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: asocket* find_local_socket(unsigned local_id, unsigned peer_id) {
asocket* s;
asocket* result = NULL;
adb_mutex_lock(&socket_list_lock);
for (s = local_socket_list.next; s != &local_socket_list; s = s->next) {
if (s->id != local_id) {
continue;
}
if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) {
result = s;
}
break;
}
adb_mutex_unlock(&socket_list_lock);
return result;
}
Commit Message: adb: switch the socket list mutex to a recursive_mutex.
sockets.cpp was branching on whether a socket close function was
local_socket_close in order to avoid a potential deadlock if the socket
list lock was held while closing a peer socket.
Bug: http://b/28347842
Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3
(cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa)
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: static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies,
size_t mincodes, size_t numcodes, unsigned maxbitlen)
{
unsigned error = 0;
while(!frequencies[numcodes - 1] && numcodes > mincodes) numcodes--; /*trim zeroes*/
tree->maxbitlen = maxbitlen;
tree->numcodes = (unsigned)numcodes; /*number of symbols*/
tree->lengths = (unsigned*)realloc(tree->lengths, numcodes * sizeof(unsigned));
if(!tree->lengths) return 83; /*alloc fail*/
/*initialize all lengths to 0*/
memset(tree->lengths, 0, numcodes * sizeof(unsigned));
error = lodepng_huffman_code_lengths(tree->lengths, frequencies, numcodes, maxbitlen);
if(!error) error = HuffmanTree_makeFromLengths2(tree);
return error;
}
Commit Message: Fixed #5645: realloc return handling
CWE ID: CWE-772
Target: 1
Example 2:
Code: void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
spinlock_t *ptl)
{
pte_t pte;
swp_entry_t entry;
struct page *page;
spin_lock(ptl);
pte = *ptep;
if (!is_swap_pte(pte))
goto out;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto out;
page = migration_entry_to_page(entry);
/*
* Once radix-tree replacement of page migration started, page_count
* *must* be zero. And, we don't want to call wait_on_page_locked()
* against a page without get_page().
* So, we use get_page_unless_zero(), here. Even failed, page fault
* will occur again.
*/
if (!get_page_unless_zero(page))
goto out;
pte_unmap_unlock(ptep, ptl);
wait_on_page_locked(page);
put_page(page);
return;
out:
pte_unmap_unlock(ptep, ptl);
}
Commit Message: mm: migrate dirty page without clear_page_dirty_for_io etc
clear_page_dirty_for_io() has accumulated writeback and memcg subtleties
since v2.6.16 first introduced page migration; and the set_page_dirty()
which completed its migration of PageDirty, later had to be moderated to
__set_page_dirty_nobuffers(); then PageSwapBacked had to skip that too.
No actual problems seen with this procedure recently, but if you look into
what the clear_page_dirty_for_io(page)+set_page_dirty(newpage) is actually
achieving, it turns out to be nothing more than moving the PageDirty flag,
and its NR_FILE_DIRTY stat from one zone to another.
It would be good to avoid a pile of irrelevant decrementations and
incrementations, and improper event counting, and unnecessary descent of
the radix_tree under tree_lock (to set the PAGECACHE_TAG_DIRTY which
radix_tree_replace_slot() left in place anyway).
Do the NR_FILE_DIRTY movement, like the other stats movements, while
interrupts still disabled in migrate_page_move_mapping(); and don't even
bother if the zone is the same. Do the PageDirty movement there under
tree_lock too, where old page is frozen and newpage not yet visible:
bearing in mind that as soon as newpage becomes visible in radix_tree, an
un-page-locked set_page_dirty() might interfere (or perhaps that's just
not possible: anything doing so should already hold an additional
reference to the old page, preventing its migration; but play safe).
But we do still need to transfer PageDirty in migrate_page_copy(), for
those who don't go the mapping route through migrate_page_move_mapping().
Signed-off-by: Hugh Dickins <[email protected]>
Cc: Christoph Lameter <[email protected]>
Cc: "Kirill A. Shutemov" <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: Oleg Nesterov <[email protected]>
Cc: Sasha Levin <[email protected]>
Cc: Dmitry Vyukov <[email protected]>
Cc: KOSAKI Motohiro <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-476
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: doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
int tok, const char *next, const char **nextPtr, XML_Bool haveMore) {
#ifdef XML_DTD
static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'};
#endif /* XML_DTD */
static const XML_Char atypeCDATA[]
= {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, '\0'};
static const XML_Char atypeID[] = {ASCII_I, ASCII_D, '\0'};
static const XML_Char atypeIDREF[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, '\0'};
static const XML_Char atypeIDREFS[]
= {ASCII_I, ASCII_D, ASCII_R, ASCII_E, ASCII_F, ASCII_S, '\0'};
static const XML_Char atypeENTITY[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T, ASCII_Y, '\0'};
static const XML_Char atypeENTITIES[]
= {ASCII_E, ASCII_N, ASCII_T, ASCII_I, ASCII_T,
ASCII_I, ASCII_E, ASCII_S, '\0'};
static const XML_Char atypeNMTOKEN[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K, ASCII_E, ASCII_N, '\0'};
static const XML_Char atypeNMTOKENS[]
= {ASCII_N, ASCII_M, ASCII_T, ASCII_O, ASCII_K,
ASCII_E, ASCII_N, ASCII_S, '\0'};
static const XML_Char notationPrefix[]
= {ASCII_N, ASCII_O, ASCII_T, ASCII_A, ASCII_T,
ASCII_I, ASCII_O, ASCII_N, ASCII_LPAREN, '\0'};
static const XML_Char enumValueSep[] = {ASCII_PIPE, '\0'};
static const XML_Char enumValueStart[] = {ASCII_LPAREN, '\0'};
/* save one level of indirection */
DTD *const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
if (enc == parser->m_encoding) {
eventPP = &parser->m_eventPtr;
eventEndPP = &parser->m_eventEndPtr;
} else {
eventPP = &(parser->m_openInternalEntities->internalEventPtr);
eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
int role;
XML_Bool handleDefault = XML_TRUE;
*eventPP = s;
*eventEndPP = next;
if (tok <= 0) {
if (haveMore && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
switch (tok) {
case XML_TOK_INVALID:
*eventPP = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
return XML_ERROR_PARTIAL_CHAR;
case -XML_TOK_PROLOG_S:
tok = -tok;
break;
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
if (enc != parser->m_encoding
&& ! parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
/* WFC: PE Between Declarations - must check that PE contains
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
if (parser->m_isParamEntity || enc != parser->m_encoding) {
if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
return XML_ERROR_NONE;
}
#endif /* XML_DTD */
return XML_ERROR_NO_ELEMENTS;
default:
tok = -tok;
next = end;
break;
}
}
role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL: {
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
case XML_ROLE_DOCTYPE_NAME:
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
if (parser->m_startDoctypeDeclHandler) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 1);
parser->m_doctypeName = NULL;
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
#ifdef XML_DTD
case XML_ROLE_TEXT_DECL: {
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
enc = parser->m_encoding;
handleDefault = XML_FALSE;
} break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
poolFinish(&parser->m_tempPool);
parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
/* fall through */
case XML_ROLE_ENTITY_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_PUBLIC_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
if (parser->m_doctypeName) {
parser->m_startDoctypeDeclHandler(
parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
parser->m_doctypePubid, 0);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
/* parser->m_doctypeSysid will be non-NULL in the case of a previous
XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity) {
/* The external subset name "#" will have already been
* inserted into the hash table at the start of the
* external entity parsing, so no allocation will happen
* and lookup() cannot fail.
*/
return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
}
if (parser->m_useForeignDTD)
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else if (! parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
if (parser->m_endDoctypeDeclHandler) {
parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_INSTANCE_START:
#ifdef XML_DTD
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_paramEntityParsing
&& parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName, sizeof(ENTITY));
if (! entity)
return XML_ERROR_NO_MEMORY;
entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
else
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
}
#endif /* XML_DTD */
parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
if (! parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeIsCdata = XML_FALSE;
parser->m_declAttributeType = NULL;
parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
parser->m_declAttributeIsCdata = XML_TRUE;
parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
parser->m_declAttributeIsId = XML_TRUE;
parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
if (parser->m_declAttributeType) {
prefix = enumValueSep;
} else {
prefix = (role == XML_ROLE_ATTRIBUTE_NOTATION_VALUE ? notationPrefix
: enumValueStart);
}
if (! poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
if (! poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
if (! defineAttribute(parser->m_declElementType,
parser->m_declAttributeId,
parser->m_declAttributeIsCdata,
parser->m_declAttributeIsId, 0, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType, 0,
role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_DEFAULT_ATTRIBUTE_VALUE:
case XML_ROLE_FIXED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result = storeAttributeValue(
parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar, next - enc->minBytesPerChar, &dtd->pool);
if (result)
return result;
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
if (! defineAttribute(
parser->m_declElementType, parser->m_declAttributeId,
parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
|| (*parser->m_declAttributeType == XML_T(ASCII_N)
&& parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
if (! poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
|| ! poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
parser->m_declAttributeType = parser->m_tempPool.start;
poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
parser->m_attlistDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name,
parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal, role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_ENTITY_VALUE:
if (dtd->keepProcessing) {
enum XML_Error result = storeEntityValue(
parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar);
if (parser->m_declEntity) {
parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
parser->m_declEntity->textLen
= (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
} else
poolDiscard(&dtd->entityValuePool);
if (result != XML_ERROR_NONE)
return result;
}
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
if (parser->m_startDoctypeDeclHandler) {
parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
/* use externalSubsetName to make parser->m_doctypeSysid non-NULL
for the case where no parser->m_startDoctypeDeclHandler is set */
parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (! dtd->standalone
#ifdef XML_DTD
&& ! parser->m_paramEntityParsing
#endif /* XML_DTD */
&& parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
if (! parser->m_declEntity) {
parser->m_declEntity = (ENTITY *)lookup(
parser, &dtd->paramEntities, externalSubsetName, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->publicId = NULL;
}
#endif /* XML_DTD */
/* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->systemId
= poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
/* Don't suppress the default handler if we fell through from
* the XML_ROLE_DOCTYPE_SYSTEM_ID case.
*/
if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
if (dtd->keepProcessing && parser->m_declEntity
&& parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->is_param, 0, 0, parser->m_declEntity->base,
parser->m_declEntity->systemId, parser->m_declEntity->publicId, 0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
if (dtd->keepProcessing && parser->m_declEntity) {
parser->m_declEntity->notation
= poolStoreString(&dtd->pool, enc, s, next);
if (! parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
parser->m_unparsedEntityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
} else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
parser->m_entityDeclHandler(
parser->m_handlerArg, parser->m_declEntity->name, 0, 0, 0,
parser->m_declEntity->base, parser->m_declEntity->systemId,
parser->m_declEntity->publicId, parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
break;
case XML_ROLE_GENERAL_ENTITY_NAME: {
if (XmlPredefinedEntityName(enc, s, next)) {
parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
} break;
case XML_ROLE_PARAM_ENTITY_NAME:
#ifdef XML_DTD
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (! name)
return XML_ERROR_NO_MEMORY;
parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
if (! parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
} else {
poolFinish(&dtd->pool);
parser->m_declEntity->publicId = NULL;
parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
parser->m_declEntity->is_internal
= ! (parser->m_parentParser || parser->m_openInternalEntities);
if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
} else {
poolDiscard(&dtd->pool);
parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
parser->m_declNotationPublicId = NULL;
parser->m_declNotationName = NULL;
if (parser->m_notationDeclHandler) {
parser->m_declNotationName
= poolStoreString(&parser->m_tempPool, enc, s, next);
if (! parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (! XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
if (parser
->m_declNotationName) { /* means m_notationDeclHandler != NULL */
XML_Char *tem = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
parser->m_declNotationPublicId = tem;
poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
systemId, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
parser->m_notationDeclHandler(
parser->m_handlerArg, parser->m_declNotationName, parser->m_curBase,
0, parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
/* PE references in internal subset are
not allowed within declarations. */
return XML_ERROR_PARAM_ENTITY_REF;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
default:
return XML_ERROR_SYNTAX;
}
#ifdef XML_DTD
case XML_ROLE_IGNORE_SECT: {
enum XML_Error result;
if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (! next) {
parser->m_processor = ignoreSectionProcessor;
return result;
}
} break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
if (parser->m_prologState.level >= parser->m_groupSize) {
if (parser->m_groupSize) {
{
char *const new_connector = (char *)REALLOC(
parser, parser->m_groupConnector, parser->m_groupSize *= 2);
if (new_connector == NULL) {
parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
}
parser->m_groupConnector = new_connector;
}
if (dtd->scaffIndex) {
int *const new_scaff_index = (int *)REALLOC(
parser, dtd->scaffIndex, parser->m_groupSize * sizeof(int));
if (new_scaff_index == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = new_scaff_index;
}
} else {
parser->m_groupConnector
= (char *)MALLOC(parser, parser->m_groupSize = 32);
if (! parser->m_groupConnector) {
parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
}
}
}
parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
assert(dtd->scaffIndex != NULL);
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
&& ! parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
if (! parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
ENTITY *entity;
name = poolStoreString(&dtd->pool, enc, s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (! name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
poolDiscard(&dtd->pool);
/* first, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
if (parser->m_prologState.documentEntity
&& (dtd->standalone ? ! parser->m_openInternalEntities
: ! dtd->hasParamEntityRefs)) {
if (! entity)
return XML_ERROR_UNDEFINED_ENTITY;
else if (! entity->is_internal) {
/* It's hard to exhaustively search the code to be sure,
* but there doesn't seem to be a way of executing the
* following line. There are two cases:
*
* If 'standalone' is false, the DTD must have no
* parameter entities or we wouldn't have passed the outer
* 'if' statement. That measn the only entity in the hash
* table is the external subset name "#" which cannot be
* given as a parameter entity name in XML syntax, so the
* lookup must have returned NULL and we don't even reach
* the test for an internal entity.
*
* If 'standalone' is true, it does not seem to be
* possible to create entities taking this code path that
* are not internal entities, so fail the test above.
*
* Because this analysis is very uncertain, the code is
* being left in place and merely removed from the
* coverage test statistics.
*/
return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
}
} else if (! entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
if ((role == XML_ROLE_PARAM_ENTITY_REF)
&& parser->m_skippedEntityHandler) {
parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
}
if (entity->open)
return XML_ERROR_RECURSIVE_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
XML_Bool betweenDecl
= (role == XML_ROLE_PARAM_ENTITY_REF ? XML_TRUE : XML_FALSE);
result = processInternalEntity(parser, entity, betweenDecl);
if (result != XML_ERROR_NONE)
return result;
handleDefault = XML_FALSE;
break;
}
if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
if (! parser->m_externalEntityRefHandler(
parser->m_externalEntityRefHandlerArg, 0, entity->base,
entity->systemId, entity->publicId)) {
entity->open = XML_FALSE;
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
}
entity->open = XML_FALSE;
handleDefault = XML_FALSE;
if (! dtd->paramEntityRead) {
dtd->keepProcessing = dtd->standalone;
break;
}
} else {
dtd->keepProcessing = dtd->standalone;
break;
}
}
#endif /* XML_DTD */
if (! dtd->standalone && parser->m_notStandaloneHandler
&& ! parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
if (parser->m_elementDeclHandler) {
parser->m_declElementType = getElementType(parser, enc, s, next);
if (! parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
dtd->in_eldecl = XML_TRUE;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler) {
XML_Content *content
= (XML_Content *)MALLOC(parser, sizeof(XML_Content));
if (! content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
content->name = NULL;
content->numchildren = 0;
content->children = NULL;
content->type = ((role == XML_ROLE_CONTENT_ANY) ? XML_CTYPE_ANY
: XML_CTYPE_EMPTY);
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_PCDATA:
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_CONTENT_ELEMENT:
quant = XML_CQUANT_NONE;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_OPT:
quant = XML_CQUANT_OPT;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_REP:
quant = XML_CQUANT_REP;
goto elementContent;
case XML_ROLE_CONTENT_ELEMENT_PLUS:
quant = XML_CQUANT_PLUS;
elementContent:
if (dtd->in_eldecl) {
ELEMENT_TYPE *el;
const XML_Char *name;
int nameLen;
const char *nxt
= (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
return XML_ERROR_NO_MEMORY;
dtd->scaffold[myindex].type = XML_CTYPE_NAME;
dtd->scaffold[myindex].quant = quant;
el = getElementType(parser, enc, s, nxt);
if (! el)
return XML_ERROR_NO_MEMORY;
name = el->name;
dtd->scaffold[myindex].name = name;
nameLen = 0;
for (; name[nameLen++];)
;
dtd->contentStringLen += nameLen;
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_CLOSE:
quant = XML_CQUANT_NONE;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_OPT:
quant = XML_CQUANT_OPT;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_REP:
quant = XML_CQUANT_REP;
goto closeGroup;
case XML_ROLE_GROUP_CLOSE_PLUS:
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
if (dtd->scaffLevel == 0) {
if (! handleDefault) {
XML_Content *model = build_model(parser);
if (! model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
parser->m_elementDeclHandler(
parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
}
}
break;
/* End element declaration stuff */
case XML_ROLE_PI:
if (! reportProcessingInstruction(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_COMMENT:
if (! reportComment(parser, enc, s, next))
return XML_ERROR_NO_MEMORY;
handleDefault = XML_FALSE;
break;
case XML_ROLE_NONE:
switch (tok) {
case XML_TOK_BOM:
handleDefault = XML_FALSE;
break;
}
break;
case XML_ROLE_DOCTYPE_NONE:
if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
case XML_FINISHED:
return XML_ERROR_ABORTED;
default:
s = next;
tok = XmlPrologTok(enc, s, end, &next);
}
}
/* not reached */
}
Commit Message: xmlparse.c: Deny internal entities closing the doctype
CWE ID: CWE-611
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 Image *ReadPSDImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
has_merged_image,
skip_layers,
status;
MagickOffsetType
offset;
MagickSizeType
length;
PSDInfo
psd_info;
register ssize_t
i;
ssize_t
count;
unsigned char
*data;
/*
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 image header.
*/
count=ReadBlob(image,4,(unsigned char *) psd_info.signature);
psd_info.version=ReadBlobMSBShort(image);
if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) ||
((psd_info.version != 1) && (psd_info.version != 2)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,6,psd_info.reserved);
psd_info.channels=ReadBlobMSBShort(image);
if (psd_info.channels > MaxPSDChannels)
ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded");
psd_info.rows=ReadBlobMSBLong(image);
psd_info.columns=ReadBlobMSBLong(image);
if ((psd_info.version == 1) && ((psd_info.rows > 30000) ||
(psd_info.columns > 30000)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.depth=ReadBlobMSBShort(image);
if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
psd_info.mode=ReadBlobMSBShort(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s",
(double) psd_info.columns,(double) psd_info.rows,(double)
psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType)
psd_info.mode));
/*
Initialize image.
*/
image->depth=psd_info.depth;
image->columns=psd_info.columns;
image->rows=psd_info.rows;
if (SetImageBackgroundColor(image) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace);
image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace);
image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse;
}
else
image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse;
/*
Read PSD raster colormap only present for indexed and duotone images.
*/
length=ReadBlobMSBLong(image);
if (length != 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading colormap");
if (psd_info.mode == DuotoneMode)
{
/*
Duotone image data; the format of this data is undocumented.
*/
data=(unsigned char *) AcquireQuantumMemory((size_t) length,
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,data);
data=(unsigned char *) RelinquishMagickMemory(data);
}
else
{
size_t
number_colors;
/*
Read PSD raster colormap.
*/
number_colors=length/3;
if (number_colors > 65536)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireImageColormap(image,number_colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->matte=MagickFalse;
}
}
has_merged_image=MagickTrue;
length=ReadBlobMSBLong(image);
if (length != 0)
{
unsigned char
*blocks;
/*
Image resources block.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading image resource blocks - %.20g bytes",(double)
((MagickOffsetType) length));
blocks=(unsigned char *) AcquireQuantumMemory((size_t) length+16,
sizeof(*blocks));
if (blocks == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) length,blocks);
if ((count != (ssize_t) length) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
(void) ParseImageResourceBlocks(image,blocks,(size_t) length,
&has_merged_image);
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
}
/*
Layer and mask block.
*/
length=GetPSDSize(&psd_info,image);
if (length == 8)
{
length=ReadBlobMSBLong(image);
length=ReadBlobMSBLong(image);
}
offset=TellBlob(image);
skip_layers=MagickFalse;
if ((image_info->number_scenes == 1) && (image_info->scene == 0) &&
(has_merged_image != MagickFalse))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" read composite only");
skip_layers=MagickTrue;
}
if (length == 0)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has no layers");
}
else
{
if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
return((Image *) NULL);
}
/*
Skip the rest of the layer and mask information.
*/
SeekBlob(image,offset+length,SEEK_SET);
}
/*
If we are only "pinging" the image, then we're done - so return.
*/
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
/*
Read the precombined layer, present for PSD < 4 compatibility.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading the precombined layer");
if (has_merged_image != MagickFalse || GetImageListLength(image) == 1)
has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image,&psd_info,
exception);
if (has_merged_image == MagickFalse && GetImageListLength(image) == 1 &&
length != 0)
{
SeekBlob(image,offset,SEEK_SET);
if (ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception) !=
MagickTrue)
{
(void) CloseBlob(image);
return((Image *) NULL);
}
}
if (has_merged_image == MagickFalse && GetImageListLength(image) > 1)
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel);
image->background_color.opacity=TransparentOpacity;
merged=MergeImageLayers(image,FlattenLayer,exception);
ReplaceImageInList(&image,merged);
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int no_sideband(transport_smart *t, struct git_odb_writepack *writepack, gitno_buffer *buf, git_transfer_progress *stats)
{
int recvd;
do {
if (t->cancelled.val) {
giterr_set(GITERR_NET, "The fetch was cancelled by the user");
return GIT_EUSER;
}
if (writepack->append(writepack, buf->data, buf->offset, stats) < 0)
return -1;
gitno_consume_n(buf, buf->offset);
if ((recvd = gitno_recv(buf)) < 0)
return recvd;
} while(recvd > 0);
if (writepack->commit(writepack, stats) < 0)
return -1;
return 0;
}
Commit Message: smart_pkt: treat empty packet lines as error
The Git protocol does not specify what should happen in the case
of an empty packet line (that is a packet line "0004"). We
currently indicate success, but do not return a packet in the
case where we hit an empty line. The smart protocol was not
prepared to handle such packets in all cases, though, resulting
in a `NULL` pointer dereference.
Fix the issue by returning an error instead. As such kind of
packets is not even specified by upstream, this is the right
thing to do.
CWE ID: CWE-476
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: check_filename(char *str, int len)
{
int i;
if (len == 0)
return nfserr_inval;
if (isdotent(str, len))
return nfserr_badname;
for (i = 0; i < len; i++)
if (str[i] == '/')
return nfserr_badname;
return 0;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
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 sas_discover_end_dev(struct domain_device *dev)
{
int res;
res = sas_notify_lldd_dev_found(dev);
if (res)
return res;
sas_discover_event(dev->port, DISCE_PROBE);
return 0;
}
Commit Message: scsi: libsas: direct call probe and destruct
In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery
competing with ata error handling") introduced disco mutex to prevent
rediscovery competing with ata error handling and put the whole
revalidation in the mutex. But the rphy add/remove needs to wait for the
error handling which also grabs the disco mutex. This may leads to dead
lock.So the probe and destruct event were introduce to do the rphy
add/remove asynchronously and out of the lock.
The asynchronously processed workers makes the whole discovery process
not atomic, the other events may interrupt the process. For example,
if a loss of signal event inserted before the probe event, the
sas_deform_port() is called and the port will be deleted.
And sas_port_delete() may run before the destruct event, but the
port-x:x is the top parent of end device or expander. This leads to
a kernel WARNING such as:
[ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22'
[ 82.042983] ------------[ cut here ]------------
[ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237
sysfs_remove_group+0x94/0xa0
[ 82.043059] Call trace:
[ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0
[ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70
[ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308
[ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60
[ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80
[ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0
[ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50
[ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0
[ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0
[ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490
[ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128
[ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50
Make probe and destruct a direct call in the disco and revalidate function,
but put them outside the lock. The whole discovery or revalidate won't
be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT
event are deleted as a result of the direct call.
Introduce a new list to destruct the sas_port and put the port delete after
the destruct. This makes sure the right order of destroying the sysfs
kobject and fix the warning above.
In sas_ex_revalidate_domain() have a loop to find all broadcasted
device, and sometimes we have a chance to find the same expander twice.
Because the sas_port will be deleted at the end of the whole revalidate
process, sas_port with the same name cannot be added before this.
Otherwise the sysfs will complain of creating duplicate filename. Since
the LLDD will send broadcast for every device change, we can only
process one expander's revalidation.
[mkp: kbuild test robot warning]
Signed-off-by: Jason Yan <[email protected]>
CC: John Garry <[email protected]>
CC: Johannes Thumshirn <[email protected]>
CC: Ewan Milne <[email protected]>
CC: Christoph Hellwig <[email protected]>
CC: Tomas Henzl <[email protected]>
CC: Dan Williams <[email protected]>
Reviewed-by: Hannes Reinecke <[email protected]>
Signed-off-by: Martin K. Petersen <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: static zend_always_inline Bucket *zend_hash_index_find_bucket(const HashTable *ht, zend_ulong h)
{
uint32_t nIndex;
uint32_t idx;
Bucket *p, *arData;
arData = ht->arData;
nIndex = h | ht->nTableMask;
idx = HT_HASH_EX(arData, nIndex);
while (idx != HT_INVALID_IDX) {
ZEND_ASSERT(idx < HT_IDX_TO_HASH(ht->nTableSize));
p = HT_HASH_TO_BUCKET_EX(arData, idx);
if (p->h == h && !p->key) {
return p;
}
idx = Z_NEXT(p->val);
}
return NULL;
}
Commit Message: Fix #73832 - leave the table in a safe state if the size is too big.
CWE ID: CWE-190
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 IsManualFallbackForFillingEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
!IsPreLollipopAndroid();
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <[email protected]>
Commit-Queue: NIKHIL SAHNI <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534923}
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: long mkvparser::UnserializeInt(
IMkvReader* pReader,
long long pos,
long size,
long long& result)
{
assert(pReader);
assert(pos >= 0);
assert(size > 0);
assert(size <= 8);
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i)
{
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; //success
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool RenderFrameImpl::IsLocalRoot() const {
bool is_local_root = static_cast<bool>(render_widget_);
DCHECK_EQ(is_local_root,
!(frame_->Parent() && frame_->Parent()->IsWebLocalFrame()));
return is_local_root;
}
Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo.
Note: Since this required changing the test
RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually
re-introduced https://crbug.com/666714 locally (the bug the test was
added for), and reran the test to confirm that it still covers the bug.
Bug: 786836
Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270
Commit-Queue: Lowell Manners <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Cr-Commit-Position: refs/heads/master@{#653137}
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: _gnutls_ciphertext2compressed (gnutls_session_t session,
opaque * compress_data,
int compress_size,
gnutls_datum_t ciphertext, uint8_t type)
{
uint8_t MAC[MAX_HASH_SIZE];
uint16_t c_length;
uint8_t pad;
int length;
digest_hd_st td;
uint16_t blocksize;
int ret, i, pad_failed = 0;
uint8_t major, minor;
gnutls_protocol_t ver;
int hash_size =
_gnutls_hash_get_algo_len (session->security_parameters.
read_mac_algorithm);
ver = gnutls_protocol_get_version (session);
minor = _gnutls_version_get_minor (ver);
major = _gnutls_version_get_major (ver);
blocksize = _gnutls_cipher_get_block_size (session->security_parameters.
read_bulk_cipher_algorithm);
/* initialize MAC
*/
ret = mac_init (&td, session->security_parameters.read_mac_algorithm,
session->connection_state.read_mac_secret.data,
session->connection_state.read_mac_secret.size, ver);
if (ret < 0
&& session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
/* actual decryption (inplace)
*/
{
gnutls_assert ();
return ret;
}
length = ciphertext.size - hash_size;
break;
case CIPHER_BLOCK:
if ((ciphertext.size < blocksize) || (ciphertext.size % blocksize != 0))
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
if ((ret = _gnutls_cipher_decrypt (&session->connection_state.
read_cipher_state,
ciphertext.data,
ciphertext.size)) < 0)
{
gnutls_assert ();
return ret;
}
/* ignore the IV in TLS 1.1.
*/
if (session->security_parameters.version >= GNUTLS_TLS1_1)
{
ciphertext.size -= blocksize;
ciphertext.data += blocksize;
if (ciphertext.size == 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
}
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */
length = ciphertext.size - hash_size - pad;
if (pad > ciphertext.size - hash_size)
{
gnutls_assert ();
/* We do not fail here. We check below for the
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
pad_failed = GNUTLS_E_DECRYPTION_FAILED;
}
/* Check the pading bytes (TLS 1.x)
*/
if (ver >= GNUTLS_TLS1 && pad_failed == 0)
gnutls_assert ();
return GNUTLS_E_INTERNAL_ERROR;
}
if (length < 0)
length = 0;
c_length = _gnutls_conv_uint16 ((uint16_t) length);
/* Pass the type, version, length and compressed through
* MAC.
*/
if (session->security_parameters.read_mac_algorithm != GNUTLS_MAC_NULL)
{
_gnutls_hmac (&td,
UINT64DATA (session->connection_state.
read_sequence_number), 8);
_gnutls_hmac (&td, &type, 1);
if (ver >= GNUTLS_TLS1)
{ /* TLS 1.x */
_gnutls_hmac (&td, &major, 1);
_gnutls_hmac (&td, &minor, 1);
}
_gnutls_hmac (&td, &c_length, 2);
if (length > 0)
_gnutls_hmac (&td, ciphertext.data, length);
mac_deinit (&td, MAC, ver);
}
/* This one was introduced to avoid a timing attack against the TLS
* 1.0 protocol.
*/
if (pad_failed != 0)
return pad_failed;
/* HMAC was not the same.
*/
if (memcmp (MAC, &ciphertext.data[length], hash_size) != 0)
{
gnutls_assert ();
return GNUTLS_E_DECRYPTION_FAILED;
}
/* copy the decrypted stuff to compress_data.
*/
if (compress_size < length)
{
gnutls_assert ();
return GNUTLS_E_DECOMPRESSION_FAILED;
}
memcpy (compress_data, ciphertext.data, length);
return length;
}
Commit Message:
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 show_object(struct object *object, struct strbuf *path,
const char *last, void *data)
{
struct bitmap *base = data;
bitmap_set(base, find_object_pos(object->oid.hash));
mark_as_seen(object);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static long mem_seek(jas_stream_obj_t *obj, long offset, int origin)
{
jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj;
size_t newpos;
JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin));
switch (origin) {
case SEEK_SET:
newpos = offset;
break;
case SEEK_END:
newpos = m->len_ - offset;
break;
case SEEK_CUR:
newpos = m->pos_ + offset;
break;
default:
abort();
break;
}
if (newpos < 0) {
return -1;
}
m->pos_ = newpos;
return m->pos_;
}
Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder.
Also, added some comments marking I/O stream interfaces that probably
need to be changed (in the long term) to fix integer overflow problems.
CWE ID: CWE-476
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 udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
unsigned int ulen, copied;
int peeked, off = 0;
int err;
int is_udplite = IS_UDPLITE(sk);
bool slow;
if (flags & MSG_ERRQUEUE)
return ip_recv_error(sk, msg, len, addr_len);
try_again:
skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
&peeked, &off, &err);
if (!skb)
goto out;
ulen = skb->len - sizeof(struct udphdr);
copied = len;
if (copied > ulen)
copied = ulen;
else if (copied < ulen)
msg->msg_flags |= MSG_TRUNC;
/*
* If checksum is needed at all, try to do it while copying the
* data. If the data is truncated, or if we only want a partial
* coverage checksum (UDP-Lite), do it before the copy.
*/
if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {
if (udp_lib_checksum_complete(skb))
goto csum_copy_err;
}
if (skb_csum_unnecessary(skb))
err = skb_copy_datagram_msg(skb, sizeof(struct udphdr),
msg, copied);
else {
err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr),
msg);
if (err == -EINVAL)
goto csum_copy_err;
}
if (unlikely(err)) {
trace_kfree_skb(skb, udp_recvmsg);
if (!peeked) {
atomic_inc(&sk->sk_drops);
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INERRORS, is_udplite);
}
goto out_free;
}
if (!peeked)
UDP_INC_STATS_USER(sock_net(sk),
UDP_MIB_INDATAGRAMS, is_udplite);
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = udp_hdr(skb)->source;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr));
err = copied;
if (flags & MSG_TRUNC)
err = ulen;
out_free:
skb_free_datagram_locked(sk, skb);
out:
return err;
csum_copy_err:
slow = lock_sock_fast(sk);
if (!skb_kill_datagram(sk, skb, flags)) {
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite);
UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite);
}
unlock_sock_fast(sk, slow);
/* starting over for a new packet, but check if we need to yield */
cond_resched();
msg->msg_flags &= ~MSG_TRUNC;
goto try_again;
}
Commit Message: udp: properly support MSG_PEEK with truncated buffers
Backport of this upstream commit into stable kernels :
89c22d8c3b27 ("net: Fix skb csum races when peeking")
exposed a bug in udp stack vs MSG_PEEK support, when user provides
a buffer smaller than skb payload.
In this case,
skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr),
msg->msg_iov);
returns -EFAULT.
This bug does not happen in upstream kernels since Al Viro did a great
job to replace this into :
skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);
This variant is safe vs short buffers.
For the time being, instead reverting Herbert Xu patch and add back
skb->ip_summed invalid changes, simply store the result of
udp_lib_checksum_complete() so that we avoid computing the checksum a
second time, and avoid the problematic
skb_copy_and_csum_datagram_iovec() call.
This patch can be applied on recent kernels as it avoids a double
checksumming, then backported to stable kernels as a bug fix.
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-358
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 OPENSSL_fork_child(void)
{
rand_fork();
}
Commit Message:
CWE ID: CWE-330
Target: 1
Example 2:
Code: bool RenderViewImpl::IsEditableNode(const WebKit::WebNode& node) {
bool is_editable_node = false;
if (!node.isNull()) {
if (node.isContentEditable()) {
is_editable_node = true;
} else if (node.isElementNode()) {
is_editable_node =
node.toConst<WebElement>().isTextFormControlElement();
}
}
return is_editable_node;
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
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 BrowserEventRouter::TabReplacedAt(TabStripModel* tab_strip_model,
WebContents* old_contents,
WebContents* new_contents,
int index) {
const int new_tab_id = ExtensionTabUtil::GetTabId(new_contents);
const int old_tab_id = ExtensionTabUtil::GetTabId(old_contents);
scoped_ptr<ListValue> args(new ListValue());
args->Append(Value::CreateIntegerValue(new_tab_id));
args->Append(Value::CreateIntegerValue(old_tab_id));
DispatchEvent(Profile::FromBrowserContext(new_contents->GetBrowserContext()),
events::kOnTabReplaced,
args.Pass(),
EventRouter::USER_GESTURE_UNKNOWN);
const int removed_count = tab_entries_.erase(old_tab_id);
DCHECK_GT(removed_count, 0);
UnregisterForTabNotifications(old_contents);
if (!GetTabEntry(new_contents)) {
tab_entries_[new_tab_id] = TabEntry();
RegisterForTabNotifications(new_contents);
}
}
Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the
"tabs" permission.
BUG=168442
Review URL: https://chromiumcodereview.appspot.com/11824004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98
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: SYSCALL_DEFINE2(timerfd_create, int, clockid, int, flags)
{
int ufd;
struct timerfd_ctx *ctx;
/* Check the TFD_* constants for consistency. */
BUILD_BUG_ON(TFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(TFD_NONBLOCK != O_NONBLOCK);
if ((flags & ~TFD_CREATE_FLAGS) ||
(clockid != CLOCK_MONOTONIC &&
clockid != CLOCK_REALTIME &&
clockid != CLOCK_REALTIME_ALARM &&
clockid != CLOCK_BOOTTIME &&
clockid != CLOCK_BOOTTIME_ALARM))
return -EINVAL;
if (!capable(CAP_WAKE_ALARM) &&
(clockid == CLOCK_REALTIME_ALARM ||
clockid == CLOCK_BOOTTIME_ALARM))
return -EPERM;
ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
if (!ctx)
return -ENOMEM;
init_waitqueue_head(&ctx->wqh);
ctx->clockid = clockid;
if (isalarm(ctx))
alarm_init(&ctx->t.alarm,
ctx->clockid == CLOCK_REALTIME_ALARM ?
ALARM_REALTIME : ALARM_BOOTTIME,
timerfd_alarmproc);
else
hrtimer_init(&ctx->t.tmr, clockid, HRTIMER_MODE_ABS);
ctx->moffs = ktime_mono_to_real(0);
ufd = anon_inode_getfd("[timerfd]", &timerfd_fops, ctx,
O_RDWR | (flags & TFD_SHARED_FCNTL_FLAGS));
if (ufd < 0)
kfree(ctx);
return ufd;
}
Commit Message: timerfd: Protect the might cancel mechanism proper
The handling of the might_cancel queueing is not properly protected, so
parallel operations on the file descriptor can race with each other and
lead to list corruptions or use after free.
Protect the context for these operations with a seperate lock.
The wait queue lock cannot be reused for this because that would create a
lock inversion scenario vs. the cancel lock. Replacing might_cancel with an
atomic (atomic_t or atomic bit) does not help either because it still can
race vs. the actual list operation.
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: "[email protected]"
Cc: syzkaller <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Link: http://lkml.kernel.org/r/alpine.DEB.2.20.1701311521430.3457@nanos
Signed-off-by: Thomas Gleixner <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static size_t TracePath(MVGInfo *mvg_info,const char *path,
ExceptionInfo *exception)
{
char
*next_token,
token[MagickPathExtent];
const char
*p;
double
x,
y;
int
attribute,
last_attribute;
MagickBooleanType
status;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
ssize_t
subpath_offset;
subpath_offset=mvg_info->offset;
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
status=MagickTrue;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
if (status == MagickFalse)
break;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
double
angle = 0.0;
MagickBooleanType
large_arc = MagickFalse,
sweep = MagickFalse;
PointInfo
arc = {0.0, 0.0};
/*
Elliptical arc.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
arc.x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
arc.y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Cubic Bézier curve.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,4) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
/*
Line to.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
/*
Move to.
*/
if (mvg_info->offset != subpath_offset)
{
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
subpath_offset=mvg_info->offset;
}
i=0;
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Quadratic Bézier curve.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,3) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Cubic Bézier curve.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,4) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
last_attribute=attribute;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Quadratic Bézier curve.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (status == MagickFalse)
break;
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,3) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
last_attribute=attribute;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
/*
Line to.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
/*
Close path.
*/
point=start;
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
primitive_info->closed_subpath=MagickTrue;
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
subpath_offset=mvg_info->offset;
z_count++;
break;
}
default:
{
ThrowPointExpectedException(token,exception);
break;
}
}
}
if (status == MagickFalse)
return(0);
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
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: base::ProcessHandle TabLifecycleUnitSource::TabLifecycleUnit::GetProcessHandle()
const {
content::RenderFrameHost* main_frame = GetWebContents()->GetMainFrame();
if (!main_frame)
return base::ProcessHandle();
content::RenderProcessHost* process = main_frame->GetProcess();
if (!process)
return base::ProcessHandle();
return process->GetProcess().Handle();
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
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: static int __init big_key_init(void)
{
return register_key_type(&key_type_big_key);
}
Commit Message: KEYS: Sort out big_key initialisation
big_key has two separate initialisation functions, one that registers the
key type and one that registers the crypto. If the key type fails to
register, there's no problem if the crypto registers successfully because
there's no way to reach the crypto except through the key type.
However, if the key type registers successfully but the crypto does not,
big_key_rng and big_key_blkcipher may end up set to NULL - but the code
neither checks for this nor unregisters the big key key type.
Furthermore, since the key type is registered before the crypto, it is
theoretically possible for the kernel to try adding a big_key before the
crypto is set up, leading to the same effect.
Fix this by merging big_key_crypto_init() and big_key_init() and calling
the resulting function late. If they're going to be encrypted, we
shouldn't be creating big_keys before we have the facilities to do the
encryption available. The key type registration is also moved after the
crypto initialisation.
The fix also includes message printing on failure.
If the big_key type isn't correctly set up, simply doing:
dd if=/dev/zero bs=4096 count=1 | keyctl padd big_key a @s
ought to cause an oops.
Fixes: 13100a72f40f5748a04017e0ab3df4cf27c809ef ('Security: Keys: Big keys stored encrypted')
Signed-off-by: David Howells <[email protected]>
cc: Peter Hlavaty <[email protected]>
cc: Kirill Marinushkin <[email protected]>
cc: Artem Savkov <[email protected]>
cc: [email protected]
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
{
struct bpf_verifier_state *state = env->cur_state;
struct bpf_reg_state *regs = state->regs, *reg;
int i;
for (i = 0; i < MAX_BPF_REG; i++)
if (reg_is_pkt_pointer_any(®s[i]))
mark_reg_unknown(env, regs, i);
for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
if (state->stack[i].slot_type[0] != STACK_SPILL)
continue;
reg = &state->stack[i].spilled_ptr;
if (reg_is_pkt_pointer_any(reg))
__mark_reg_unknown(reg);
}
}
Commit Message: bpf: fix branch pruning logic
when the verifier detects that register contains a runtime constant
and it's compared with another constant it will prune exploration
of the branch that is guaranteed not to be taken at runtime.
This is all correct, but malicious program may be constructed
in such a way that it always has a constant comparison and
the other branch is never taken under any conditions.
In this case such path through the program will not be explored
by the verifier. It won't be taken at run-time either, but since
all instructions are JITed the malicious program may cause JITs
to complain about using reserved fields, etc.
To fix the issue we have to track the instructions explored by
the verifier and sanitize instructions that are dead at run time
with NOPs. We cannot reject such dead code, since llvm generates
it for valid C code, since it doesn't do as much data flow
analysis as the verifier does.
Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)")
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[email protected]>
Signed-off-by: Daniel Borkmann <[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 bool compare_img(const vpx_image_t *img1,
const vpx_image_t *img2) {
bool match = (img1->fmt == img2->fmt) &&
(img1->d_w == img2->d_w) &&
(img1->d_h == img2->d_h);
const unsigned int width_y = img1->d_w;
const unsigned int height_y = img1->d_h;
unsigned int i;
for (i = 0; i < height_y; ++i)
match = (memcmp(img1->planes[VPX_PLANE_Y] + i * img1->stride[VPX_PLANE_Y],
img2->planes[VPX_PLANE_Y] + i * img2->stride[VPX_PLANE_Y],
width_y) == 0) && match;
const unsigned int width_uv = (img1->d_w + 1) >> 1;
const unsigned int height_uv = (img1->d_h + 1) >> 1;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_U] + i * img1->stride[VPX_PLANE_U],
img2->planes[VPX_PLANE_U] + i * img2->stride[VPX_PLANE_U],
width_uv) == 0) && match;
for (i = 0; i < height_uv; ++i)
match = (memcmp(img1->planes[VPX_PLANE_V] + i * img1->stride[VPX_PLANE_V],
img2->planes[VPX_PLANE_V] + i * img2->stride[VPX_PLANE_V],
width_uv) == 0) && match;
return match;
}
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
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 snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *host_iface;
struct usb_interface_descriptor *altsd;
void *control_header;
int i, protocol;
/* find audiocontrol interface */
host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
control_header = snd_usb_find_csint_desc(host_iface->extra,
host_iface->extralen,
NULL, UAC_HEADER);
altsd = get_iface_desc(host_iface);
protocol = altsd->bInterfaceProtocol;
if (!control_header) {
dev_err(&dev->dev, "cannot find UAC_HEADER\n");
return -EINVAL;
}
switch (protocol) {
default:
dev_warn(&dev->dev,
"unknown interface protocol %#02x, assuming v1\n",
protocol);
/* fall through */
case UAC_VERSION_1: {
struct uac1_ac_header_descriptor *h1 = control_header;
if (!h1->bInCollection) {
dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
return -EINVAL;
}
if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
return -EINVAL;
}
for (i = 0; i < h1->bInCollection; i++)
snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
break;
}
case UAC_VERSION_2: {
struct usb_interface_assoc_descriptor *assoc =
usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
if (!assoc) {
/*
* Firmware writers cannot count to three. So to find
* the IAD on the NuForce UDH-100, also check the next
* interface.
*/
struct usb_interface *iface =
usb_ifnum_to_if(dev, ctrlif + 1);
if (iface &&
iface->intf_assoc &&
iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
assoc = iface->intf_assoc;
}
if (!assoc) {
dev_err(&dev->dev, "Audio class v2 interfaces need an interface association\n");
return -EINVAL;
}
for (i = 0; i < assoc->bInterfaceCount; i++) {
int intf = assoc->bFirstInterface + i;
if (intf != ctrlif)
snd_usb_create_stream(chip, ctrlif, intf);
}
break;
}
}
return 0;
}
Commit Message: ALSA: usb-audio: Check out-of-bounds access by corrupted buffer descriptor
When a USB-audio device receives a maliciously adjusted or corrupted
buffer descriptor, the USB-audio driver may access an out-of-bounce
value at its parser. This was detected by syzkaller, something like:
BUG: KASAN: slab-out-of-bounds in usb_audio_probe+0x27b2/0x2ab0
Read of size 1 at addr ffff88006b83a9e8 by task kworker/0:1/24
CPU: 0 PID: 24 Comm: kworker/0:1 Not tainted 4.14.0-rc1-42251-gebb2c2437d80 #224
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011
Workqueue: usb_hub_wq hub_event
Call Trace:
__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+0x22f/0x340 mm/kasan/report.c:409
__asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427
snd_usb_create_streams sound/usb/card.c:248
usb_audio_probe+0x27b2/0x2ab0 sound/usb/card.c:605
usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932
generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174
usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266
really_probe drivers/base/dd.c:413
driver_probe_device+0x610/0xa00 drivers/base/dd.c:557
__device_attach_driver+0x230/0x290 drivers/base/dd.c:653
bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463
__device_attach+0x26e/0x3d0 drivers/base/dd.c:710
device_initial_probe+0x1f/0x30 drivers/base/dd.c:757
bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523
device_add+0xd0b/0x1660 drivers/base/core.c:1835
usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457
hub_port_connect drivers/usb/core/hub.c:4903
hub_port_connect_change drivers/usb/core/hub.c:5009
port_event drivers/usb/core/hub.c:5115
hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195
process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119
worker_thread+0x221/0x1850 kernel/workqueue.c:2253
kthread+0x3a1/0x470 kernel/kthread.c:231
ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431
This patch adds the checks of out-of-bounce accesses at appropriate
places and bails out when it goes out of the given buffer.
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-125
Target: 1
Example 2:
Code: base::SequencedTaskRunner* TaskRunner() const {
return context_->TaskRunner();
}
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: 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 ctr_crypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct crypto_sparc64_aes_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
struct blkcipher_walk walk;
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, AES_BLOCK_SIZE);
desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
ctx->ops->load_encrypt_keys(&ctx->key[0]);
while ((nbytes = walk.nbytes) >= AES_BLOCK_SIZE) {
unsigned int block_len = nbytes & AES_BLOCK_MASK;
if (likely(block_len)) {
ctx->ops->ctr_crypt(&ctx->key[0],
(const u64 *)walk.src.virt.addr,
(u64 *) walk.dst.virt.addr,
block_len, (u64 *) walk.iv);
}
nbytes &= AES_BLOCK_SIZE - 1;
err = blkcipher_walk_done(desc, &walk, nbytes);
}
if (walk.nbytes) {
ctr_crypt_final(ctx, &walk);
err = blkcipher_walk_done(desc, &walk, 0);
}
fprs_write(0);
return err;
}
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
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: QuicConnectionHelperTest()
: framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)),
creator_(guid_, &framer_),
net_log_(BoundNetLog()),
scheduler_(new MockScheduler()),
socket_(&empty_data_, net_log_.net_log()),
runner_(new TestTaskRunner(&clock_)),
helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)),
connection_(guid_, IPEndPoint(), helper_),
frame1_(1, false, 0, data1) {
connection_.set_visitor(&visitor_);
connection_.SetScheduler(scheduler_);
}
Commit Message: Fix uninitialized access in QuicConnectionHelperTest
BUG=159928
Review URL: https://chromiumcodereview.appspot.com/11360153
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: void SettingLevelBubbleDelegateView::Init() {
SetLayoutManager(new views::FillLayout());
view_ = new SettingLevelBubbleView();
AddChildView(view_);
}
Commit Message: chromeos: Move audio, power, and UI files into subdirs.
This moves more files from chrome/browser/chromeos/ into
subdirectories.
BUG=chromium-os:22896
TEST=did chrome os builds both with and without aura
TBR=sky
Review URL: http://codereview.chromium.org/9125006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 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: nfsd4_link(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate,
struct nfsd4_link *link)
{
__be32 status = nfserr_nofilehandle;
if (!cstate->save_fh.fh_dentry)
return status;
status = nfsd_link(rqstp, &cstate->current_fh,
link->li_name, link->li_namelen, &cstate->save_fh);
if (!status)
set_change_info(&link->li_cinfo, &cstate->current_fh);
return status;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404
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::unique_ptr<content::BluetoothChooser> Browser::RunBluetoothChooser(
content::RenderFrameHost* frame,
const content::BluetoothChooser::EventHandler& event_handler) {
std::unique_ptr<BluetoothChooserController> bluetooth_chooser_controller(
new BluetoothChooserController(frame, event_handler));
std::unique_ptr<BluetoothChooserDesktop> bluetooth_chooser_desktop(
new BluetoothChooserDesktop(bluetooth_chooser_controller.get()));
std::unique_ptr<ChooserBubbleDelegate> chooser_bubble_delegate(
new ChooserBubbleDelegate(frame,
std::move(bluetooth_chooser_controller)));
Browser* browser = chrome::FindBrowserWithWebContents(
WebContents::FromRenderFrameHost(frame));
BubbleReference bubble_reference = browser->GetBubbleManager()->ShowBubble(
std::move(chooser_bubble_delegate));
return std::move(bluetooth_chooser_desktop);
}
Commit Message: Ensure device choosers are closed on navigation
The requestDevice() IPCs can race with navigation. This change ensures
that choosers are closed on navigation and adds browser tests to
exercise this for Web Bluetooth and WebUSB.
Bug: 723503
Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c
Reviewed-on: https://chromium-review.googlesource.com/1099961
Commit-Queue: Reilly Grant <[email protected]>
Reviewed-by: Michael Wasserman <[email protected]>
Reviewed-by: Jeffrey Yasskin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#569900}
CWE ID: CWE-362
Target: 1
Example 2:
Code: static inline bool isValidNameASCII(const CharType* characters, unsigned length)
{
CharType c = characters[0];
if (!(isASCIIAlpha(c) || c == ':' || c == '_'))
return false;
for (unsigned i = 1; i < length; ++i) {
c = characters[i];
if (!(isASCIIAlphanumeric(c) || c == ':' || c == '_' || c == '-' || c == '.'))
return false;
}
return true;
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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 void create_object_entry(const unsigned char *sha1,
enum object_type type,
uint32_t hash,
int exclude,
int no_try_delta,
uint32_t index_pos,
struct packed_git *found_pack,
off_t found_offset)
{
struct object_entry *entry;
entry = packlist_alloc(&to_pack, sha1, index_pos);
entry->hash = hash;
if (type)
entry->type = type;
if (exclude)
entry->preferred_base = 1;
else
nr_result++;
if (found_pack) {
entry->in_pack = found_pack;
entry->in_pack_offset = found_offset;
}
entry->no_try_delta = no_try_delta;
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119
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: double ConvolverNode::latencyTime() const
{
return m_reverb ? m_reverb->latencyFrames() / static_cast<double>(sampleRate()) : 0;
}
Commit Message: Fix threading races on ConvolverNode::m_reverb in ConvolverNode::latencyFrames()
According to the crash report (https://cluster-fuzz.appspot.com/testcase?key=6515787040817152),
ConvolverNode::m_reverb races between ConvolverNode::latencyFrames() and ConvolverNode::setBuffer().
This CL adds a proper lock for ConvolverNode::m_reverb.
BUG=223962
No tests because the crash depends on threading races and thus not reproducible.
Review URL: https://chromiumcodereview.appspot.com/23514037
git-svn-id: svn://svn.chromium.org/blink/trunk@157245 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-362
Target: 1
Example 2:
Code: psf_open_rsrc (SF_PRIVATE *psf)
{
if (psf->rsrc.handle != NULL)
return 0 ;
/* Test for MacOSX style resource fork on HPFS or HPFS+ filesystems. */
snprintf (psf->rsrc.path.c, sizeof (psf->rsrc.path.c), "%s/rsrc", psf->file.path.c) ;
psf->error = SFE_NO_ERROR ;
if ((psf->rsrc.handle = psf_open_handle (&psf->rsrc)) != NULL)
{ psf->rsrclength = psf_get_filelen_handle (psf->rsrc.handle) ;
return SFE_NO_ERROR ;
} ;
/*
** Now try for a resource fork stored as a separate file in the same
** directory, but preceded with a dot underscore.
*/
snprintf (psf->rsrc.path.c, sizeof (psf->rsrc.path.c), "%s._%s", psf->file.dir.c, psf->file.name.c) ;
psf->error = SFE_NO_ERROR ;
if ((psf->rsrc.handle = psf_open_handle (&psf->rsrc)) != NULL)
{ psf->rsrclength = psf_get_filelen_handle (psf->rsrc.handle) ;
return SFE_NO_ERROR ;
} ;
/*
** Now try for a resource fork stored in a separate file in the
** .AppleDouble/ directory.
*/
snprintf (psf->rsrc.path.c, sizeof (psf->rsrc.path.c), "%s.AppleDouble/%s", psf->file.dir.c, psf->file.name.c) ;
psf->error = SFE_NO_ERROR ;
if ((psf->rsrc.handle = psf_open_handle (&psf->rsrc)) != NULL)
{ psf->rsrclength = psf_get_filelen_handle (psf->rsrc.handle) ;
return SFE_NO_ERROR ;
} ;
/* No resource file found. */
if (psf->rsrc.handle == NULL)
psf_log_syserr (psf, GetLastError ()) ;
psf->rsrc.handle = NULL ;
return psf->error ;
} /* psf_open_rsrc */
Commit Message: src/file_io.c : Prevent potential divide-by-zero.
Closes: https://github.com/erikd/libsndfile/issues/92
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: int git_index_snapshot_new(git_vector *snap, git_index *index)
{
int error;
GIT_REFCOUNT_INC(index);
git_atomic_inc(&index->readers);
git_vector_sort(&index->entries);
error = git_vector_dup(snap, &index->entries, index->entries._cmp);
if (error < 0)
git_index_free(index);
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: | 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* allocFromUTF32(const char32_t* in, size_t len)
{
if (len == 0) {
return getEmptyString();
}
const ssize_t bytes = utf32_to_utf8_length(in, len);
if (bytes < 0) {
return getEmptyString();
}
SharedBuffer* buf = SharedBuffer::alloc(bytes+1);
ALOG_ASSERT(buf, "Unable to allocate shared buffer");
if (!buf) {
return getEmptyString();
}
char* str = (char*) buf->data();
utf32_to_utf8(in, len, str);
return str;
}
Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8
Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length
is causing a heap overflow.
Correcting the length computation and adding bound checks to the
conversion functions.
Test: ran libutils_tests
Bug: 29250543
Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb
(cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1)
CWE ID: CWE-119
Target: 1
Example 2:
Code: int tls1_set_sigalgs(CERT *c, const int *psig_nids, size_t salglen, int client)
{
unsigned char *sigalgs, *sptr;
int rhash, rsign;
size_t i;
if (salglen & 1)
return 0;
sigalgs = OPENSSL_malloc(salglen);
if (sigalgs == NULL)
return 0;
for (i = 0, sptr = sigalgs; i < salglen; i+=2)
{
rhash = tls12_find_id(*psig_nids++, tls12_md,
sizeof(tls12_md)/sizeof(tls12_lookup));
rsign = tls12_find_id(*psig_nids++, tls12_sig,
sizeof(tls12_sig)/sizeof(tls12_lookup));
if (rhash == -1 || rsign == -1)
goto err;
*sptr++ = rhash;
*sptr++ = rsign;
}
if (client)
{
if (c->client_sigalgs)
OPENSSL_free(c->client_sigalgs);
c->client_sigalgs = sigalgs;
c->client_sigalgslen = salglen;
}
else
{
if (c->conf_sigalgs)
OPENSSL_free(c->conf_sigalgs);
c->conf_sigalgs = sigalgs;
c->conf_sigalgslen = salglen;
}
return 1;
err:
OPENSSL_free(sigalgs);
return 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: nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp,
struct svc_export *exp,
struct dentry *dentry, u32 *bmval,
struct svc_rqst *rqstp, int ignore_crossmnt)
{
u32 bmval0 = bmval[0];
u32 bmval1 = bmval[1];
u32 bmval2 = bmval[2];
struct kstat stat;
struct svc_fh *tempfh = NULL;
struct kstatfs statfs;
__be32 *p;
int starting_len = xdr->buf->len;
int attrlen_offset;
__be32 attrlen;
u32 dummy;
u64 dummy64;
u32 rdattr_err = 0;
__be32 status;
int err;
struct nfs4_acl *acl = NULL;
void *context = NULL;
int contextlen;
bool contextsupport = false;
struct nfsd4_compoundres *resp = rqstp->rq_resp;
u32 minorversion = resp->cstate.minorversion;
struct path path = {
.mnt = exp->ex_path.mnt,
.dentry = dentry,
};
struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
BUG_ON(bmval1 & NFSD_WRITEONLY_ATTRS_WORD1);
BUG_ON(!nfsd_attrs_supported(minorversion, bmval));
if (exp->ex_fslocs.migrated) {
status = fattr_handle_absent_fs(&bmval0, &bmval1, &bmval2, &rdattr_err);
if (status)
goto out;
}
err = vfs_getattr(&path, &stat, STATX_BASIC_STATS, AT_STATX_SYNC_AS_STAT);
if (err)
goto out_nfserr;
if ((bmval0 & (FATTR4_WORD0_FILES_AVAIL | FATTR4_WORD0_FILES_FREE |
FATTR4_WORD0_FILES_TOTAL | FATTR4_WORD0_MAXNAME)) ||
(bmval1 & (FATTR4_WORD1_SPACE_AVAIL | FATTR4_WORD1_SPACE_FREE |
FATTR4_WORD1_SPACE_TOTAL))) {
err = vfs_statfs(&path, &statfs);
if (err)
goto out_nfserr;
}
if ((bmval0 & (FATTR4_WORD0_FILEHANDLE | FATTR4_WORD0_FSID)) && !fhp) {
tempfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL);
status = nfserr_jukebox;
if (!tempfh)
goto out;
fh_init(tempfh, NFS4_FHSIZE);
status = fh_compose(tempfh, exp, dentry, NULL);
if (status)
goto out;
fhp = tempfh;
}
if (bmval0 & FATTR4_WORD0_ACL) {
err = nfsd4_get_nfs4_acl(rqstp, dentry, &acl);
if (err == -EOPNOTSUPP)
bmval0 &= ~FATTR4_WORD0_ACL;
else if (err == -EINVAL) {
status = nfserr_attrnotsupp;
goto out;
} else if (err != 0)
goto out_nfserr;
}
#ifdef CONFIG_NFSD_V4_SECURITY_LABEL
if ((bmval2 & FATTR4_WORD2_SECURITY_LABEL) ||
bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) {
if (exp->ex_flags & NFSEXP_SECURITY_LABEL)
err = security_inode_getsecctx(d_inode(dentry),
&context, &contextlen);
else
err = -EOPNOTSUPP;
contextsupport = (err == 0);
if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) {
if (err == -EOPNOTSUPP)
bmval2 &= ~FATTR4_WORD2_SECURITY_LABEL;
else if (err)
goto out_nfserr;
}
}
#endif /* CONFIG_NFSD_V4_SECURITY_LABEL */
status = nfsd4_encode_bitmap(xdr, bmval0, bmval1, bmval2);
if (status)
goto out;
attrlen_offset = xdr->buf->len;
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
p++; /* to be backfilled later */
if (bmval0 & FATTR4_WORD0_SUPPORTED_ATTRS) {
u32 supp[3];
memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp));
if (!IS_POSIXACL(dentry->d_inode))
supp[0] &= ~FATTR4_WORD0_ACL;
if (!contextsupport)
supp[2] &= ~FATTR4_WORD2_SECURITY_LABEL;
if (!supp[2]) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(2);
*p++ = cpu_to_be32(supp[0]);
*p++ = cpu_to_be32(supp[1]);
} else {
p = xdr_reserve_space(xdr, 16);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(3);
*p++ = cpu_to_be32(supp[0]);
*p++ = cpu_to_be32(supp[1]);
*p++ = cpu_to_be32(supp[2]);
}
}
if (bmval0 & FATTR4_WORD0_TYPE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
dummy = nfs4_file_type(stat.mode);
if (dummy == NF4BAD) {
status = nfserr_serverfault;
goto out;
}
*p++ = cpu_to_be32(dummy);
}
if (bmval0 & FATTR4_WORD0_FH_EXPIRE_TYPE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
if (exp->ex_flags & NFSEXP_NOSUBTREECHECK)
*p++ = cpu_to_be32(NFS4_FH_PERSISTENT);
else
*p++ = cpu_to_be32(NFS4_FH_PERSISTENT|
NFS4_FH_VOL_RENAME);
}
if (bmval0 & FATTR4_WORD0_CHANGE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = encode_change(p, &stat, d_inode(dentry), exp);
}
if (bmval0 & FATTR4_WORD0_SIZE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, stat.size);
}
if (bmval0 & FATTR4_WORD0_LINK_SUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_SYMLINK_SUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_NAMED_ATTR) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_FSID) {
p = xdr_reserve_space(xdr, 16);
if (!p)
goto out_resource;
if (exp->ex_fslocs.migrated) {
p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MAJOR);
p = xdr_encode_hyper(p, NFS4_REFERRAL_FSID_MINOR);
} else switch(fsid_source(fhp)) {
case FSIDSOURCE_FSID:
p = xdr_encode_hyper(p, (u64)exp->ex_fsid);
p = xdr_encode_hyper(p, (u64)0);
break;
case FSIDSOURCE_DEV:
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(MAJOR(stat.dev));
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(MINOR(stat.dev));
break;
case FSIDSOURCE_UUID:
p = xdr_encode_opaque_fixed(p, exp->ex_uuid,
EX_UUID_LEN);
break;
}
}
if (bmval0 & FATTR4_WORD0_UNIQUE_HANDLES) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_LEASE_TIME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(nn->nfsd4_lease);
}
if (bmval0 & FATTR4_WORD0_RDATTR_ERROR) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(rdattr_err);
}
if (bmval0 & FATTR4_WORD0_ACL) {
struct nfs4_ace *ace;
if (acl == NULL) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
goto out_acl;
}
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(acl->naces);
for (ace = acl->aces; ace < acl->aces + acl->naces; ace++) {
p = xdr_reserve_space(xdr, 4*3);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(ace->type);
*p++ = cpu_to_be32(ace->flag);
*p++ = cpu_to_be32(ace->access_mask &
NFS4_ACE_MASK_ALL);
status = nfsd4_encode_aclname(xdr, rqstp, ace);
if (status)
goto out;
}
}
out_acl:
if (bmval0 & FATTR4_WORD0_ACLSUPPORT) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(IS_POSIXACL(dentry->d_inode) ?
ACL4_SUPPORT_ALLOW_ACL|ACL4_SUPPORT_DENY_ACL : 0);
}
if (bmval0 & FATTR4_WORD0_CANSETTIME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_CASE_INSENSITIVE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
}
if (bmval0 & FATTR4_WORD0_CASE_PRESERVING) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_CHOWN_RESTRICTED) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_FILEHANDLE) {
p = xdr_reserve_space(xdr, fhp->fh_handle.fh_size + 4);
if (!p)
goto out_resource;
p = xdr_encode_opaque(p, &fhp->fh_handle.fh_base,
fhp->fh_handle.fh_size);
}
if (bmval0 & FATTR4_WORD0_FILEID) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, stat.ino);
}
if (bmval0 & FATTR4_WORD0_FILES_AVAIL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_ffree);
}
if (bmval0 & FATTR4_WORD0_FILES_FREE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_ffree);
}
if (bmval0 & FATTR4_WORD0_FILES_TOTAL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) statfs.f_files);
}
if (bmval0 & FATTR4_WORD0_FS_LOCATIONS) {
status = nfsd4_encode_fs_locations(xdr, rqstp, exp);
if (status)
goto out;
}
if (bmval0 & FATTR4_WORD0_HOMOGENEOUS) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval0 & FATTR4_WORD0_MAXFILESIZE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, exp->ex_path.mnt->mnt_sb->s_maxbytes);
}
if (bmval0 & FATTR4_WORD0_MAXLINK) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(255);
}
if (bmval0 & FATTR4_WORD0_MAXNAME) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(statfs.f_namelen);
}
if (bmval0 & FATTR4_WORD0_MAXREAD) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp));
}
if (bmval0 & FATTR4_WORD0_MAXWRITE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (u64) svc_max_payload(rqstp));
}
if (bmval1 & FATTR4_WORD1_MODE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.mode & S_IALLUGO);
}
if (bmval1 & FATTR4_WORD1_NO_TRUNC) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(1);
}
if (bmval1 & FATTR4_WORD1_NUMLINKS) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.nlink);
}
if (bmval1 & FATTR4_WORD1_OWNER) {
status = nfsd4_encode_user(xdr, rqstp, stat.uid);
if (status)
goto out;
}
if (bmval1 & FATTR4_WORD1_OWNER_GROUP) {
status = nfsd4_encode_group(xdr, rqstp, stat.gid);
if (status)
goto out;
}
if (bmval1 & FATTR4_WORD1_RAWDEV) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
*p++ = cpu_to_be32((u32) MAJOR(stat.rdev));
*p++ = cpu_to_be32((u32) MINOR(stat.rdev));
}
if (bmval1 & FATTR4_WORD1_SPACE_AVAIL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_bavail * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_FREE) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_bfree * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_TOTAL) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)statfs.f_blocks * (u64)statfs.f_bsize;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_SPACE_USED) {
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
dummy64 = (u64)stat.blocks << 9;
p = xdr_encode_hyper(p, dummy64);
}
if (bmval1 & FATTR4_WORD1_TIME_ACCESS) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.atime.tv_sec);
*p++ = cpu_to_be32(stat.atime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_TIME_DELTA) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(0);
*p++ = cpu_to_be32(1);
*p++ = cpu_to_be32(0);
}
if (bmval1 & FATTR4_WORD1_TIME_METADATA) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.ctime.tv_sec);
*p++ = cpu_to_be32(stat.ctime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_TIME_MODIFY) {
p = xdr_reserve_space(xdr, 12);
if (!p)
goto out_resource;
p = xdr_encode_hyper(p, (s64)stat.mtime.tv_sec);
*p++ = cpu_to_be32(stat.mtime.tv_nsec);
}
if (bmval1 & FATTR4_WORD1_MOUNTED_ON_FILEID) {
struct kstat parent_stat;
u64 ino = stat.ino;
p = xdr_reserve_space(xdr, 8);
if (!p)
goto out_resource;
/*
* Get parent's attributes if not ignoring crossmount
* and this is the root of a cross-mounted filesystem.
*/
if (ignore_crossmnt == 0 &&
dentry == exp->ex_path.mnt->mnt_root) {
err = get_parent_attributes(exp, &parent_stat);
if (err)
goto out_nfserr;
ino = parent_stat.ino;
}
p = xdr_encode_hyper(p, ino);
}
#ifdef CONFIG_NFSD_PNFS
if (bmval1 & FATTR4_WORD1_FS_LAYOUT_TYPES) {
status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_LAYOUT_TYPES) {
status = nfsd4_encode_layout_types(xdr, exp->ex_layout_types);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_LAYOUT_BLKSIZE) {
p = xdr_reserve_space(xdr, 4);
if (!p)
goto out_resource;
*p++ = cpu_to_be32(stat.blksize);
}
#endif /* CONFIG_NFSD_PNFS */
if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) {
status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0,
NFSD_SUPPATTR_EXCLCREAT_WORD1,
NFSD_SUPPATTR_EXCLCREAT_WORD2);
if (status)
goto out;
}
if (bmval2 & FATTR4_WORD2_SECURITY_LABEL) {
status = nfsd4_encode_security_label(xdr, rqstp, context,
contextlen);
if (status)
goto out;
}
attrlen = htonl(xdr->buf->len - attrlen_offset - 4);
write_bytes_to_xdr_buf(xdr->buf, attrlen_offset, &attrlen, 4);
status = nfs_ok;
out:
#ifdef CONFIG_NFSD_V4_SECURITY_LABEL
if (context)
security_release_secctx(context, contextlen);
#endif /* CONFIG_NFSD_V4_SECURITY_LABEL */
kfree(acl);
if (tempfh) {
fh_put(tempfh);
kfree(tempfh);
}
if (status)
xdr_truncate_encode(xdr, starting_len);
return status;
out_nfserr:
status = nfserrno(err);
goto out;
out_resource:
status = nfserr_resource;
goto out;
}
Commit Message: nfsd: encoders mustn't use unitialized values in error cases
In error cases, lgp->lg_layout_type may be out of bounds; so we
shouldn't be using it until after the check of nfserr.
This was seen to crash nfsd threads when the server receives a LAYOUTGET
request with a large layout type.
GETDEVICEINFO has the same problem.
Reported-by: Ari Kauppi <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-129
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: IMPEG2D_ERROR_CODES_T impeg2d_vld_decode(
dec_state_t *ps_dec,
WORD16 *pi2_outAddr, /*!< Address where decoded symbols will be stored */
const UWORD8 *pu1_scan, /*!< Scan table to be used */
UWORD8 *pu1_pos, /*!< Scan table to be used */
UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */
UWORD16 u2_chroma_flag, /*!< Chroma Block or not */
UWORD16 u2_d_picture, /*!< D Picture or not */
UWORD16 u2_intra_vlc_format, /*!< Intra VLC format */
UWORD16 u2_mpeg2, /*!< MPEG-2 or not */
WORD32 *pi4_num_coeffs /*!< Returns the number of coeffs in block */
)
{
UWORD32 u4_sym_len;
UWORD32 u4_decoded_value;
UWORD32 u4_level_first_byte;
WORD32 u4_level;
UWORD32 u4_run, u4_numCoeffs;
UWORD32 u4_buf;
UWORD32 u4_buf_nxt;
UWORD32 u4_offset;
UWORD32 *pu4_buf_aligned;
UWORD32 u4_bits;
stream_t *ps_stream = &ps_dec->s_bit_stream;
WORD32 u4_pos;
UWORD32 u4_nz_cols;
UWORD32 u4_nz_rows;
*pi4_num_coeffs = 0;
ps_dec->u4_non_zero_cols = 0;
ps_dec->u4_non_zero_rows = 0;
u4_nz_cols = ps_dec->u4_non_zero_cols;
u4_nz_rows = ps_dec->u4_non_zero_rows;
GET_TEMP_STREAM_DATA(u4_buf,u4_buf_nxt,u4_offset,pu4_buf_aligned,ps_stream)
/**************************************************************************/
/* Decode the DC coefficient in case of Intra block */
/**************************************************************************/
if(u2_intra_flag)
{
WORD32 dc_size;
WORD32 dc_diff;
WORD32 maxLen;
WORD32 idx;
maxLen = MPEG2_DCT_DC_SIZE_LEN;
idx = 0;
if(u2_chroma_flag != 0)
{
maxLen += 1;
idx++;
}
{
WORD16 end = 0;
UWORD32 maxLen_tmp = maxLen;
UWORD16 m_iBit;
/* Get the maximum number of bits needed to decode a symbol */
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,maxLen)
do
{
maxLen_tmp--;
/* Read one bit at a time from the variable to decode the huffman code */
m_iBit = (UWORD8)((u4_bits >> maxLen_tmp) & 0x1);
/* Get the next node pointer or the symbol from the tree */
end = gai2_impeg2d_dct_dc_size[idx][end][m_iBit];
}while(end > 0);
dc_size = end + MPEG2_DCT_DC_SIZE_OFFSET;
/* Flush the appropriate number of bits from the stream */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,(maxLen - maxLen_tmp),pu4_buf_aligned)
}
if (dc_size != 0)
{
UWORD32 u4_bits;
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, dc_size)
dc_diff = u4_bits;
if ((dc_diff & (1 << (dc_size - 1))) == 0) //v Probably the prediction algo?
dc_diff -= (1 << dc_size) - 1;
}
else
{
dc_diff = 0;
}
pi2_outAddr[*pi4_num_coeffs] = dc_diff;
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
if (0 != dc_diff)
{
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
u4_numCoeffs = 1;
}
/**************************************************************************/
/* Decoding of first AC coefficient in case of non Intra block */
/**************************************************************************/
else
{
/* First symbol can be 1s */
UWORD32 u4_bits;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,1)
if(u4_bits == 1)
{
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,1, pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned, 1)
if(u4_bits == 1)
{
pi2_outAddr[*pi4_num_coeffs] = -1;
}
else
{
pi2_outAddr[*pi4_num_coeffs] = 1;
}
/* This indicates the position of the coefficient. Since this is the DC
* coefficient, we put the position as 0.
*/
pu1_pos[*pi4_num_coeffs] = pu1_scan[0];
(*pi4_num_coeffs)++;
u4_numCoeffs = 1;
u4_nz_cols |= 0x01;
u4_nz_rows |= 0x01;
}
else
{
u4_numCoeffs = 0;
}
}
if (1 == u2_d_picture)
{
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE);
}
if (1 == u2_intra_vlc_format && u2_intra_flag)
{
while(1)
{
UWORD32 lead_zeros;
WORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf,u4_buf_nxt,u4_offset,u4_bits,u4_sym_len)
DecodedValue = gau2_impeg2d_tab_one_1_9[u4_bits >> 8];
u4_sym_len = (DecodedValue & 0xf);
u4_level = DecodedValue >> 9;
/* One table lookup */
if(0 != u4_level)
{
u4_run = ((DecodedValue >> 4) & 0x1f);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if (DecodedValue == END_OF_BLOCK_ONE)
{
u4_sym_len = 4;
break;
}
else
{
/*Second table lookup*/
lead_zeros = CLZ(u4_bits) - 20;/* -16 since we are dealing with WORD32 */
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
if (1 == lead_zeros)
{
u4_sym_len = ((u4_bits & 0x18) >> 3) == 2 ? 11:10;
}
else
{
u4_sym_len = 11 + lead_zeros;
}
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_one_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG2 Escape Code */
/*********************************************************************/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
}
else
{
while(1)
{
UWORD32 lead_zeros;
UWORD16 DecodedValue;
u4_sym_len = 17;
IBITS_NXT(u4_buf, u4_buf_nxt, u4_offset, u4_bits, u4_sym_len)
DecodedValue = gau2_impeg2d_tab_zero_1_9[u4_bits >> 8];
u4_sym_len = BITS(DecodedValue, 3, 0);
u4_level = ((WORD16) DecodedValue) >> 9;
if (0 != u4_level)
{
u4_run = BITS(DecodedValue, 8,4);
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
else
{
if(DecodedValue == END_OF_BLOCK_ZERO)
{
u4_sym_len = 2;
break;
}
else
{
lead_zeros = CLZ(u4_bits) - 20;/* -15 since we are dealing with WORD32 */
/*Second table lookup*/
if (0 != lead_zeros)
{
u4_bits = (u4_bits >> (6 - lead_zeros)) & 0x001F;
/* Flush the number of bits */
u4_sym_len = 11 + lead_zeros;
/* Calculate the address */
u4_bits = ((lead_zeros - 1) << 5) + u4_bits;
DecodedValue = gau2_impeg2d_tab_zero_10_16[u4_bits];
u4_run = BITS(DecodedValue, 8,4);
u4_level = ((WORD16) DecodedValue) >> 9;
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
if (1 == lead_zeros)
u4_sym_len--;
/* flushing */
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*Escape Sequence*/
else if(u2_mpeg2 == 1)
{
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,18)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 12);
u4_level = (u4_decoded_value & 0x0FFF);
if (u4_level)
u4_level = (u4_level - ((u4_level & 0x0800) << 1));
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
/*********************************************************************/
/* MPEG1 Escape Code */
/*********************************************************************/
else
{
/*-----------------------------------------------------------
* MPEG-1 Stream
*
* <See D.9.3 of MPEG-2> Run-level escape syntax
* Run-level values that cannot be coded with a VLC are coded
* by the escape code '0000 01' followed by
* either a 14-bit FLC (127 <= level <= 127),
* or a 22-bit FLC (255 <= level <= 255).
* This is described in Annex B,B.5f of MPEG-1.standard
*-----------------------------------------------------------*/
/*-----------------------------------------------------------
* First 6 bits are the value of the Run. Next is First 8 bits
* of Level. These bits decide whether it is 14 bit FLC or
* 22-bit FLC.
*
* If( first 8 bits of Level == '1000000' or '00000000')
* then its is 22-bit FLC.
* else
* it is 14-bit FLC.
*-----------------------------------------------------------*/
u4_sym_len = 6;
FLUSH_BITS(u4_offset,u4_buf,u4_buf_nxt,u4_sym_len,pu4_buf_aligned)
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,14)
u4_decoded_value = u4_bits;
u4_run = (u4_decoded_value >> 8);
u4_level_first_byte = (u4_decoded_value & 0x0FF);
if(u4_level_first_byte & 0x7F)
{
/*-------------------------------------------------------
* First 8 bits of level are neither 1000000 nor 00000000
* Hence 14-bit FLC (Last 8 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_First_Byte - 256 : Level_First_Byte
*-------------------------------------------------------*/
u4_level = (u4_level_first_byte -
((u4_level_first_byte & 0x80) << 1));
}
else
{
/*-------------------------------------------------------
* Next 8 bits are either 1000000 or 00000000
* Hence 22-bit FLC (Last 16 bits are used to get level)
*
* Level = (msb of Level_First_Byte is 1)?
* Level_Second_Byte - 256 : Level_Second_Byte
*-------------------------------------------------------*/
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,8)
u4_level = u4_bits;
u4_level = (u4_level - (u4_level_first_byte << 1));
}
u4_numCoeffs += u4_run;
u4_pos = pu1_scan[u4_numCoeffs++ & 63];
pu1_pos[*pi4_num_coeffs] = u4_pos;
pi2_outAddr[*pi4_num_coeffs] = u4_level;
(*pi4_num_coeffs)++;
}
}
}
u4_nz_cols |= 1 << (u4_pos & 0x7);
u4_nz_rows |= 1 << (u4_pos >> 0x3);
if (u4_numCoeffs > 64)
{
return IMPEG2D_MB_TEX_DECODE_ERR;
}
}
IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len)
}
PUT_TEMP_STREAM_DATA(u4_buf, u4_buf_nxt, u4_offset, pu4_buf_aligned, ps_stream)
ps_dec->u4_non_zero_cols = u4_nz_cols;
ps_dec->u4_non_zero_rows = u4_nz_rows;
return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE;
}
Commit Message: Error Check for VLD Symbols Read
The maximum number of lead zeros in a VLD symbol (17 bits long) is 11.
Bug: 34093073
Change-Id: Ifd3f64a3a5199d6e4c33ca65449fc396cfb2f3fc
(cherry picked from commit 75e0ad5127752ce37e3fc78a156652e5da435f14)
CWE ID: CWE-200
Target: 1
Example 2:
Code: bool PrintWebViewHelper::PrintPreviewContext::CreatePreviewDocument(
PrintMsg_Print_Params* print_params,
const std::vector<int>& pages,
bool ignore_css_margins) {
DCHECK_EQ(INITIALIZED, state_);
state_ = RENDERING;
metafile_.reset(new printing::PreviewMetafile);
if (!metafile_->Init()) {
set_error(PREVIEW_ERROR_METAFILE_INIT_FAILED);
LOG(ERROR) << "PreviewMetafile Init failed";
return false;
}
prep_frame_view_.reset(new PrepareFrameAndViewForPrint(*print_params, frame(),
node()));
UpdateFrameAndViewFromCssPageLayout(frame_, node_, prep_frame_view_.get(),
*print_params, ignore_css_margins);
print_params_.reset(new PrintMsg_Print_Params(*print_params));
total_page_count_ = prep_frame_view_->GetExpectedPageCount();
if (total_page_count_ == 0) {
LOG(ERROR) << "CreatePreviewDocument got 0 page count";
set_error(PREVIEW_ERROR_ZERO_PAGES);
return false;
}
int selected_page_count = pages.size();
current_page_index_ = 0;
print_ready_metafile_page_count_ = selected_page_count;
pages_to_render_ = pages;
if (selected_page_count == 0) {
print_ready_metafile_page_count_ = total_page_count_;
for (int i = 0; i < total_page_count_; ++i)
pages_to_render_.push_back(i);
} else if (generate_draft_pages_) {
int pages_index = 0;
for (int i = 0; i < total_page_count_; ++i) {
if (pages_index < selected_page_count && i == pages[pages_index]) {
pages_index++;
continue;
}
pages_to_render_.push_back(i);
}
}
document_render_time_ = base::TimeDelta();
begin_time_ = base::TimeTicks::Now();
return true;
}
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: 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: Tab* TabStrip::FindTabForEvent(const gfx::Point& point) {
DCHECK(touch_layout_);
int active_tab_index = touch_layout_->active_index();
Tab* tab = FindTabForEventFrom(point, active_tab_index, -1);
return tab ? tab : FindTabForEventFrom(point, active_tab_index + 1, 1);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
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: update_info_partition_on_linux_dmmp (Device *device)
{
const gchar *dm_name;
const gchar* const *targets_type;
const gchar* const *targets_params;
gchar *params;
gint linear_slave_major;
gint linear_slave_minor;
guint64 offset_sectors;
Device *linear_slave;
gchar *s;
params = NULL;
dm_name = g_udev_device_get_property (device->priv->d, "DM_NAME");
if (dm_name == NULL)
goto out;
targets_type = g_udev_device_get_property_as_strv (device->priv->d, "UDISKS_DM_TARGETS_TYPE");
if (targets_type == NULL || g_strcmp0 (targets_type[0], "linear") != 0)
goto out;
goto out;
params = decode_udev_encoded_string (targets_params[0]);
if (sscanf (params,
"%d:%d %" G_GUINT64_FORMAT,
&linear_slave_major,
&linear_slave_minor,
&offset_sectors) != 3)
goto out;
linear_slave = daemon_local_find_by_dev (device->priv->daemon,
makedev (linear_slave_major, linear_slave_minor));
if (linear_slave == NULL)
goto out;
if (!linear_slave->priv->device_is_linux_dmmp)
goto out;
/* The Partition* properties has been set as part of
* update_info_partition() by reading UDISKS_PARTITION_*
* properties.. so here we bascially just update the presentation
* device file name and and whether the device is a drive.
*/
s = g_strdup_printf ("/dev/mapper/%s", dm_name);
device_set_device_file_presentation (device, s);
g_free (s);
device_set_device_is_drive (device, FALSE);
out:
g_free (params);
return TRUE;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: number_option(str, valp, base)
char *str;
u_int32_t *valp;
int base;
{
char *ptr;
*valp = strtoul(str, &ptr, base);
if (ptr == str) {
option_error("invalid numeric parameter '%s' for %s option",
str, current_option);
return 0;
}
return 1;
}
Commit Message: pppd: Eliminate potential integer overflow in option parsing
When we are reading in a word from an options file, we maintain a count
of the length we have seen so far in 'len', which is an int. When len
exceeds MAXWORDLEN - 1 (i.e. 1023) we cease storing characters in the
buffer but we continue to increment len. Since len is an int, it will
wrap around to -2147483648 after it reaches 2147483647. At that point
our test of (len < MAXWORDLEN-1) will succeed and we will start writing
characters to memory again.
This may enable an attacker to overwrite the heap and thereby corrupt
security-relevant variables. For this reason it has been assigned a
CVE identifier, CVE-2014-3158.
This fixes the bug by ceasing to increment len once it reaches MAXWORDLEN.
Reported-by: Lee Campbell <[email protected]>
Signed-off-by: Paul Mackerras <[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 uint32_t select_lease_time(struct dhcp_packet *packet)
{
uint32_t lease_time_sec = server_config.max_lease_sec;
uint8_t *lease_time_opt = udhcp_get_option(packet, DHCP_LEASE_TIME);
if (lease_time_opt) {
move_from_unaligned32(lease_time_sec, lease_time_opt);
lease_time_sec = ntohl(lease_time_sec);
if (lease_time_sec > server_config.max_lease_sec)
lease_time_sec = server_config.max_lease_sec;
if (lease_time_sec < server_config.min_lease_sec)
lease_time_sec = server_config.min_lease_sec;
}
return lease_time_sec;
}
Commit Message:
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: lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p,
const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile)
{ /* i_ctx_p is NULL running arg (@) files.
* lib_path and mem are never NULL
*/
bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file;
bool search_with_no_combine = false;
bool search_with_combine = false;
char fmode[2] = { 'r', 0};
gx_io_device *iodev = iodev_default(mem);
gs_main_instance *minst = get_minst_from_memory(mem);
int code;
/* when starting arg files (@ files) iodev_default is not yet set */
if (iodev == 0)
iodev = (gx_io_device *)gx_io_device_table[0];
search_with_combine = false;
} else {
search_with_no_combine = starting_arg_file;
search_with_combine = true;
}
Commit Message:
CWE ID: CWE-200
Target: 1
Example 2:
Code: void LayerTreeHost::SetAnimationEvents(
std::unique_ptr<MutatorEvents> events) {
DCHECK(task_runner_provider_->IsMainThread());
mutator_host_->SetAnimationEvents(std::move(events));
}
Commit Message: (Reland) Discard compositor frames from unloaded web content
This is a reland of https://codereview.chromium.org/2707243005/ with a
small change to fix an uninitialized memory error that fails on MSAN
bots.
BUG=672847
[email protected], [email protected]
CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2731283003
Cr-Commit-Position: refs/heads/master@{#454954}
CWE ID: CWE-362
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 ShelfLayoutManager::UpdateAutoHideState() {
AutoHideState auto_hide_state =
CalculateAutoHideState(state_.visibility_state);
if (auto_hide_state != state_.auto_hide_state) {
if (auto_hide_state == AUTO_HIDE_HIDDEN) {
SetState(state_.visibility_state);
FOR_EACH_OBSERVER(Observer, observers_,
OnAutoHideStateChanged(auto_hide_state));
} else {
auto_hide_timer_.Stop();
auto_hide_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kAutoHideDelayMS),
this, &ShelfLayoutManager::UpdateAutoHideStateNow);
FOR_EACH_OBSERVER(Observer, observers_, OnAutoHideStateChanged(
CalculateAutoHideState(state_.visibility_state)));
}
} else {
auto_hide_timer_.Stop();
}
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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 CuePoint::Load(IMkvReader* pReader) {
if (m_timecode >= 0) // already loaded
return;
assert(m_track_positions == NULL);
assert(m_track_positions_count == 0);
long long pos_ = -m_timecode;
const long long element_start = pos_;
long long stop;
{
long len;
const long long id = ReadUInt(pReader, pos_, len);
assert(id == 0x3B); // CuePoint ID
if (id != 0x3B)
return;
pos_ += len; // consume ID
const long long size = ReadUInt(pReader, pos_, len);
assert(size >= 0);
pos_ += len; // consume Size field
stop = pos_ + size;
}
const long long element_size = stop - element_start;
long long pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x33) // CueTime ID
m_timecode = UnserializeUInt(pReader, pos, size);
else if (id == 0x37) // CueTrackPosition(s) ID
++m_track_positions_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(m_timecode >= 0);
assert(m_track_positions_count > 0);
m_track_positions = new TrackPosition[m_track_positions_count];
TrackPosition* p = m_track_positions;
pos = pos_;
while (pos < stop) {
long len;
const long long id = ReadUInt(pReader, pos, len);
assert(id >= 0); // TODO
assert((pos + len) <= stop);
pos += len; // consume ID
const long long size = ReadUInt(pReader, pos, len);
assert(size >= 0);
assert((pos + len) <= stop);
pos += len; // consume Size field
assert((pos + size) <= stop);
if (id == 0x37) { // CueTrackPosition(s) ID
TrackPosition& tp = *p++;
tp.Parse(pReader, pos, size);
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(size_t(p - m_track_positions) == m_track_positions_count);
m_element_start = element_start;
m_element_size = element_size;
}
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
Target: 1
Example 2:
Code: SYSCALL_DEFINE3(timer_create, const clockid_t, which_clock,
struct sigevent __user *, timer_event_spec,
timer_t __user *, created_timer_id)
{
if (timer_event_spec) {
sigevent_t event;
if (copy_from_user(&event, timer_event_spec, sizeof (event)))
return -EFAULT;
return do_timer_create(which_clock, &event, created_timer_id);
}
return do_timer_create(which_clock, NULL, created_timer_id);
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Acked-by: John Stultz <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190
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 *ReadRLEImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define SkipLinesOp 0x01
#define SetColorOp 0x02
#define SkipPixelsOp 0x03
#define ByteDataOp 0x05
#define RunDataOp 0x06
#define EOFOp 0x07
char
magick[12];
Image
*image;
IndexPacket
index;
int
opcode,
operand,
status;
MagickStatusType
flags;
MagickSizeType
number_pixels;
MemoryInfo
*pixel_info;
register IndexPacket
*indexes;
register ssize_t
x;
register PixelPacket
*q;
register ssize_t
i;
register unsigned char
*p;
size_t
bits_per_pixel,
map_length,
number_colormaps,
number_planes,
number_planes_filled,
one,
offset,
pixel_info_length;
ssize_t
count,
y;
unsigned char
background_color[256],
*colormap,
pixel,
plane,
*pixels;
/*
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)
return(DestroyImageList(image));
/*
Determine if this a RLE file.
*/
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 2) || (memcmp(magick,"\122\314",2) != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Read image header.
*/
image->page.x=ReadBlobLSBShort(image);
image->page.y=ReadBlobLSBShort(image);
image->columns=ReadBlobLSBShort(image);
image->rows=ReadBlobLSBShort(image);
flags=(MagickStatusType) ReadBlobByte(image);
image->matte=flags & 0x04 ? MagickTrue : MagickFalse;
number_planes=(size_t) ReadBlobByte(image);
bits_per_pixel=(size_t) ReadBlobByte(image);
number_colormaps=(size_t) ReadBlobByte(image);
map_length=(unsigned char) ReadBlobByte(image);
if (map_length >= 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
one=1;
map_length=one << map_length;
if ((number_planes == 0) || (number_planes == 2) ||
((flags & 0x04) && (number_colormaps > 254)) || (bits_per_pixel != 8) ||
(image->columns == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (flags & 0x02)
{
/*
No background color-- initialize to black.
*/
for (i=0; i < (ssize_t) number_planes; i++)
background_color[i]=0;
(void) ReadBlobByte(image);
}
else
{
/*
Initialize background color.
*/
p=background_color;
for (i=0; i < (ssize_t) number_planes; i++)
*p++=(unsigned char) ReadBlobByte(image);
}
if ((number_planes & 0x01) == 0)
(void) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
colormap=(unsigned char *) NULL;
if (number_colormaps != 0)
{
/*
Read image colormaps.
*/
colormap=(unsigned char *) AcquireQuantumMemory(number_colormaps,
3*map_length*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
for (i=0; i < (ssize_t) number_colormaps; i++)
for (x=0; x < (ssize_t) map_length; x++)
*p++=(unsigned char) ScaleShortToQuantum(ReadBlobLSBShort(image));
}
if ((flags & 0x08) != 0)
{
char
*comment;
size_t
length;
/*
Read image comment.
*/
length=ReadBlobLSBShort(image);
if (length != 0)
{
comment=(char *) AcquireQuantumMemory(length,sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ReadBlob(image,length-1,(unsigned char *) comment);
comment[length-1]='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
if ((length & 0x01) == 0)
(void) ReadBlobByte(image);
}
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Allocate RLE pixels.
*/
if (image->matte != MagickFalse)
number_planes++;
number_pixels=(MagickSizeType) image->columns*image->rows;
number_planes_filled=(number_planes % 2 == 0) ? number_planes :
number_planes+1;
if ((number_pixels*number_planes_filled) != (size_t) (number_pixels*
number_planes_filled))
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info=AcquireVirtualMemory(image->columns,image->rows*
number_planes_filled*sizeof(*pixels));
if (pixel_info == (MemoryInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixel_info_length=image->columns*image->rows*number_planes_filled;
pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
if ((flags & 0x01) && !(flags & 0x02))
{
ssize_t
j;
/*
Set background color.
*/
p=pixels;
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (image->matte == MagickFalse)
for (j=0; j < (ssize_t) number_planes; j++)
*p++=background_color[j];
else
{
for (j=0; j < (ssize_t) (number_planes-1); j++)
*p++=background_color[j];
*p++=0; /* initialize matte channel */
}
}
}
/*
Read runlength-encoded image.
*/
plane=0;
x=0;
y=0;
opcode=ReadBlobByte(image);
do
{
switch (opcode & 0x3f)
{
case SkipLinesOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x=0;
y+=operand;
break;
}
case SetColorOp:
{
operand=ReadBlobByte(image);
plane=(unsigned char) operand;
if (plane == 255)
plane=(unsigned char) (number_planes-1);
x=0;
break;
}
case SkipPixelsOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
x+=operand;
break;
}
case ByteDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
operand++;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
p=pixels+offset;
for (i=0; i < (ssize_t) operand; i++)
{
pixel=(unsigned char) ReadBlobByte(image);
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
if (operand & 0x01)
(void) ReadBlobByte(image);
x+=operand;
break;
}
case RunDataOp:
{
operand=ReadBlobByte(image);
if (opcode & 0x40)
operand=ReadBlobLSBSignedShort(image);
pixel=(unsigned char) ReadBlobByte(image);
(void) ReadBlobByte(image);
operand++;
offset=((image->rows-y-1)*image->columns*number_planes)+x*
number_planes+plane;
p=pixels+offset;
if (offset+((size_t) operand*number_planes) > pixel_info_length)
{
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
for (i=0; i < (ssize_t) operand; i++)
{
if ((y < (ssize_t) image->rows) &&
((x+i) < (ssize_t) image->columns))
*p=pixel;
p+=number_planes;
}
x+=operand;
break;
}
default:
break;
}
opcode=ReadBlobByte(image);
} while (((opcode & 0x3f) != EOFOp) && (opcode != EOF));
if (number_colormaps != 0)
{
MagickStatusType
mask;
/*
Apply colormap affineation to image.
*/
mask=(MagickStatusType) (map_length-1);
p=pixels;
x=(ssize_t) number_planes;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) number_pixels; i++)
{
if (IsValidColormapIndex(image,*p & mask,&index,exception) ==
MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
else
if ((number_planes >= 3) && (number_colormaps >= 3))
for (i=0; i < (ssize_t) number_pixels; i++)
for (x=0; x < (ssize_t) number_planes; x++)
{
if (IsValidColormapIndex(image,(size_t) (x*map_length+
(*p & mask)),&index,exception) == MagickFalse)
break;
*p=colormap[(ssize_t) index];
p++;
}
if ((i < (ssize_t) number_pixels) || (x < (ssize_t) number_planes))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
}
}
/*
Initialize image structure.
*/
if (number_planes >= 3)
{
/*
Convert raster image to DirectClass pixel packets.
*/
p=pixels;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
if (image->matte != MagickFalse)
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Create colormap.
*/
if (number_colormaps == 0)
map_length=256;
if (AcquireImageColormap(image,map_length) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=colormap;
if (number_colormaps == 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
/*
Pseudocolor.
*/
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
else
if (number_colormaps > 1)
for (i=0; i < (ssize_t) image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum(*p);
image->colormap[i].green=ScaleCharToQuantum(*(p+map_length));
image->colormap[i].blue=ScaleCharToQuantum(*(p+map_length*2));
p++;
}
p=pixels;
if (image->matte == MagickFalse)
{
/*
Convert raster image to PseudoClass pixel packets.
*/
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++)
SetPixelIndex(indexes+x,*p++);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
(void) SyncImage(image);
}
else
{
/*
Image has a matte channel-- promote to DirectClass.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelRed(q,image->colormap[(ssize_t) index].red);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelGreen(q,image->colormap[(ssize_t) index].green);
if (IsValidColormapIndex(image,*p++,&index,exception) ==
MagickFalse)
break;
SetPixelBlue(q,image->colormap[(ssize_t) index].blue);
SetPixelAlpha(q,ScaleCharToQuantum(*p++));
q++;
}
if (x < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
image->colormap=(PixelPacket *) RelinquishMagickMemory(
image->colormap);
image->storage_class=DirectClass;
image->colors=0;
}
}
if (number_colormaps != 0)
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
pixel_info=RelinquishVirtualMemory(pixel_info);
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;
(void) ReadBlobByte(image);
count=ReadBlob(image,2,(unsigned char *) magick);
if ((count != 0) && (memcmp(magick,"\122\314",2) == 0))
{
/*
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 ((count != 0) && (memcmp(magick,"\122\314",2) == 0));
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message: https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=29710
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(mcrypt_module_self_test)
{
MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
if (mcrypt_module_self_test(module, dir) == 0) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
Commit Message: Fix bug #72455: Heap Overflow due to integer overflows
CWE ID: CWE-190
Target: 1
Example 2:
Code: SYSCALL_DEFINE3(shmctl, int, shmid, int, cmd, struct shmid_ds __user *, buf)
{
struct shmid_kernel *shp;
int err, version;
struct ipc_namespace *ns;
if (cmd < 0 || shmid < 0)
return -EINVAL;
version = ipc_parse_version(&cmd);
ns = current->nsproxy->ipc_ns;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
case SHM_STAT:
case IPC_STAT:
return shmctl_nolock(ns, shmid, cmd, version, buf);
case IPC_RMID:
case IPC_SET:
return shmctl_down(ns, shmid, cmd, buf, version);
case SHM_LOCK:
case SHM_UNLOCK:
{
struct file *shm_file;
rcu_read_lock();
shp = shm_obtain_object_check(ns, shmid);
if (IS_ERR(shp)) {
err = PTR_ERR(shp);
goto out_unlock1;
}
audit_ipc_obj(&(shp->shm_perm));
err = security_shm_shmctl(shp, cmd);
if (err)
goto out_unlock1;
ipc_lock_object(&shp->shm_perm);
/* check if shm_destroy() is tearing down shp */
if (!ipc_valid_object(&shp->shm_perm)) {
err = -EIDRM;
goto out_unlock0;
}
if (!ns_capable(ns->user_ns, CAP_IPC_LOCK)) {
kuid_t euid = current_euid();
if (!uid_eq(euid, shp->shm_perm.uid) &&
!uid_eq(euid, shp->shm_perm.cuid)) {
err = -EPERM;
goto out_unlock0;
}
if (cmd == SHM_LOCK && !rlimit(RLIMIT_MEMLOCK)) {
err = -EPERM;
goto out_unlock0;
}
}
shm_file = shp->shm_file;
if (is_file_hugepages(shm_file))
goto out_unlock0;
if (cmd == SHM_LOCK) {
struct user_struct *user = current_user();
err = shmem_lock(shm_file, 1, user);
if (!err && !(shp->shm_perm.mode & SHM_LOCKED)) {
shp->shm_perm.mode |= SHM_LOCKED;
shp->mlock_user = user;
}
goto out_unlock0;
}
/* SHM_UNLOCK */
if (!(shp->shm_perm.mode & SHM_LOCKED))
goto out_unlock0;
shmem_lock(shm_file, 0, shp->mlock_user);
shp->shm_perm.mode &= ~SHM_LOCKED;
shp->mlock_user = NULL;
get_file(shm_file);
ipc_unlock_object(&shp->shm_perm);
rcu_read_unlock();
shmem_unlock_mapping(shm_file->f_mapping);
fput(shm_file);
return err;
}
default:
return -EINVAL;
}
out_unlock0:
ipc_unlock_object(&shp->shm_perm);
out_unlock1:
rcu_read_unlock();
return err;
}
Commit Message: Initialize msg/shm IPC objects before doing ipc_addid()
As reported by Dmitry Vyukov, we really shouldn't do ipc_addid() before
having initialized the IPC object state. Yes, we initialize the IPC
object in a locked state, but with all the lockless RCU lookup work,
that IPC object lock no longer means that the state cannot be seen.
We already did this for the IPC semaphore code (see commit e8577d1f0329:
"ipc/sem.c: fully initialize sem_array before making it visible") but we
clearly forgot about msg and shm.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: Manfred Spraul <[email protected]>
Cc: Davidlohr Bueso <[email protected]>
Cc: [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: static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
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 scan(Scanner *s)
{
uchar *cursor = s->cur;
char *str, *ptr = NULL;
std:
s->tok = cursor;
s->len = 0;
#line 311 "ext/date/lib/parse_iso_intervals.re"
#line 291 "ext/date/lib/parse_iso_intervals.c"
{
YYCTYPE yych;
unsigned int yyaccept = 0;
static const unsigned char yybm[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
128, 128, 128, 128, 128, 128, 128, 128,
128, 128, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
YYDEBUG(0, *YYCURSOR);
if ((YYLIMIT - YYCURSOR) < 20) YYFILL(20);
yych = *YYCURSOR;
if (yych <= ',') {
if (yych <= '\n') {
if (yych <= 0x00) goto yy9;
if (yych <= 0x08) goto yy11;
if (yych <= '\t') goto yy7;
goto yy9;
} else {
if (yych == ' ') goto yy7;
if (yych <= '+') goto yy11;
goto yy7;
}
} else {
if (yych <= 'O') {
if (yych <= '-') goto yy11;
if (yych <= '/') goto yy7;
if (yych <= '9') goto yy4;
goto yy11;
} else {
if (yych <= 'P') goto yy5;
if (yych != 'R') goto yy11;
}
}
YYDEBUG(2, *YYCURSOR);
++YYCURSOR;
if ((yych = *YYCURSOR) <= '/') goto yy3;
if (yych <= '9') goto yy98;
yy3:
YYDEBUG(3, *YYCURSOR);
#line 424 "ext/date/lib/parse_iso_intervals.re"
{
add_error(s, "Unexpected character");
goto std;
}
#line 366 "ext/date/lib/parse_iso_intervals.c"
yy4:
YYDEBUG(4, *YYCURSOR);
yyaccept = 0;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy3;
if (yych <= '9') goto yy59;
goto yy3;
yy5:
YYDEBUG(5, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy12;
if (yych == 'T') goto yy14;
yy6:
YYDEBUG(6, *YYCURSOR);
#line 351 "ext/date/lib/parse_iso_intervals.re"
{
timelib_sll nr;
int in_time = 0;
DEBUG_OUTPUT("period");
TIMELIB_INIT;
ptr++;
do {
if ( *ptr == 'T' ) {
in_time = 1;
ptr++;
}
if ( *ptr == '\0' ) {
add_error(s, "Missing expected time part");
break;
}
nr = timelib_get_unsigned_nr((char **) &ptr, 12);
switch (*ptr) {
case 'Y': s->period->y = nr; break;
case 'W': s->period->d = nr * 7; break;
case 'D': s->period->d = nr; break;
case 'H': s->period->h = nr; break;
case 'S': s->period->s = nr; break;
case 'M':
if (in_time) {
s->period->i = nr;
} else {
s->period->m = nr;
}
break;
default:
add_error(s, "Undefined period specifier");
break;
}
ptr++;
} while (*ptr);
s->have_period = 1;
TIMELIB_DEINIT;
return TIMELIB_PERIOD;
}
#line 424 "ext/date/lib/parse_iso_intervals.c"
yy7:
YYDEBUG(7, *YYCURSOR);
++YYCURSOR;
YYDEBUG(8, *YYCURSOR);
#line 413 "ext/date/lib/parse_iso_intervals.re"
{
goto std;
}
#line 433 "ext/date/lib/parse_iso_intervals.c"
yy9:
YYDEBUG(9, *YYCURSOR);
++YYCURSOR;
YYDEBUG(10, *YYCURSOR);
#line 418 "ext/date/lib/parse_iso_intervals.re"
{
s->pos = cursor; s->line++;
goto std;
}
#line 443 "ext/date/lib/parse_iso_intervals.c"
yy11:
YYDEBUG(11, *YYCURSOR);
yych = *++YYCURSOR;
goto yy3;
yy12:
YYDEBUG(12, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych >= '0') goto yy25;
} else {
if (yych == 'D') goto yy24;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych >= 'W') goto yy26;
} else {
if (yych == 'Y') goto yy28;
}
}
yy13:
YYDEBUG(13, *YYCURSOR);
YYCURSOR = YYMARKER;
if (yyaccept <= 0) {
goto yy3;
} else {
goto yy6;
}
yy14:
YYDEBUG(14, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy15;
}
goto yy6;
yy15:
YYDEBUG(15, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(16, *YYCURSOR);
if (yybm[0+yych] & 128) {
goto yy15;
}
if (yych <= 'L') {
if (yych == 'H') goto yy19;
goto yy13;
} else {
if (yych <= 'M') goto yy18;
if (yych != 'S') goto yy13;
}
yy17:
YYDEBUG(17, *YYCURSOR);
yych = *++YYCURSOR;
goto yy6;
yy18:
YYDEBUG(18, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy22;
goto yy6;
yy19:
YYDEBUG(19, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych >= ':') goto yy6;
yy20:
YYDEBUG(20, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 2) YYFILL(2);
yych = *YYCURSOR;
YYDEBUG(21, *YYCURSOR);
if (yych <= 'L') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy20;
goto yy13;
} else {
if (yych <= 'M') goto yy18;
if (yych == 'S') goto yy17;
goto yy13;
}
yy22:
YYDEBUG(22, *YYCURSOR);
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(23, *YYCURSOR);
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy22;
if (yych == 'S') goto yy17;
goto yy13;
yy24:
YYDEBUG(24, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'T') goto yy14;
goto yy6;
yy25:
YYDEBUG(25, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
goto yy35;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
yy26:
YYDEBUG(26, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy33;
if (yych == 'T') goto yy14;
goto yy6;
yy27:
YYDEBUG(27, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy31;
if (yych == 'T') goto yy14;
goto yy6;
yy28:
YYDEBUG(28, *YYCURSOR);
yyaccept = 1;
yych = *(YYMARKER = ++YYCURSOR);
if (yych <= '/') goto yy6;
if (yych <= '9') goto yy29;
if (yych == 'T') goto yy14;
goto yy6;
yy29:
YYDEBUG(29, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(30, *YYCURSOR);
if (yych <= 'D') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy29;
if (yych <= 'C') goto yy13;
goto yy24;
} else {
if (yych <= 'M') {
if (yych <= 'L') goto yy13;
goto yy27;
} else {
if (yych == 'W') goto yy26;
goto yy13;
}
}
yy31:
YYDEBUG(31, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(32, *YYCURSOR);
if (yych <= 'C') {
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy31;
goto yy13;
} else {
if (yych <= 'D') goto yy24;
if (yych == 'W') goto yy26;
goto yy13;
}
yy33:
YYDEBUG(33, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
YYDEBUG(34, *YYCURSOR);
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy33;
if (yych == 'D') goto yy24;
goto yy13;
yy35:
YYDEBUG(35, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
goto yy26;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
YYDEBUG(36, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy39;
YYDEBUG(37, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy40;
if (yych <= '1') goto yy41;
goto yy13;
yy38:
YYDEBUG(38, *YYCURSOR);
++YYCURSOR;
if ((YYLIMIT - YYCURSOR) < 3) YYFILL(3);
yych = *YYCURSOR;
yy39:
YYDEBUG(39, *YYCURSOR);
if (yych <= 'L') {
if (yych <= '9') {
if (yych <= '/') goto yy13;
goto yy38;
} else {
if (yych == 'D') goto yy24;
goto yy13;
}
} else {
if (yych <= 'W') {
if (yych <= 'M') goto yy27;
if (yych <= 'V') goto yy13;
goto yy26;
} else {
if (yych == 'Y') goto yy28;
goto yy13;
}
}
yy40:
YYDEBUG(40, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy42;
goto yy13;
yy41:
YYDEBUG(41, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '3') goto yy13;
yy42:
YYDEBUG(42, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy13;
YYDEBUG(43, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy44;
if (yych <= '2') goto yy45;
if (yych <= '3') goto yy46;
goto yy13;
yy44:
YYDEBUG(44, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy47;
goto yy13;
yy45:
YYDEBUG(45, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy47;
goto yy13;
yy46:
YYDEBUG(46, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy47:
YYDEBUG(47, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(48, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy49;
if (yych <= '2') goto yy50;
goto yy13;
yy49:
YYDEBUG(49, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy51;
goto yy13;
yy50:
YYDEBUG(50, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy51:
YYDEBUG(51, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(52, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(53, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(54, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(55, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(56, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(57, *YYCURSOR);
++YYCURSOR;
YYDEBUG(58, *YYCURSOR);
#line 393 "ext/date/lib/parse_iso_intervals.re"
{
DEBUG_OUTPUT("combinedrep");
TIMELIB_INIT;
s->period->y = timelib_get_unsigned_nr((char **) &ptr, 4);
ptr++;
s->period->m = timelib_get_unsigned_nr((char **) &ptr, 2);
ptr++;
s->period->d = timelib_get_unsigned_nr((char **) &ptr, 2);
ptr++;
s->period->h = timelib_get_unsigned_nr((char **) &ptr, 2);
ptr++;
s->period->i = timelib_get_unsigned_nr((char **) &ptr, 2);
ptr++;
s->period->s = timelib_get_unsigned_nr((char **) &ptr, 2);
s->have_period = 1;
TIMELIB_DEINIT;
return TIMELIB_PERIOD;
}
#line 792 "ext/date/lib/parse_iso_intervals.c"
yy59:
YYDEBUG(59, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(60, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(61, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') {
if (yych == '-') goto yy64;
goto yy13;
} else {
if (yych <= '0') goto yy62;
if (yych <= '1') goto yy63;
goto yy13;
}
yy62:
YYDEBUG(62, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy85;
goto yy13;
yy63:
YYDEBUG(63, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '2') goto yy85;
goto yy13;
yy64:
YYDEBUG(64, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy65;
if (yych <= '1') goto yy66;
goto yy13;
yy65:
YYDEBUG(65, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy67;
goto yy13;
yy66:
YYDEBUG(66, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '3') goto yy13;
yy67:
YYDEBUG(67, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != '-') goto yy13;
YYDEBUG(68, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy69;
if (yych <= '2') goto yy70;
if (yych <= '3') goto yy71;
goto yy13;
yy69:
YYDEBUG(69, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy72;
goto yy13;
yy70:
YYDEBUG(70, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy72;
goto yy13;
yy71:
YYDEBUG(71, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy72:
YYDEBUG(72, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(73, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy74;
if (yych <= '2') goto yy75;
goto yy13;
yy74:
YYDEBUG(74, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy76;
goto yy13;
yy75:
YYDEBUG(75, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy76:
YYDEBUG(76, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(77, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(78, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(79, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != ':') goto yy13;
YYDEBUG(80, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(81, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(82, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'Z') goto yy13;
yy83:
YYDEBUG(83, *YYCURSOR);
++YYCURSOR;
YYDEBUG(84, *YYCURSOR);
#line 327 "ext/date/lib/parse_iso_intervals.re"
{
timelib_time *current;
if (s->have_date || s->have_period) {
current = s->end;
s->have_end_date = 1;
} else {
current = s->begin;
s->have_begin_date = 1;
}
DEBUG_OUTPUT("datetimebasic | datetimeextended");
TIMELIB_INIT;
current->y = timelib_get_nr((char **) &ptr, 4);
current->m = timelib_get_nr((char **) &ptr, 2);
current->d = timelib_get_nr((char **) &ptr, 2);
current->h = timelib_get_nr((char **) &ptr, 2);
current->i = timelib_get_nr((char **) &ptr, 2);
current->s = timelib_get_nr((char **) &ptr, 2);
s->have_date = 1;
TIMELIB_DEINIT;
return TIMELIB_ISO_DATE;
}
#line 944 "ext/date/lib/parse_iso_intervals.c"
yy85:
YYDEBUG(85, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '0') goto yy86;
if (yych <= '2') goto yy87;
if (yych <= '3') goto yy88;
goto yy13;
yy86:
YYDEBUG(86, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '0') goto yy13;
if (yych <= '9') goto yy89;
goto yy13;
yy87:
YYDEBUG(87, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy89;
goto yy13;
yy88:
YYDEBUG(88, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '2') goto yy13;
yy89:
YYDEBUG(89, *YYCURSOR);
yych = *++YYCURSOR;
if (yych != 'T') goto yy13;
YYDEBUG(90, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '1') goto yy91;
if (yych <= '2') goto yy92;
goto yy13;
yy91:
YYDEBUG(91, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych <= '9') goto yy93;
goto yy13;
yy92:
YYDEBUG(92, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '5') goto yy13;
yy93:
YYDEBUG(93, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(94, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(95, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= '6') goto yy13;
YYDEBUG(96, *YYCURSOR);
yych = *++YYCURSOR;
if (yych <= '/') goto yy13;
if (yych >= ':') goto yy13;
YYDEBUG(97, *YYCURSOR);
yych = *++YYCURSOR;
if (yych == 'Z') goto yy83;
goto yy13;
yy98:
YYDEBUG(98, *YYCURSOR);
++YYCURSOR;
if (YYLIMIT <= YYCURSOR) YYFILL(1);
yych = *YYCURSOR;
YYDEBUG(99, *YYCURSOR);
if (yych <= '/') goto yy100;
if (yych <= '9') goto yy98;
yy100:
YYDEBUG(100, *YYCURSOR);
#line 316 "ext/date/lib/parse_iso_intervals.re"
{
DEBUG_OUTPUT("recurrences");
TIMELIB_INIT;
ptr++;
s->recurrences = timelib_get_unsigned_nr((char **) &ptr, 9);
TIMELIB_DEINIT;
s->have_recurrences = 1;
return TIMELIB_PERIOD;
}
#line 1032 "ext/date/lib/parse_iso_intervals.c"
}
#line 428 "ext/date/lib/parse_iso_intervals.re"
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: void CommandBufferProxyImpl::OnGpuAsyncMessageError(
gpu::error::ContextLostReason reason,
gpu::error::Error error) {
CheckLock();
last_state_lock_.AssertAcquired();
last_state_.error = error;
last_state_.context_lost_reason = reason;
base::AutoUnlock unlock(last_state_lock_);
DisconnectChannel();
}
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: 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 vsock_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *listener;
int err;
struct sock *connected;
struct vsock_sock *vconnected;
long timeout;
DEFINE_WAIT(wait);
err = 0;
listener = sock->sk;
lock_sock(listener);
if (sock->type != SOCK_STREAM) {
err = -EOPNOTSUPP;
goto out;
}
if (listener->sk_state != SS_LISTEN) {
err = -EINVAL;
goto out;
}
/* Wait for children sockets to appear; these are the new sockets
* created upon connection establishment.
*/
timeout = sock_sndtimeo(listener, flags & O_NONBLOCK);
prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
while ((connected = vsock_dequeue_accept(listener)) == NULL &&
listener->sk_err == 0) {
release_sock(listener);
timeout = schedule_timeout(timeout);
lock_sock(listener);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
goto out_wait;
} else if (timeout == 0) {
err = -EAGAIN;
goto out_wait;
}
prepare_to_wait(sk_sleep(listener), &wait, TASK_INTERRUPTIBLE);
}
if (listener->sk_err)
err = -listener->sk_err;
if (connected) {
listener->sk_ack_backlog--;
lock_sock(connected);
vconnected = vsock_sk(connected);
/* If the listener socket has received an error, then we should
* reject this socket and return. Note that we simply mark the
* socket rejected, drop our reference, and let the cleanup
* function handle the cleanup; the fact that we found it in
* the listener's accept queue guarantees that the cleanup
* function hasn't run yet.
*/
if (err) {
vconnected->rejected = true;
release_sock(connected);
sock_put(connected);
goto out_wait;
}
newsock->state = SS_CONNECTED;
sock_graft(connected, newsock);
release_sock(connected);
sock_put(connected);
}
out_wait:
finish_wait(sk_sleep(listener), &wait);
out:
release_sock(listener);
return err;
}
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 __munlock_pagevec(struct pagevec *pvec, struct zone *zone)
{
int i;
int nr = pagevec_count(pvec);
int delta_munlocked;
struct pagevec pvec_putback;
int pgrescued = 0;
pagevec_init(&pvec_putback, 0);
/* Phase 1: page isolation */
spin_lock_irq(zone_lru_lock(zone));
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (TestClearPageMlocked(page)) {
/*
* We already have pin from follow_page_mask()
* so we can spare the get_page() here.
*/
if (__munlock_isolate_lru_page(page, false))
continue;
else
__munlock_isolation_failed(page);
}
/*
* We won't be munlocking this page in the next phase
* but we still need to release the follow_page_mask()
* pin. We cannot do it under lru_lock however. If it's
* the last pin, __page_cache_release() would deadlock.
*/
pagevec_add(&pvec_putback, pvec->pages[i]);
pvec->pages[i] = NULL;
}
delta_munlocked = -nr + pagevec_count(&pvec_putback);
__mod_zone_page_state(zone, NR_MLOCK, delta_munlocked);
spin_unlock_irq(zone_lru_lock(zone));
/* Now we can release pins of pages that we are not munlocking */
pagevec_release(&pvec_putback);
/* Phase 2: page munlock */
for (i = 0; i < nr; i++) {
struct page *page = pvec->pages[i];
if (page) {
lock_page(page);
if (!__putback_lru_fast_prepare(page, &pvec_putback,
&pgrescued)) {
/*
* Slow path. We don't want to lose the last
* pin before unlock_page()
*/
get_page(page); /* for putback_lru_page() */
__munlock_isolated_page(page);
unlock_page(page);
put_page(page); /* from follow_page_mask() */
}
}
}
/*
* Phase 3: page putback for pages that qualified for the fast path
* This will also call put_page() to return pin from follow_page_mask()
*/
if (pagevec_count(&pvec_putback))
__putback_lru_fast(&pvec_putback, pgrescued);
}
Commit Message: mlock: fix mlock count can not decrease in race condition
Kefeng reported that when running the follow test, the mlock count in
meminfo will increase permanently:
[1] testcase
linux:~ # cat test_mlockal
grep Mlocked /proc/meminfo
for j in `seq 0 10`
do
for i in `seq 4 15`
do
./p_mlockall >> log &
done
sleep 0.2
done
# wait some time to let mlock counter decrease and 5s may not enough
sleep 5
grep Mlocked /proc/meminfo
linux:~ # cat p_mlockall.c
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#define SPACE_LEN 4096
int main(int argc, char ** argv)
{
int ret;
void *adr = malloc(SPACE_LEN);
if (!adr)
return -1;
ret = mlockall(MCL_CURRENT | MCL_FUTURE);
printf("mlcokall ret = %d\n", ret);
ret = munlockall();
printf("munlcokall ret = %d\n", ret);
free(adr);
return 0;
}
In __munlock_pagevec() we should decrement NR_MLOCK for each page where
we clear the PageMlocked flag. Commit 1ebb7cc6a583 ("mm: munlock: batch
NR_MLOCK zone state updates") has introduced a bug where we don't
decrement NR_MLOCK for pages where we clear the flag, but fail to
isolate them from the lru list (e.g. when the pages are on some other
cpu's percpu pagevec). Since PageMlocked stays cleared, the NR_MLOCK
accounting gets permanently disrupted by this.
Fix it by counting the number of page whose PageMlock flag is cleared.
Fixes: 1ebb7cc6a583 (" mm: munlock: batch NR_MLOCK zone state updates")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Yisheng Xie <[email protected]>
Reported-by: Kefeng Wang <[email protected]>
Tested-by: Kefeng Wang <[email protected]>
Cc: Vlastimil Babka <[email protected]>
Cc: Joern Engel <[email protected]>
Cc: Mel Gorman <[email protected]>
Cc: Michel Lespinasse <[email protected]>
Cc: Hugh Dickins <[email protected]>
Cc: Rik van Riel <[email protected]>
Cc: Johannes Weiner <[email protected]>
Cc: Michal Hocko <[email protected]>
Cc: Xishi Qiu <[email protected]>
Cc: zhongjiang <[email protected]>
Cc: Hanjun Guo <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-20
Target: 1
Example 2:
Code: static void fuse_writepage_free(struct fuse_conn *fc, struct fuse_req *req)
{
int i;
for (i = 0; i < req->num_pages; i++)
__free_page(req->pages[i]);
if (req->ff)
fuse_file_put(req->ff, false);
}
Commit Message: fuse: break infinite loop in fuse_fill_write_pages()
I got a report about unkillable task eating CPU. Further
investigation shows, that the problem is in the fuse_fill_write_pages()
function. If iov's first segment has zero length, we get an infinite
loop, because we never reach iov_iter_advance() call.
Fix this by calling iov_iter_advance() before repeating an attempt to
copy data from userspace.
A similar problem is described in 124d3b7041f ("fix writev regression:
pan hanging unkillable and un-straceable"). If zero-length segmend
is followed by segment with invalid address,
iov_iter_fault_in_readable() checks only first segment (zero-length),
iov_iter_copy_from_user_atomic() skips it, fails at second and
returns zero -> goto again without skipping zero-length segment.
Patch calls iov_iter_advance() before goto again: we'll skip zero-length
segment at second iteraction and iov_iter_fault_in_readable() will detect
invalid address.
Special thanks to Konstantin Khlebnikov, who helped a lot with the commit
description.
Cc: Andrew Morton <[email protected]>
Cc: Maxim Patlasov <[email protected]>
Cc: Konstantin Khlebnikov <[email protected]>
Signed-off-by: Roman Gushchin <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Fixes: ea9b9907b82a ("fuse: implement perform_write")
Cc: <[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 WebResourceService::StartFetch() {
ScheduleFetch(cache_update_delay_ms_);
prefs_->SetString(last_update_time_pref_name_,
base::DoubleToString(base::Time::Now().ToDoubleT()));
if (in_fetch_)
return;
in_fetch_ = true;
GURL web_resource_server =
application_locale_.empty()
? web_resource_server_
: google_util::AppendGoogleLocaleParam(web_resource_server_,
application_locale_);
DVLOG(1) << "WebResourceService StartFetch " << web_resource_server;
url_fetcher_ =
net::URLFetcher::Create(web_resource_server, net::URLFetcher::GET, this);
url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE |
net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
url_fetcher_->SetRequestContext(request_context_.get());
url_fetcher_->Start();
}
Commit Message: Add data usage tracking for chrome services
Add data usage tracking for captive portal, web resource and signin services
BUG=655749
Review-Url: https://codereview.chromium.org/2643013004
Cr-Commit-Position: refs/heads/master@{#445810}
CWE ID: CWE-190
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: RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
SetContentViewCore(NULL);
if (!shared_surface_.is_null()) {
ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle(
shared_surface_);
}
}
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:
Target: 1
Example 2:
Code: void ExtensionSettingsHandler::Initialize() {
}
Commit Message: [i18n-fixlet] Make strings branding specific in extension code.
IDS_EXTENSIONS_UNINSTALL
IDS_EXTENSIONS_INCOGNITO_WARNING
IDS_EXTENSION_INSTALLED_HEADING
IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug.
IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE
BUG=NONE
TEST=NONE
Review URL: http://codereview.chromium.org/9107061
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
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 PPVarToNPVariant(PP_Var var, NPVariant* result) {
switch (var.type) {
case PP_VARTYPE_UNDEFINED:
VOID_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_NULL:
NULL_TO_NPVARIANT(*result);
break;
case PP_VARTYPE_BOOL:
BOOLEAN_TO_NPVARIANT(var.value.as_bool, *result);
break;
case PP_VARTYPE_INT32:
INT32_TO_NPVARIANT(var.value.as_int, *result);
break;
case PP_VARTYPE_DOUBLE:
DOUBLE_TO_NPVARIANT(var.value.as_double, *result);
break;
case PP_VARTYPE_STRING: {
scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
if (!string) {
VOID_TO_NPVARIANT(*result);
return false;
}
const std::string& value = string->value();
STRINGN_TO_NPVARIANT(base::strdup(value.c_str()), value.size(), *result);
break;
}
case PP_VARTYPE_OBJECT: {
scoped_refptr<ObjectVar> object(ObjectVar::FromPPVar(var));
if (!object) {
VOID_TO_NPVARIANT(*result);
return false;
}
OBJECT_TO_NPVARIANT(WebBindings::retainObject(object->np_object()),
*result);
break;
}
case PP_VARTYPE_ARRAY:
case PP_VARTYPE_DICTIONARY:
VOID_TO_NPVARIANT(*result);
break;
}
return true;
}
Commit Message: Fix invalid read in ppapi code
BUG=77493
TEST=attached test
Review URL: http://codereview.chromium.org/6883059
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@82172 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: cJSON *cJSON_CreateInt( int64_t num )
{
cJSON *item = cJSON_New_Item();
if ( item ) {
item->type = cJSON_Number;
item->valuefloat = num;
item->valueint = num;
}
return item;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool BrowserInit::LaunchWithProfile::Launch(
Profile* profile,
const std::vector<GURL>& urls_to_open,
bool process_startup) {
DCHECK(profile);
profile_ = profile;
if (command_line_.HasSwitch(switches::kDnsLogDetails))
chrome_browser_net::EnablePredictorDetailedLog(true);
if (command_line_.HasSwitch(switches::kDnsPrefetchDisable) &&
profile->GetNetworkPredictor()) {
profile->GetNetworkPredictor()->EnablePredictor(false);
}
if (command_line_.HasSwitch(switches::kDumpHistogramsOnExit))
base::StatisticsRecorder::set_dump_on_exit(true);
if (command_line_.HasSwitch(switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line_.GetSwitchValueASCII(switches::kRemoteDebuggingPort);
int64 port;
if (base::StringToInt64(port_str, &port) && port > 0 && port < 65535) {
std::string frontend_str;
if (command_line_.HasSwitch(switches::kRemoteDebuggingFrontend)) {
frontend_str = command_line_.GetSwitchValueASCII(
switches::kRemoteDebuggingFrontend);
}
g_browser_process->InitDevToolsHttpProtocolHandler(
profile,
"127.0.0.1",
static_cast<int>(port),
frontend_str);
} else {
DLOG(WARNING) << "Invalid http debugger port number " << port;
}
}
if (OpenApplicationWindow(profile)) {
RecordLaunchModeHistogram(LM_AS_WEBAPP);
} else {
RecordLaunchModeHistogram(urls_to_open.empty()?
LM_TO_BE_DECIDED : LM_WITH_URLS);
ProcessLaunchURLs(process_startup, urls_to_open);
OpenApplicationTab(profile);
if (process_startup) {
if (browser_defaults::kOSSupportsOtherBrowsers &&
!command_line_.HasSwitch(switches::kNoDefaultBrowserCheck)) {
if (!CheckIfAutoLaunched(profile)) {
CheckDefaultBrowser(profile);
}
}
#if defined(OS_MACOSX)
KeystoneInfoBar::PromotionInfoBar(profile);
#endif
}
}
#if defined(OS_WIN)
if (command_line_.HasSwitch(switches::kPrint)) {
Browser* browser = BrowserList::GetLastActive();
browser->Print();
}
#endif
if (!command_line_.HasSwitch(switches::kNoEvents)) {
FilePath script_path;
PathService::Get(chrome::FILE_RECORDED_SCRIPT, &script_path);
bool record_mode = command_line_.HasSwitch(switches::kRecordMode);
bool playback_mode = command_line_.HasSwitch(switches::kPlaybackMode);
if (record_mode && chrome::kRecordModeEnabled)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
#if defined(OS_WIN)
if (process_startup)
ShellIntegration::MigrateChromiumShortcuts();
#endif // defined(OS_WIN)
return true;
}
Commit Message: chromeos: Move audio, power, and UI files into subdirs.
This moves more files from chrome/browser/chromeos/ into
subdirectories.
BUG=chromium-os:22896
TEST=did chrome os builds both with and without aura
TBR=sky
Review URL: http://codereview.chromium.org/9125006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 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: process_secondary_order(STREAM s)
{
/* The length isn't calculated correctly by the server.
* For very compact orders the length becomes negative
* so a signed integer must be used. */
uint16 length;
uint16 flags;
uint8 type;
uint8 *next_order;
in_uint16_le(s, length);
in_uint16_le(s, flags); /* used by bmpcache2 */
in_uint8(s, type);
next_order = s->p + (sint16) length + 7;
switch (type)
{
case RDP_ORDER_RAW_BMPCACHE:
process_raw_bmpcache(s);
break;
case RDP_ORDER_COLCACHE:
process_colcache(s);
break;
case RDP_ORDER_BMPCACHE:
process_bmpcache(s);
break;
case RDP_ORDER_FONTCACHE:
process_fontcache(s);
break;
case RDP_ORDER_RAW_BMPCACHE2:
process_bmpcache2(s, flags, False); /* uncompressed */
break;
case RDP_ORDER_BMPCACHE2:
process_bmpcache2(s, flags, True); /* compressed */
break;
case RDP_ORDER_BRUSHCACHE:
process_brushcache(s, flags);
break;
default:
logger(Graphics, Warning,
"process_secondary_order(), unhandled secondary order %d", type);
}
s->p = next_order;
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119
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: ActionReply Smb4KMountHelper::mount(const QVariantMap &args)
{
ActionReply reply;
QMapIterator<QString, QVariant> it(args);
proc.setOutputChannelMode(KProcess::SeparateChannels);
proc.setProcessEnvironment(QProcessEnvironment::systemEnvironment());
#if defined(Q_OS_LINUX)
proc.setEnv("PASSWD", entry["mh_url"].toUrl().password(), true);
#endif
QVariantMap entry = it.value().toMap();
KProcess proc(this);
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
#else
#endif
proc.setProgram(command);
proc.start();
if (proc.waitForStarted(-1))
{
bool userKill = false;
QStringList command;
#if defined(Q_OS_LINUX)
command << entry["mh_command"].toString();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
command << entry["mh_options"].toStringList();
#elif defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD)
command << entry["mh_command"].toString();
command << entry["mh_options"].toStringList();
command << entry["mh_unc"].toString();
command << entry["mh_mountpoint"].toString();
else
{
}
if (HelperSupport::isStopped())
{
proc.kill();
userKill = true;
break;
}
else
{
}
}
if (proc.exitStatus() == KProcess::CrashExit)
{
if (!userKill)
{
reply.setType(ActionReply::HelperErrorType);
reply.setErrorDescription(i18n("The mount process crashed."));
break;
}
else
{
}
}
else
{
QString stdErr = QString::fromUtf8(proc.readAllStandardError());
reply.addData(QString("mh_error_message_%1").arg(index), stdErr.trimmed());
}
}
Commit Message:
CWE ID: CWE-20
Target: 1
Example 2:
Code: static int imap_tags_edit(struct Context *ctx, const char *tags, char *buf, size_t buflen)
{
char *new = NULL;
char *checker = NULL;
struct ImapData *idata = (struct ImapData *) ctx->data;
/* Check for \* flags capability */
if (!imap_has_flag(&idata->flags, NULL))
{
mutt_error(_("IMAP server doesn't support custom flags"));
return -1;
}
*buf = '\0';
if (tags)
strncpy(buf, tags, buflen);
if (mutt_get_field("Tags: ", buf, buflen, 0) != 0)
return -1;
/* each keyword must be atom defined by rfc822 as:
*
* atom = 1*<any CHAR except specials, SPACE and CTLs>
* CHAR = ( 0.-127. )
* specials = "(" / ")" / "<" / ">" / "@"
* / "," / ";" / ":" / "\" / <">
* / "." / "[" / "]"
* SPACE = ( 32. )
* CTLS = ( 0.-31., 127.)
*
* And must be separated by one space.
*/
new = buf;
checker = buf;
SKIPWS(checker);
while (*checker != '\0')
{
if (*checker < 32 || *checker >= 127 || // We allow space because it's the separator
*checker == 40 || // (
*checker == 41 || // )
*checker == 60 || // <
*checker == 62 || // >
*checker == 64 || // @
*checker == 44 || // ,
*checker == 59 || // ;
*checker == 58 || // :
*checker == 92 || // backslash
*checker == 34 || // "
*checker == 46 || // .
*checker == 91 || // [
*checker == 93) // ]
{
mutt_error(_("Invalid IMAP flags"));
return 0;
}
/* Skip duplicate space */
while (*checker == ' ' && *(checker + 1) == ' ')
checker++;
/* copy char to new and go the next one */
*new ++ = *checker++;
}
*new = '\0';
new = buf; /* rewind */
mutt_str_remove_trailing_ws(new);
if (mutt_str_strcmp(tags, buf) == 0)
return 0;
return 1;
}
Commit Message: quote imap strings more carefully
Co-authored-by: JerikoOne <[email protected]>
CWE ID: CWE-77
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 authenc_geniv_ahash_update_done(struct crypto_async_request *areq,
int err)
{
struct aead_request *req = areq->data;
struct crypto_aead *authenc = crypto_aead_reqtfm(req);
struct crypto_authenc_ctx *ctx = crypto_aead_ctx(authenc);
struct authenc_request_ctx *areq_ctx = aead_request_ctx(req);
struct ahash_request *ahreq = (void *)(areq_ctx->tail + ctx->reqoff);
if (err)
goto out;
ahash_request_set_crypt(ahreq, areq_ctx->sg, ahreq->result,
areq_ctx->cryptlen);
ahash_request_set_callback(ahreq, aead_request_flags(req) &
CRYPTO_TFM_REQ_MAY_SLEEP,
areq_ctx->complete, req);
err = crypto_ahash_finup(ahreq);
if (err)
goto out;
scatterwalk_map_and_copy(ahreq->result, areq_ctx->sg,
areq_ctx->cryptlen,
crypto_aead_authsize(authenc), 1);
out:
authenc_request_complete(req, err);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[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: Mac_Read_POST_Resource( FT_Library library,
FT_Stream stream,
FT_Long *offsets,
FT_Long resource_cnt,
FT_Long face_index,
FT_Face *aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
FT_Memory memory = library->memory;
FT_Byte* pfb_data;
int i, type, flags;
FT_Long len;
FT_Long pfb_len, pfb_pos, pfb_lenpos;
FT_Long rlen, temp;
if ( face_index == -1 )
face_index = 0;
if ( face_index != 0 )
return error;
/* Find the length of all the POST resources, concatenated. Assume */
/* worst case (each resource in its own section). */
pfb_len = 0;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit;
if ( FT_READ_LONG( temp ) )
goto Exit;
pfb_len += temp + 6;
}
if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
goto Exit;
pfb_data[0] = 0x80;
pfb_data[1] = 1; /* Ascii section */
pfb_data[2] = 0; /* 4-byte length, fill in later */
pfb_data[3] = 0;
pfb_data[4] = 0;
pfb_data[5] = 0;
pfb_pos = 6;
pfb_lenpos = 2;
len = 0;
type = 1;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit2;
if ( FT_READ_LONG( rlen ) )
goto Exit;
if ( FT_READ_USHORT( flags ) )
goto Exit;
FT_TRACE3(( "POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\n",
i, offsets[i], rlen, flags ));
/* the flags are part of the resource, so rlen >= 2. */
/* but some fonts declare rlen = 0 for empty fragment */
if ( rlen > 2 )
if ( ( flags >> 8 ) == type )
len += rlen;
else
{
if ( pfb_lenpos + 3 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
if ( ( flags >> 8 ) == 5 ) /* End of font mark */
break;
if ( pfb_pos + 6 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_pos++] = 0x80;
type = flags >> 8;
len = rlen;
pfb_data[pfb_pos++] = (FT_Byte)type;
pfb_lenpos = pfb_pos;
pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
}
error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
if ( error )
goto Exit2;
pfb_pos += rlen;
}
if ( pfb_pos + 2 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_pos++] = 0x80;
pfb_data[pfb_pos++] = 3;
if ( pfb_lenpos + 3 > pfb_len + 2 )
goto Exit2;
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
return open_face_from_buffer( library,
pfb_data,
pfb_pos,
face_index,
"type1",
aface );
Exit2:
FT_FREE( pfb_data );
Exit:
return error;
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: Ins_WS( TT_ExecContext exc,
FT_Long* args )
{
FT_ULong I = (FT_ULong)args[0];
if ( BOUNDSL( I, exc->storeSize ) )
{
if ( exc->pedantic_hinting )
ARRAY_BOUND_ERROR;
}
else
exc->storage[I] = args[1];
}
Commit Message:
CWE ID: CWE-476
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: SiteInstanceTest()
: ui_thread_(BrowserThread::UI, &message_loop_),
file_user_blocking_thread_(BrowserThread::FILE_USER_BLOCKING,
&message_loop_),
io_thread_(BrowserThread::IO, &message_loop_),
old_browser_client_(NULL) {
}
Commit Message: Check for appropriate bindings in process-per-site mode.
BUG=174059
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12188025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98
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 PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr,
int preview_request_id,
bool* cancel) {
PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_addr,
preview_request_id,
cancel);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200
Target: 1
Example 2:
Code: static void mix_pool_bytes(struct entropy_store *r, const void *in, int bytes)
{
mix_pool_bytes_extract(r, in, bytes, NULL);
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[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 PrintPreviewHandler::GetNumberFormatAndMeasurementSystem(
base::DictionaryValue* settings) {
UErrorCode errorCode = U_ZERO_ERROR;
const char* locale = g_browser_process->GetApplicationLocale().c_str();
UMeasurementSystem system = ulocdata_getMeasurementSystem(locale, &errorCode);
if (errorCode > U_ZERO_ERROR || system == UMS_LIMIT)
system = UMS_SI;
settings->SetString(kNumberFormat, base::FormatDouble(123456.78, 2));
settings->SetInteger(kMeasurementSystem, system);
}
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
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: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize)
{ int k ;
for (k = 0 ; k < bufsize - 1 ; k++)
{ if (psf->headindex < psf->headend)
{ ptr [k] = psf->header [psf->headindex] ;
psf->headindex ++ ;
}
else
{ psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ;
ptr [k] = psf->header [psf->headindex] ;
psf->headindex = psf->headend ;
} ;
if (ptr [k] == '\n')
break ;
} ;
ptr [k] = 0 ;
return k ;
} /* header_gets */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119
Target: 1
Example 2:
Code: FT_Get_Char_Index( FT_Face face,
FT_ULong charcode )
{
FT_UInt result = 0;
if ( face && face->charmap )
{
FT_CMap cmap = FT_CMAP( face->charmap );
if ( charcode > 0xFFFFFFFFUL )
{
FT_TRACE1(( "FT_Get_Char_Index: too large charcode" ));
FT_TRACE1(( " 0x%x is truncated\n", charcode ));
}
result = cmap->clazz->char_index( cmap, (FT_UInt32)charcode );
}
return result;
}
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: long ContentEncoding::ParseEncryptionEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption->key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption->signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption->sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos,
size,
pReader,
&encryption->aes_settings);
if (status)
return status;
}
pos += size; //consume payload
assert(pos <= stop);
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
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: do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return 1;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
return 0;
}
Commit Message: Extend build-id reporting to 8-byte IDs that lld can generate (Ed Maste)
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ipv6_renew_option(void *ohdr,
struct ipv6_opt_hdr __user *newopt, int newoptlen,
int inherit,
struct ipv6_opt_hdr **hdr,
char **p)
{
if (inherit) {
if (ohdr) {
memcpy(*p, ohdr, ipv6_optlen((struct ipv6_opt_hdr *)ohdr));
*hdr = (struct ipv6_opt_hdr *)*p;
*p += CMSG_ALIGN(ipv6_optlen(*hdr));
}
} else {
if (newopt) {
if (copy_from_user(*p, newopt, newoptlen))
return -EFAULT;
*hdr = (struct ipv6_opt_hdr *)*p;
if (ipv6_optlen(*hdr) > newoptlen)
return -EINVAL;
*p += CMSG_ALIGN(newoptlen);
}
}
return 0;
}
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
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 vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
{
int i,n;
for (i=0; i < f->page_crc_tests; ++i)
f->scan[i].bytes_done = 0;
if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
if (data_len < 4) return 0;
data_len -= 3; // need to look for 4-byte sequence, so don't miss
for (i=0; i < data_len; ++i) {
if (data[i] == 0x4f) {
if (0==memcmp(data+i, ogg_page_header, 4)) {
int j,len;
uint32 crc;
if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
data_len = i;
break;
}
len = 27 + data[i+26];
for (j=0; j < data[i+26]; ++j)
len += data[i+27+j];
crc = 0;
for (j=0; j < 22; ++j)
crc = crc32_update(crc, data[i+j]);
for ( ; j < 26; ++j)
crc = crc32_update(crc, 0);
n = f->page_crc_tests++;
f->scan[n].bytes_left = len-j;
f->scan[n].crc_so_far = crc;
f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
if (data[i+27+data[i+26]-1] == 255)
f->scan[n].sample_loc = ~0;
else
f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
f->scan[n].bytes_done = i+j;
if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
break;
}
}
}
}
for (i=0; i < f->page_crc_tests;) {
uint32 crc;
int j;
int n = f->scan[i].bytes_done;
int m = f->scan[i].bytes_left;
if (m > data_len - n) m = data_len - n;
crc = f->scan[i].crc_so_far;
for (j=0; j < m; ++j)
crc = crc32_update(crc, data[n+j]);
f->scan[i].bytes_left -= m;
f->scan[i].crc_so_far = crc;
if (f->scan[i].bytes_left == 0) {
if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
data_len = n+m; // consumption amount is wherever that scan ended
f->page_crc_tests = -1; // drop out of page scan mode
f->previous_length = 0; // decode-but-don't-output one frame
f->next_seg = -1; // start a new page
f->current_loc = f->scan[i].sample_loc; // set the current sample location
f->current_loc_valid = f->current_loc != ~0U;
return data_len;
}
f->scan[i] = f->scan[--f->page_crc_tests];
} else {
++i;
}
}
return data_len;
}
Commit Message: fix unchecked length in stb_vorbis that could crash on corrupt/invalid files
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* sspi_SecureHandleGetLowerPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwLower);
return pointer;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476
Target: 1
Example 2:
Code: static void CL_GenerateQKey(void)
{
int len = 0;
unsigned char buff[ QKEY_SIZE ];
fileHandle_t f;
len = FS_SV_FOpenFileRead( QKEY_FILE, &f );
FS_FCloseFile( f );
if( len == QKEY_SIZE ) {
Com_Printf( "QKEY found.\n" );
return;
}
else {
if( len > 0 ) {
Com_Printf( "QKEY file size != %d, regenerating\n",
QKEY_SIZE );
}
Com_Printf( "QKEY building random string\n" );
Com_RandomBytes( buff, sizeof(buff) );
f = FS_SV_FOpenFileWrite( QKEY_FILE );
if( !f ) {
Com_Printf( "QKEY could not open %s for write\n",
QKEY_FILE );
return;
}
FS_Write( buff, sizeof(buff), f );
FS_FCloseFile( f );
Com_Printf( "QKEY generated\n" );
}
}
Commit Message: 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: cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t ofs = CDF_GETUINT32(p, (i << 1) + 1);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
Commit Message: Add missing check offset test (Francisco Alonso, Jan Kaluza at RedHat)
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 int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr,
pmd_t *pmd, unsigned int flags)
{
int result;
handle_t *handle = NULL;
struct inode *inode = file_inode(vma->vm_file);
struct super_block *sb = inode->i_sb;
bool write = flags & FAULT_FLAG_WRITE;
if (write) {
sb_start_pagefault(sb);
file_update_time(vma->vm_file);
handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE,
ext4_chunk_trans_blocks(inode,
PMD_SIZE / PAGE_SIZE));
}
if (IS_ERR(handle))
result = VM_FAULT_SIGBUS;
else
result = __dax_pmd_fault(vma, addr, pmd, flags,
ext4_get_block_dax, ext4_end_io_unwritten);
if (write) {
if (!IS_ERR(handle))
ext4_journal_stop(handle);
sb_end_pagefault(sb);
}
return result;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static inline bool isCombiningVoicedSoundMark(UChar character)
{
switch (character) {
case 0x3099: // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
case 0x309A: // COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
return true;
}
return false;
}
Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure.
BUG=156930,177197
[email protected]
Review URL: https://codereview.chromium.org/15057010
git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_option_dentry *topt = filp->private_data;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (val != 0 && val != 1)
return -EINVAL;
if (!!(topt->flags->val & topt->opt->bit) != val) {
mutex_lock(&trace_types_lock);
ret = __set_tracer_option(topt->tr, topt->flags,
topt->opt, !val);
mutex_unlock(&trace_types_lock);
if (ret)
return ret;
}
*ppos += cnt;
return cnt;
}
Commit Message: Merge tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace
Pull tracing fixes from Steven Rostedt:
"This contains a few fixes and a clean up.
- a bad merge caused an "endif" to go in the wrong place in
scripts/Makefile.build
- softirq tracing fix for tracing that corrupts lockdep and causes a
false splat
- histogram documentation typo fixes
- fix a bad memory reference when passing in no filter to the filter
code
- simplify code by using the swap macro instead of open coding the
swap"
* tag 'trace-v4.18-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/rostedt/linux-trace:
tracing: Fix SKIP_STACK_VALIDATION=1 build due to bad merge with -mrecord-mcount
tracing: Fix some errors in histogram documentation
tracing: Use swap macro in update_max_tr
softirq: Reorder trace_softirqs_on to prevent lockdep splat
tracing: Check for no filter when processing event filters
CWE ID: CWE-787
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.