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: bool SVGElement::HasSVGParent() const {
return ParentOrShadowHostElement() &&
ParentOrShadowHostElement()->IsSVGElement();
}
Commit Message: Fix SVG crash for v0 distribution into foreignObject.
We require a parent element to be an SVG element for non-svg-root
elements in order to create a LayoutObject for them. However, we checked
the light tree parent element, not the flat tree one which is the parent
for the layout tree construction. Note that this is just an issue in
Shadow DOM v0 since v1 does not allow shadow roots on SVG elements.
Bug: 915469
Change-Id: Id81843abad08814fae747b5bc81c09666583f130
Reviewed-on: https://chromium-review.googlesource.com/c/1382494
Reviewed-by: Fredrik Söderquist <[email protected]>
Commit-Queue: Rune Lillesveen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#617487}
CWE ID: CWE-704
Target: 1
Example 2:
Code: static blk_status_t pf_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)
{
struct pf_unit *pf = hctx->queue->queuedata;
spin_lock_irq(&pf_spin_lock);
list_add_tail(&bd->rq->queuelist, &pf->rq_list);
pf_request();
spin_unlock_irq(&pf_spin_lock);
return BLK_STS_OK;
}
Commit Message: paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[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: void RenderWidgetHostImpl::DidReceiveRendererFrame() {
view_->DidReceiveRendererFrame();
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
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::hasContentEditableAttributeSet() const {
const AtomicString& contentEditableValue = getAttribute(contenteditableAttr);
if (contentEditableValue.isNull())
return false;
return contentEditableValue.isEmpty() ||
equalIgnoringCase(contentEditableValue, "true");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254
Target: 1
Example 2:
Code: static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int segno = curseg->segno;
int dir = ALLOC_LEFT;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, segno));
if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
dir = ALLOC_RIGHT;
if (test_opt(sbi, NOHEAP))
dir = ALLOC_RIGHT;
segno = __get_next_segno(sbi, type);
get_new_segment(sbi, &segno, new_sec, dir);
curseg->next_segno = segno;
reset_curseg(sbi, type, 1);
curseg->alloc_type = LFS;
}
Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control
Mount fs with option noflush_merge, boot failed for illegal address
fcc in function f2fs_issue_flush:
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush); -> Here, fcc illegal
return ret;
}
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[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: static int get_default_root(pool *p, int allow_symlinks, const char **root) {
config_rec *c = NULL;
const char *dir = NULL;
int res;
c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE);
while (c != NULL) {
pr_signals_handle();
/* Check the groups acl */
if (c->argc < 2) {
dir = c->argv[0];
break;
}
res = pr_expr_eval_group_and(((char **) c->argv)+1);
if (res) {
dir = c->argv[0];
break;
}
c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE);
}
if (dir != NULL) {
const char *new_dir;
/* Check for any expandable variables. */
new_dir = path_subst_uservar(p, &dir);
if (new_dir != NULL) {
dir = new_dir;
}
if (strncmp(dir, "/", 2) == 0) {
dir = NULL;
} else {
char *realdir;
int xerrno = 0;
if (allow_symlinks == FALSE) {
char *path, target_path[PR_TUNABLE_PATH_MAX + 1];
struct stat st;
size_t pathlen;
/* First, deal with any possible interpolation. dir_realpath() will
* do this for us, but dir_realpath() ALSO automatically follows
* symlinks, which is what we do NOT want to do here.
*/
path = pstrdup(p, dir);
if (*path != '/') {
if (*path == '~') {
if (pr_fs_interpolate(dir, target_path,
sizeof(target_path)-1) < 0) {
return -1;
}
path = target_path;
}
}
/* Note: lstat(2) is sensitive to the presence of a trailing slash on
* the path, particularly in the case of a symlink to a directory.
* Thus to get the correct test, we need to remove any trailing slash
* that might be present. Subtle.
*/
pathlen = strlen(path);
if (pathlen > 1 &&
path[pathlen-1] == '/') {
path[pathlen-1] = '\0';
}
pr_fs_clear_cache2(path);
res = pr_fsio_lstat(path, &st);
if (res < 0) {
xerrno = errno;
pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path,
strerror(xerrno));
errno = xerrno;
return -1;
}
if (S_ISLNK(st.st_mode)) {
pr_log_pri(PR_LOG_WARNING,
"error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks "
"config)", path);
errno = EPERM;
return -1;
}
}
/* We need to be the final user here so that if the user has their home
* directory with a mode the user proftpd is running (i.e. the User
* directive) as can not traverse down, we can still have the default
* root.
*/
pr_fs_clear_cache2(dir);
PRIVS_USER
realdir = dir_realpath(p, dir);
xerrno = errno;
PRIVS_RELINQUISH
if (realdir) {
dir = realdir;
} else {
/* Try to provide a more informative message. */
char interp_dir[PR_TUNABLE_PATH_MAX + 1];
memset(interp_dir, '\0', sizeof(interp_dir));
(void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1);
pr_log_pri(PR_LOG_NOTICE,
"notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s",
dir, interp_dir, strerror(xerrno));
errno = xerrno;
}
}
}
*root = dir;
return 0;
}
Commit Message: Walk the entire DefaultRoot path, checking for symlinks of any component,
when AllowChrootSymlinks is disabled.
CWE ID: CWE-59
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 semctl_down(struct ipc_namespace *ns, int semid,
int cmd, int version, void __user *p)
{
struct sem_array *sma;
int err;
struct semid64_ds semid64;
struct kern_ipc_perm *ipcp;
if(cmd == IPC_SET) {
if (copy_semid_from_user(&semid64, p, version))
return -EFAULT;
}
ipcp = ipcctl_pre_down_nolock(ns, &sem_ids(ns), semid, cmd,
&semid64.sem_perm, 0);
if (IS_ERR(ipcp))
return PTR_ERR(ipcp);
sma = container_of(ipcp, struct sem_array, sem_perm);
err = security_sem_semctl(sma, cmd);
if (err) {
rcu_read_unlock();
goto out_unlock;
}
switch(cmd){
case IPC_RMID:
ipc_lock_object(&sma->sem_perm);
freeary(ns, ipcp);
goto out_up;
case IPC_SET:
ipc_lock_object(&sma->sem_perm);
err = ipc_update_perm(&semid64.sem_perm, ipcp);
if (err)
goto out_unlock;
sma->sem_ctime = get_seconds();
break;
default:
rcu_read_unlock();
err = -EINVAL;
goto out_up;
}
out_unlock:
sem_unlock(sma);
out_up:
up_write(&sem_ids(ns).rw_mutex);
return err;
}
Commit Message: ipc,sem: fine grained locking for semtimedop
Introduce finer grained locking for semtimedop, to handle the common case
of a program wanting to manipulate one semaphore from an array with
multiple semaphores.
If the call is a semop manipulating just one semaphore in an array with
multiple semaphores, only take the lock for that semaphore itself.
If the call needs to manipulate multiple semaphores, or another caller is
in a transaction that manipulates multiple semaphores, the sem_array lock
is taken, as well as all the locks for the individual semaphores.
On a 24 CPU system, performance numbers with the semop-multi
test with N threads and N semaphores, look like this:
vanilla Davidlohr's Davidlohr's + Davidlohr's +
threads patches rwlock patches v3 patches
10 610652 726325 1783589 2142206
20 341570 365699 1520453 1977878
30 288102 307037 1498167 2037995
40 290714 305955 1612665 2256484
50 288620 312890 1733453 2650292
60 289987 306043 1649360 2388008
70 291298 306347 1723167 2717486
80 290948 305662 1729545 2763582
90 290996 306680 1736021 2757524
100 292243 306700 1773700 3059159
[[email protected]: do not call sem_lock when bogus sma]
[[email protected]: make refcounter atomic]
Signed-off-by: Rik van Riel <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Acked-by: Davidlohr Bueso <[email protected]>
Cc: Chegu Vinod <[email protected]>
Cc: Jason Low <[email protected]>
Reviewed-by: Michel Lespinasse <[email protected]>
Cc: Peter Hurley <[email protected]>
Cc: Stanislav Kinsbursky <[email protected]>
Tested-by: Emmanuel Benisty <[email protected]>
Tested-by: Sedat Dilek <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: ServiceWorkerContextCore::ProviderHostIterator::~ProviderHostIterator() {}
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: static int nf_tables_dump_chains(struct sk_buff *skb,
struct netlink_callback *cb)
{
const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
const struct nft_af_info *afi;
const struct nft_table *table;
const struct nft_chain *chain;
unsigned int idx = 0, s_idx = cb->args[0];
struct net *net = sock_net(skb->sk);
int family = nfmsg->nfgen_family;
rcu_read_lock();
cb->seq = net->nft.base_seq;
list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
if (family != NFPROTO_UNSPEC && family != afi->family)
continue;
list_for_each_entry_rcu(table, &afi->tables, list) {
list_for_each_entry_rcu(chain, &table->chains, list) {
if (idx < s_idx)
goto cont;
if (idx > s_idx)
memset(&cb->args[1], 0,
sizeof(cb->args) - sizeof(cb->args[0]));
if (nf_tables_fill_chain_info(skb, net,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NFT_MSG_NEWCHAIN,
NLM_F_MULTI,
afi->family, table, chain) < 0)
goto done;
nl_dump_check_consistent(cb, nlmsg_hdr(skb));
cont:
idx++;
}
}
}
done:
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies
Jumping between chains doesn't mix well with flush ruleset. Rules
from a different chain and set elements may still refer to us.
[ 353.373791] ------------[ cut here ]------------
[ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159!
[ 353.373896] invalid opcode: 0000 [#1] SMP
[ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi
[ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98
[ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010
[...]
[ 353.375018] Call Trace:
[ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540
[ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0
[ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0
[ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790
[ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0
[ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70
[ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30
[ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0
[ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400
[ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90
[ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20
[ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0
[ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80
[ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d
[ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20
[ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b
Release objects in this order: rules -> sets -> chains -> tables, to
make sure no references to chains are held anymore.
Reported-by: Asbjoern Sloth Toennesen <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-19
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_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if(image->numcomps < 4) return;
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for(i = 0; i < max; ++i)
{
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
free(image->comps[3].data); image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
Commit Message: Fix Heap Buffer Overflow in function color_cmyk_to_rgb
Fix uclouvain/openjpeg#774
CWE ID: CWE-119
Target: 1
Example 2:
Code: void bt_sock_unregister(int proto)
{
if (proto < 0 || proto >= BT_MAX_PROTO)
return;
write_lock(&bt_proto_lock);
bt_proto[proto] = NULL;
write_unlock(&bt_proto_lock);
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: PHP_FUNCTION(linkinfo)
{
char *link;
size_t link_len;
zend_stat_t sb;
int ret;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) {
return;
}
ret = VCWD_STAT(link, &sb);
if (ret == -1) {
php_error_docref(NULL, E_WARNING, "%s", strerror(errno));
RETURN_LONG(Z_L(-1));
}
RETURN_LONG((zend_long) sb.st_dev);
}
Commit Message: Fixed bug #76459 windows linkinfo lacks openbasedir check
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: CreateDataReductionProxyChromeIOData(
Profile* profile,
const scoped_refptr<base::SingleThreadTaskRunner>& io_task_runner,
const scoped_refptr<base::SingleThreadTaskRunner>& ui_task_runner) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(profile);
DCHECK(profile->GetPrefs());
data_reduction_proxy::DataReductionProxySettings*
data_reduction_proxy_settings =
DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
profile);
bool enabled = data_reduction_proxy_settings &&
data_reduction_proxy_settings->IsDataSaverEnabledByUser();
std::unique_ptr<data_reduction_proxy::DataReductionProxyIOData>
data_reduction_proxy_io_data(
new data_reduction_proxy::DataReductionProxyIOData(
DataReductionProxyChromeSettings::GetClient(),
profile->GetPrefs(), content::GetNetworkConnectionTracker(),
io_task_runner, ui_task_runner, enabled, GetUserAgent(),
version_info::GetChannelString(chrome::GetChannel())));
data_reduction_proxy_io_data->set_lofi_decider(
std::make_unique<data_reduction_proxy::ContentLoFiDecider>());
data_reduction_proxy_io_data->set_resource_type_provider(
std::make_unique<data_reduction_proxy::ContentResourceTypeProvider>());
data_reduction_proxy_io_data->set_lofi_ui_service(
std::make_unique<data_reduction_proxy::ContentLoFiUIService>(
ui_task_runner, base::Bind(&OnLoFiResponseReceivedOnUI)));
return data_reduction_proxy_io_data;
}
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: 1
Example 2:
Code: void SetHostContentSetting(WebContents* contents, ContentSetting setting) {
HostContentSettingsMapFactory::GetForProfile(
Profile::FromBrowserContext(contents->GetBrowserContext()))
->SetContentSettingDefaultScope(
contents->GetURL(), GURL(),
CONTENT_SETTINGS_TYPE_AUTOMATIC_DOWNLOADS, std::string(), setting);
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#574437}
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: process_queued_listen_addrs(ServerOptions *options)
{
u_int i;
if (options->num_ports == 0)
options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
if (options->address_family == -1)
options->address_family = AF_UNSPEC;
for (i = 0; i < options->num_queued_listens; i++) {
add_listen_addr(options, options->queued_listen_addrs[i],
options->queued_listen_ports[i]);
free(options->queued_listen_addrs[i]);
options->queued_listen_addrs[i] = NULL;
}
free(options->queued_listen_addrs);
options->queued_listen_addrs = NULL;
free(options->queued_listen_ports);
options->queued_listen_ports = NULL;
options->num_queued_listens = 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
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: znumicc_components(i_ctx_t * i_ctx_p)
{
ref * pnval;
ref * pstrmval;
stream * s;
int ncomps, expected = 0, code;
cmm_profile_t *picc_profile;
os_ptr op = osp;
check_type(*op, t_dictionary);
check_dict_read(*op);
code = dict_find_string(op, "N", &pnval);
if (code < 0)
return code;
if (code == 0)
return code;
if (code == 0)
return_error(gs_error_undefined);
ncomps = pnval->value.intval;
/* verify the DataSource entry. Create profile from stream */
if (dict_find_string(op, "DataSource", &pstrmval) <= 0)
if (picc_profile == NULL)
return gs_throw(gs_error_VMerror, "Creation of ICC profile failed");
picc_profile->num_comps = ncomps;
picc_profile->profile_handle =
gsicc_get_profile_handle_buffer(picc_profile->buffer,
picc_profile->buffer_size,
gs_gstate_memory(igs));
if (picc_profile->profile_handle == NULL) {
rc_decrement(picc_profile,"znumicc_components");
make_int(op, expected);
return 0;
}
picc_profile->data_cs =
gscms_get_profile_data_space(picc_profile->profile_handle,
picc_profile->memory);
switch (picc_profile->data_cs) {
case gsCIEXYZ:
case gsCIELAB:
case gsRGB:
expected = 3;
break;
case gsGRAY:
expected = 1;
break;
case gsCMYK:
expected = 4;
break;
case gsNCHANNEL:
expected = 0;
break;
case gsNAMED:
case gsUNDEFINED:
expected = -1;
break;
}
make_int(op, expected);
rc_decrement(picc_profile,"zset_outputintent");
return 0;
}
Commit Message:
CWE ID: CWE-704
Target: 1
Example 2:
Code: static int is_hwaccel_pix_fmt(enum AVPixelFormat pix_fmt)
{
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
return desc->flags & AV_PIX_FMT_FLAG_HWACCEL;
}
Commit Message: avcodec/utils: correct align value for interplay
Fixes out of array access
Fixes: 452/fuzz-1-ffmpeg_VIDEO_AV_CODEC_ID_INTERPLAY_VIDEO_fuzzer
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-787
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 jspSetNoExecute() {
execInfo.execute = (execInfo.execute & (JsExecFlags)(int)~EXEC_RUN_MASK) | EXEC_NO;
}
Commit Message: Fix bug if using an undefined member of an object for for..in (fix #1437)
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void RenderWidgetHostViewAura::WasHidden() {
if (host_->is_hidden())
return;
host_->WasHidden();
released_front_lock_ = NULL;
if (ShouldReleaseFrontSurface() &&
host_->is_accelerated_compositing_active()) {
current_surface_ = 0;
UpdateExternalTexture();
}
AdjustSurfaceProtection();
#if defined(OS_WIN)
aura::RootWindow* root_window = window_->GetRootWindow();
if (root_window) {
HWND parent = root_window->GetAcceleratedWidget();
LPARAM lparam = reinterpret_cast<LPARAM>(this);
EnumChildWindows(parent, HideWindowsCallback, lparam);
}
#endif
}
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 DXVAVideoDecodeAccelerator::DXVAPictureBuffer::ReusePictureBuffer() {
DCHECK(decoding_surface_);
eglReleaseTexImage(
static_cast<EGLDisplay*>(eglGetDisplay(EGL_DEFAULT_DISPLAY)),
decoding_surface_,
EGL_BACK_BUFFER);
set_available(true);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID:
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: PrintingContext::Result PrintingContextCairo::UseDefaultSettings() {
DCHECK(!in_print_job_);
ResetSettings();
#if defined(OS_CHROMEOS)
int dpi = 300;
gfx::Size physical_size_device_units;
gfx::Rect printable_area_device_units;
int32_t width = 0;
int32_t height = 0;
UErrorCode error = U_ZERO_ERROR;
ulocdata_getPaperSize(app_locale_.c_str(), &height, &width, &error);
if (error != U_ZERO_ERROR) {
LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: "
<< error;
width = static_cast<int>(8.5 * dpi);
height = static_cast<int>(11 * dpi);
} else {
width = static_cast<int>(ConvertUnitDouble(width, 25.4, 1.0) * dpi);
height = static_cast<int>(ConvertUnitDouble(height, 25.4, 1.0) * dpi);
}
physical_size_device_units.SetSize(width, height);
printable_area_device_units.SetRect(
static_cast<int>(PrintSettingsInitializerGtk::kLeftMarginInInch * dpi),
static_cast<int>(PrintSettingsInitializerGtk::kTopMarginInInch * dpi),
width - (PrintSettingsInitializerGtk::kLeftMarginInInch +
PrintSettingsInitializerGtk::kRightMarginInInch) * dpi,
height - (PrintSettingsInitializerGtk::kTopMarginInInch +
PrintSettingsInitializerGtk::kBottomMarginInInch) * dpi);
settings_.set_dpi(dpi);
settings_.SetPrinterPrintableArea(physical_size_device_units,
printable_area_device_units,
dpi);
#else
if (!print_dialog_) {
print_dialog_ = create_dialog_func_(this);
print_dialog_->AddRefToDialog();
}
print_dialog_->UseDefaultSettings();
#endif // defined(OS_CHROMEOS)
return OK;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 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: TabsCustomBindings::TabsCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("OpenChannelToTab",
base::Bind(&TabsCustomBindings::OpenChannelToTab,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284
Target: 1
Example 2:
Code: LauncherView::~LauncherView() {
bounds_animator_->RemoveObserver(this);
model_->RemoveObserver(this);
}
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
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 journal_t *ext4_get_dev_journal(struct super_block *sb,
dev_t j_dev)
{
struct buffer_head *bh;
journal_t *journal;
ext4_fsblk_t start;
ext4_fsblk_t len;
int hblock, blocksize;
ext4_fsblk_t sb_block;
unsigned long offset;
struct ext4_super_block *es;
struct block_device *bdev;
BUG_ON(!EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL));
bdev = ext4_blkdev_get(j_dev, sb);
if (bdev == NULL)
return NULL;
blocksize = sb->s_blocksize;
hblock = bdev_logical_block_size(bdev);
if (blocksize < hblock) {
ext4_msg(sb, KERN_ERR,
"blocksize too small for journal device");
goto out_bdev;
}
sb_block = EXT4_MIN_BLOCK_SIZE / blocksize;
offset = EXT4_MIN_BLOCK_SIZE % blocksize;
set_blocksize(bdev, blocksize);
if (!(bh = __bread(bdev, sb_block, blocksize))) {
ext4_msg(sb, KERN_ERR, "couldn't read superblock of "
"external journal");
goto out_bdev;
}
es = (struct ext4_super_block *) (((char *)bh->b_data) + offset);
if ((le16_to_cpu(es->s_magic) != EXT4_SUPER_MAGIC) ||
!(le32_to_cpu(es->s_feature_incompat) &
EXT4_FEATURE_INCOMPAT_JOURNAL_DEV)) {
ext4_msg(sb, KERN_ERR, "external journal has "
"bad superblock");
brelse(bh);
goto out_bdev;
}
if (memcmp(EXT4_SB(sb)->s_es->s_journal_uuid, es->s_uuid, 16)) {
ext4_msg(sb, KERN_ERR, "journal UUID does not match");
brelse(bh);
goto out_bdev;
}
len = ext4_blocks_count(es);
start = sb_block + 1;
brelse(bh); /* we're done with the superblock */
journal = jbd2_journal_init_dev(bdev, sb->s_bdev,
start, len, blocksize);
if (!journal) {
ext4_msg(sb, KERN_ERR, "failed to create device journal");
goto out_bdev;
}
journal->j_private = sb;
ll_rw_block(READ, 1, &journal->j_sb_buffer);
wait_on_buffer(journal->j_sb_buffer);
if (!buffer_uptodate(journal->j_sb_buffer)) {
ext4_msg(sb, KERN_ERR, "I/O error on journal device");
goto out_journal;
}
if (be32_to_cpu(journal->j_superblock->s_nr_users) != 1) {
ext4_msg(sb, KERN_ERR, "External journal has more than one "
"user (unsupported) - %d",
be32_to_cpu(journal->j_superblock->s_nr_users));
goto out_journal;
}
EXT4_SB(sb)->journal_bdev = bdev;
ext4_init_journal_params(sb, journal);
return journal;
out_journal:
jbd2_journal_destroy(journal);
out_bdev:
ext4_blkdev_put(bdev);
return NULL;
}
Commit Message: ext4: fix undefined behavior in ext4_fill_flex_info()
Commit 503358ae01b70ce6909d19dd01287093f6b6271c ("ext4: avoid divide by
zero when trying to mount a corrupted file system") fixes CVE-2009-4307
by performing a sanity check on s_log_groups_per_flex, since it can be
set to a bogus value by an attacker.
sbi->s_log_groups_per_flex = sbi->s_es->s_log_groups_per_flex;
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex < 2) { ... }
This patch fixes two potential issues in the previous commit.
1) The sanity check might only work on architectures like PowerPC.
On x86, 5 bits are used for the shifting amount. That means, given a
large s_log_groups_per_flex value like 36, groups_per_flex = 1 << 36
is essentially 1 << 4 = 16, rather than 0. This will bypass the check,
leaving s_log_groups_per_flex and groups_per_flex inconsistent.
2) The sanity check relies on undefined behavior, i.e., oversized shift.
A standard-confirming C compiler could rewrite the check in unexpected
ways. Consider the following equivalent form, assuming groups_per_flex
is unsigned for simplicity.
groups_per_flex = 1 << sbi->s_log_groups_per_flex;
if (groups_per_flex == 0 || groups_per_flex == 1) {
We compile the code snippet using Clang 3.0 and GCC 4.6. Clang will
completely optimize away the check groups_per_flex == 0, leaving the
patched code as vulnerable as the original. GCC keeps the check, but
there is no guarantee that future versions will do the same.
Signed-off-by: Xi Wang <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
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 setRewriteURLFolder(const char* folder)
{
m_rewriteFolder = folder;
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Target: 1
Example 2:
Code: SCTP_STATIC void sctp_destroy_sock(struct sock *sk)
{
struct sctp_sock *sp;
SCTP_DEBUG_PRINTK("sctp_destroy_sock(sk: %p)\n", sk);
/* Release our hold on the endpoint. */
sp = sctp_sk(sk);
if (sp->do_auto_asconf) {
sp->do_auto_asconf = 0;
list_del(&sp->auto_asconf_list);
}
sctp_endpoint_free(sp->ep);
local_bh_disable();
percpu_counter_dec(&sctp_sockets_allocated);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
}
Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS
Building sctp may fail with:
In function ‘copy_from_user’,
inlined from ‘sctp_getsockopt_assoc_stats’ at
net/sctp/socket.c:5656:20:
arch/x86/include/asm/uaccess_32.h:211:26: error: call to
‘copy_from_user_overflow’ declared with attribute error: copy_from_user()
buffer size is not provably correct
if built with W=1 due to a missing parameter size validation
before the call to copy_from_user.
Signed-off-by: Guenter Roeck <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int hub_set_address(struct usb_device *udev, int devnum)
{
int retval;
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
/*
* The host controller will choose the device address,
* instead of the core having chosen it earlier
*/
if (!hcd->driver->address_device && devnum <= 1)
return -EINVAL;
if (udev->state == USB_STATE_ADDRESS)
return 0;
if (udev->state != USB_STATE_DEFAULT)
return -EINVAL;
if (hcd->driver->address_device)
retval = hcd->driver->address_device(hcd, udev);
else
retval = usb_control_msg(udev, usb_sndaddr0pipe(),
USB_REQ_SET_ADDRESS, 0, devnum, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (retval == 0) {
update_devnum(udev, devnum);
/* Device now using proper address. */
usb_set_device_state(udev, USB_STATE_ADDRESS);
usb_ep0_reinit(udev);
}
return retval;
}
Commit Message: USB: fix invalid memory access in hub_activate()
Commit 8520f38099cc ("USB: change hub initialization sleeps to
delayed_work") changed the hub_activate() routine to make part of it
run in a workqueue. However, the commit failed to take a reference to
the usb_hub structure or to lock the hub interface while doing so. As
a result, if a hub is plugged in and quickly unplugged before the work
routine can run, the routine will try to access memory that has been
deallocated. Or, if the hub is unplugged while the routine is
running, the memory may be deallocated while it is in active use.
This patch fixes the problem by taking a reference to the usb_hub at
the start of hub_activate() and releasing it at the end (when the work
is finished), and by locking the hub interface while the work routine
is running. It also adds a check at the start of the routine to see
if the hub has already been disconnected, in which nothing should be
done.
Signed-off-by: Alan Stern <[email protected]>
Reported-by: Alexandru Cornea <[email protected]>
Tested-by: Alexandru Cornea <[email protected]>
Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work")
CC: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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: static void rpza_decode_stream(RpzaContext *s)
{
int width = s->avctx->width;
int stride = s->frame.linesize[0] / 2;
int row_inc = stride - 4;
int stream_ptr = 0;
int chunk_size;
unsigned char opcode;
int n_blocks;
unsigned short colorA = 0, colorB;
unsigned short color4[4];
unsigned char index, idx;
unsigned short ta, tb;
unsigned short *pixels = (unsigned short *)s->frame.data[0];
int row_ptr = 0;
int pixel_ptr = 0;
int block_ptr;
int pixel_x, pixel_y;
int total_blocks;
/* First byte is always 0xe1. Warn if it's different */
if (s->buf[stream_ptr] != 0xe1)
av_log(s->avctx, AV_LOG_ERROR, "First chunk byte is 0x%02x instead of 0xe1\n",
s->buf[stream_ptr]);
/* Get chunk size, ingnoring first byte */
chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;
stream_ptr += 4;
/* If length mismatch use size from MOV file and try to decode anyway */
if (chunk_size != s->size)
av_log(s->avctx, AV_LOG_ERROR, "MOV chunk size != encoded chunk size; using MOV chunk size\n");
chunk_size = s->size;
/* Number of 4x4 blocks in frame. */
total_blocks = ((s->avctx->width + 3) / 4) * ((s->avctx->height + 3) / 4);
/* Process chunk data */
while (stream_ptr < chunk_size) {
opcode = s->buf[stream_ptr++]; /* Get opcode */
n_blocks = (opcode & 0x1f) + 1; /* Extract block counter from opcode */
/* If opcode MSbit is 0, we need more data to decide what to do */
if ((opcode & 0x80) == 0) {
colorA = (opcode << 8) | (s->buf[stream_ptr++]);
opcode = 0;
if ((s->buf[stream_ptr] & 0x80) != 0) {
/* Must behave as opcode 110xxxxx, using colorA computed
* above. Use fake opcode 0x20 to enter switch block at
* the right place */
opcode = 0x20;
n_blocks = 1;
}
}
switch (opcode & 0xe0) {
/* Skip blocks */
case 0x80:
while (n_blocks--) {
ADVANCE_BLOCK();
}
break;
/* Fill blocks with one color */
case 0xa0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill blocks with 4 colors */
case 0xc0:
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
case 0x20:
colorB = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
/* sort out the colors */
color4[0] = colorB;
color4[1] = 0;
color4[2] = 0;
color4[3] = colorA;
/* red components */
ta = (colorA >> 10) & 0x1F;
tb = (colorB >> 10) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;
/* green components */
ta = (colorA >> 5) & 0x1F;
tb = (colorB >> 5) & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;
color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;
/* blue components */
ta = colorA & 0x1F;
tb = colorB & 0x1F;
color4[1] |= ((11 * ta + 21 * tb) >> 5);
color4[2] |= ((21 * ta + 11 * tb) >> 5);
if (s->size - stream_ptr < n_blocks * 4)
return;
while (n_blocks--) {
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
index = s->buf[stream_ptr++];
for (pixel_x = 0; pixel_x < 4; pixel_x++){
idx = (index >> (2 * (3 - pixel_x))) & 0x03;
pixels[block_ptr] = color4[idx];
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
}
break;
/* Fill block with 16 colors */
case 0x00:
if (s->size - stream_ptr < 16)
return;
block_ptr = row_ptr + pixel_ptr;
for (pixel_y = 0; pixel_y < 4; pixel_y++) {
for (pixel_x = 0; pixel_x < 4; pixel_x++){
/* We already have color of upper left pixel */
if ((pixel_y != 0) || (pixel_x !=0)) {
colorA = AV_RB16 (&s->buf[stream_ptr]);
stream_ptr += 2;
}
pixels[block_ptr] = colorA;
block_ptr++;
}
block_ptr += row_inc;
}
ADVANCE_BLOCK();
break;
/* Unknown opcode */
default:
av_log(s->avctx, AV_LOG_ERROR, "Unknown opcode %d in rpza chunk."
" Skip remaining %d bytes of chunk data.\n", opcode,
chunk_size - stream_ptr);
return;
} /* Opcode switch */
}
}
Commit Message: avcodec/rpza: Perform pointer advance and checks before using the pointers
Fixes out of array accesses
Fixes Ticket2850
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: CloudPolicySubsystem::ObserverRegistrar::ObserverRegistrar(
CloudPolicySubsystem* cloud_policy_subsystem,
CloudPolicySubsystem::Observer* observer)
: observer_(observer) {
policy_notifier_ = cloud_policy_subsystem->notifier();
policy_notifier_->AddObserver(observer);
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 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: int ssl3_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long alg_k,Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
if (s->cert == NULL)
{
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
return(-1);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch (s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
/* s->state=SSL_ST_ACCEPT; */
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE|SSL_ST_ACCEPT:
case SSL_ST_OK|SSL_ST_ACCEPT:
s->server=1;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version>>8) != 3)
{
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
return -1;
}
if (!ssl_security(s, SSL_SECOP_VERSION, 0,
s->version, NULL))
{
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
return -1;
}
s->type=SSL_ST_ACCEPT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
BUF_MEM_free(buf);
ret= -1;
goto end;
}
s->init_buf=buf;
}
if (!ssl3_setup_buffers(s))
{
ret= -1;
goto end;
}
s->init_num=0;
s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
/* Should have been reset by ssl3_get_finished, too. */
s->s3->change_cipher_spec = 0;
if (s->state != SSL_ST_RENEGOTIATE)
{
/* Ok, we now need to push on a buffering BIO so that
* the output is sent in a way that TCP likes :-)
*/
if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
ssl3_init_finished_mac(s);
s->state=SSL3_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
}
else if (!s->s3->send_connection_binding &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
/* Server attempting to renegotiate with
* client that doesn't support secure
* renegotiation.
*/
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
ret = -1;
goto end;
}
else
{
/* s->state == SSL_ST_RENEGOTIATE,
* we will just send a HelloRequest */
s->ctx->stats.sess_accept_renegotiate++;
s->state=SSL3_ST_SW_HELLO_REQ_A;
}
break;
case SSL3_ST_SW_HELLO_REQ_A:
case SSL3_ST_SW_HELLO_REQ_B:
s->shutdown=0;
ret=ssl3_send_hello_request(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
ssl3_init_finished_mac(s);
break;
case SSL3_ST_SW_HELLO_REQ_C:
s->state=SSL_ST_OK;
break;
case SSL3_ST_SR_CLNT_HELLO_A:
case SSL3_ST_SR_CLNT_HELLO_B:
case SSL3_ST_SR_CLNT_HELLO_C:
ret=ssl3_get_client_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_SRP
s->state = SSL3_ST_SR_CLNT_HELLO_D;
case SSL3_ST_SR_CLNT_HELLO_D:
{
int al;
if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
{
/* callback indicates firther work to be done */
s->rwstate=SSL_X509_LOOKUP;
goto end;
}
if (ret != SSL_ERROR_NONE)
{
ssl3_send_alert(s,SSL3_AL_FATAL,al);
/* This is not really an error but the only means to
for a client to detect whether srp is supported. */
if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
ret= -1;
goto end;
}
}
#endif
s->renegotiate = 2;
s->state=SSL3_ST_SW_SRVR_HELLO_A;
s->init_num=0;
break;
case SSL3_ST_SW_SRVR_HELLO_A:
case SSL3_ST_SW_SRVR_HELLO_B:
ret=ssl3_send_server_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->hit)
{
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
else
s->state=SSL3_ST_SW_CHANGE_A;
}
#else
if (s->hit)
s->state=SSL3_ST_SW_CHANGE_A;
#endif
else
s->state = SSL3_ST_SW_CERT_A;
s->init_num = 0;
break;
case SSL3_ST_SW_CERT_A:
case SSL3_ST_SW_CERT_B:
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or KRB5 or SRP */
if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP))
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
ret=ssl3_send_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_SW_CERT_STATUS_A;
else
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_SW_KEY_EXCH_A:
case SSL3_ST_SW_KEY_EXCH_B:
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/* clear this, it may get reset by
* send_server_key_exchange */
if ((s->options & SSL_OP_EPHEMERAL_RSA)
#ifndef OPENSSL_NO_KRB5
&& !(alg_k & SSL_kKRB5)
#endif /* OPENSSL_NO_KRB5 */
)
/* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
* even when forbidden by protocol specs
* (handshake may fail as clients are not required to
* be able to handle this) */
s->s3->tmp.use_rsa_tmp=1;
else
s->s3->tmp.use_rsa_tmp=0;
/* only send if a DH key exchange, fortezza or
* RSA but we have a sign only certificate
*
* PSK: may send PSK identity hints
*
* For ECC ciphersuites, we send a serverKeyExchange
* message only if the cipher suite is either
* ECDH-anon or ECDHE. In other cases, the
* server certificate contains the server's
* public key for key exchange.
*/
if (s->s3->tmp.use_rsa_tmp
/* PSK: send ServerKeyExchange if PSK identity
* hint if provided */
#ifndef OPENSSL_NO_PSK
|| ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
|| (alg_k & SSL_kDHE)
|| (alg_k & SSL_kECDHE)
|| ((alg_k & SSL_kRSA)
&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
)
)
)
)
{
ret=ssl3_send_server_key_exchange(s);
if (ret <= 0) goto end;
}
else
skip=1;
s->state=SSL3_ST_SW_CERT_REQ_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_REQ_A:
case SSL3_ST_SW_CERT_REQ_B:
if (/* don't request cert unless asked for it: */
!(s->verify_mode & SSL_VERIFY_PEER) ||
/* if SSL_VERIFY_CLIENT_ONCE is set,
* don't request cert during re-negotiation: */
((s->session->peer != NULL) &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
/* never request cert in anonymous ciphersuites
* (see section "Certificate request" in SSL 3 drafts
* and in RFC 2246): */
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
/* ... except when the application insists on verification
* (against the specs, but s3_clnt.c accepts this for SSL 3) */
!(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
/* never request cert in Kerberos ciphersuites */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) ||
/* don't request certificate for SRP auth */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
/* With normal PSK Certificates and
* Certificate Requests are omitted */
|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
/* no cert request */
skip=1;
s->s3->tmp.cert_request=0;
s->state=SSL3_ST_SW_SRVR_DONE_A;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
s->s3->tmp.cert_request=1;
ret=ssl3_send_certificate_request(s);
if (ret <= 0) goto end;
#ifndef NETSCAPE_HANG_BUG
s->state=SSL3_ST_SW_SRVR_DONE_A;
#else
s->state=SSL3_ST_SW_FLUSH;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
#endif
s->init_num=0;
}
break;
case SSL3_ST_SW_SRVR_DONE_A:
case SSL3_ST_SW_SRVR_DONE_B:
ret=ssl3_send_server_done(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
break;
case SSL3_ST_SW_FLUSH:
/* This code originally checked to see if
* any data was pending using BIO_CTRL_INFO
* and then flushed. This caused problems
* as documented in PR#1939. The proposed
* fix doesn't completely resolve this issue
* as buggy implementations of BIO_CTRL_PENDING
* still exist. So instead we just flush
* unconditionally.
*/
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL3_ST_SR_CERT_A:
case SSL3_ST_SR_CERT_B:
if (s->s3->tmp.cert_request)
{
ret=ssl3_get_client_certificate(s);
if (ret <= 0) goto end;
}
s->init_num=0;
s->state=SSL3_ST_SR_KEY_EXCH_A;
break;
case SSL3_ST_SR_KEY_EXCH_A:
case SSL3_ST_SR_KEY_EXCH_B:
ret=ssl3_get_client_key_exchange(s);
if (ret <= 0)
goto end;
if (ret == 2)
{
/* For the ECDH ciphersuites when
* the client sends its ECDH pub key in
* a certificate, the CertificateVerify
* message is not sent.
* Also for GOST ciphersuites when
* the client uses its key from the certificate
* for key exchange.
*/
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
}
else if (SSL_USE_SIGALGS(s))
{
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
if (!s->session->peer)
break;
/* For sigalgs freeze the handshake buffer
* at this point and digest cached records.
*/
if (!s->s3->handshake_buffer)
{
SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
return -1;
}
s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
int offset=0;
int dgst_num;
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
/* We need to get hashes here so if there is
* a client cert, it can be verified
* FIXME - digest processing for CertificateVerify
* should be generalized. But it is next step
*/
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
if (s->s3->handshake_dgst[dgst_num])
{
int dgst_size;
s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
if (dgst_size < 0)
{
ret = -1;
goto end;
}
offset+=dgst_size;
}
}
break;
case SSL3_ST_SR_CERT_VRFY_A:
case SSL3_ST_SR_CERT_VRFY_B:
/*
* This *should* be the first time we enable CCS, but be
* extra careful about surrounding code changes. We need
* to set this here because we don't know if we're
* expecting a CertificateVerify or not.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
/* we should decide if we expected this one */
ret=ssl3_get_cert_verify(s);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num=0;
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_SR_NEXT_PROTO_A:
case SSL3_ST_SR_NEXT_PROTO_B:
/*
* Enable CCS for resumed handshakes with NPN.
* In a full handshake with NPN, we end up here through
* SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
* already set. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_next_proto(s);
if (ret <= 0) goto end;
s->init_num = 0;
s->state=SSL3_ST_SR_FINISHED_A;
break;
#endif
case SSL3_ST_SR_FINISHED_A:
case SSL3_ST_SR_FINISHED_B:
/*
* Enable CCS for resumed handshakes without NPN.
* In a full handshake, we end up here through
* SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was
* already set. Receiving a CCS clears the flag, so make
* sure not to re-enable it to ban duplicates.
* s->s3->change_cipher_spec is set when a CCS is
* processed in s3_pkt.c, and remains set until
* the client's Finished message is read.
*/
if (!s->s3->change_cipher_spec)
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
SSL3_ST_SR_FINISHED_B);
if (ret <= 0) goto end;
if (s->hit)
s->state=SSL_ST_OK;
#ifndef OPENSSL_NO_TLSEXT
else if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
#endif
else
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_SW_SESSION_TICKET_A:
case SSL3_ST_SW_SESSION_TICKET_B:
ret=ssl3_send_newsession_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_STATUS_A:
case SSL3_ST_SW_CERT_STATUS_B:
ret=ssl3_send_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_SW_CHANGE_A:
case SSL3_ST_SW_CHANGE_B:
s->session->cipher=s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
{ ret= -1; goto end; }
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FINISHED_A;
s->init_num=0;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_SW_FINISHED_A:
case SSL3_ST_SW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
s->method->ssl3_enc->server_finished_label,
s->method->ssl3_enc->server_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FLUSH;
if (s->hit)
{
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
{
s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
}
else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#endif
}
else
s->s3->tmp.next_state=SSL_ST_OK;
s->init_num=0;
break;
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
/* remove buffering on output */
ssl_free_wbio_buffer(s);
s->init_num=0;
if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
{
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
s->handshake_func=ssl3_accept;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
}
ret = 1;
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_ACCEPT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
Commit Message: Only allow ephemeral RSA keys in export ciphersuites.
OpenSSL clients would tolerate temporary RSA keys in non-export
ciphersuites. It also had an option SSL_OP_EPHEMERAL_RSA which
enabled this server side. Remove both options as they are a
protocol violation.
Thanks to Karthikeyan Bhargavan for reporting this issue.
(CVE-2015-0204)
Reviewed-by: Matt Caswell <[email protected]>
CWE ID: CWE-310
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::Local<v8::Value> compileAndRunPrivateScript(ScriptState* scriptState,
String scriptClassName,
const char* source,
size_t size) {
v8::Isolate* isolate = scriptState->isolate();
v8::TryCatch block(isolate);
String sourceString(source, size);
String fileName = scriptClassName + ".js";
v8::Local<v8::Context> context = scriptState->context();
v8::Local<v8::Object> global = context->Global();
v8::Local<v8::Value> privateScriptController =
global->Get(context, v8String(isolate, "privateScriptController"))
.ToLocalChecked();
RELEASE_ASSERT(privateScriptController->IsUndefined() ||
privateScriptController->IsObject());
if (privateScriptController->IsObject()) {
v8::Local<v8::Object> privateScriptControllerObject =
privateScriptController.As<v8::Object>();
v8::Local<v8::Value> importFunctionValue =
privateScriptControllerObject->Get(context, v8String(isolate, "import"))
.ToLocalChecked();
if (importFunctionValue->IsUndefined()) {
v8::Local<v8::Function> function;
if (!v8::FunctionTemplate::New(isolate, importFunction)
->GetFunction(context)
.ToLocal(&function) ||
!v8CallBoolean(privateScriptControllerObject->Set(
context, v8String(isolate, "import"), function))) {
dumpV8Message(context, block.Message());
LOG(FATAL)
<< "Private script error: Setting import function failed. (Class "
"name = "
<< scriptClassName.utf8().data() << ")";
}
}
}
v8::Local<v8::Script> script;
if (!v8Call(V8ScriptRunner::compileScript(
v8String(isolate, sourceString), fileName, String(),
TextPosition::minimumPosition(), isolate, nullptr, nullptr,
nullptr, NotSharableCrossOrigin),
script, block)) {
dumpV8Message(context, block.Message());
LOG(FATAL) << "Private script error: Compile failed. (Class name = "
<< scriptClassName.utf8().data() << ")";
}
v8::Local<v8::Value> result;
if (!v8Call(V8ScriptRunner::runCompiledInternalScript(isolate, script),
result, block)) {
dumpV8Message(context, block.Message());
LOG(FATAL) << "Private script error: installClass() failed. (Class name = "
<< scriptClassName.utf8().data() << ")";
}
return result;
}
Commit Message: Don't touch the prototype chain to get the private script controller.
Prior to this patch, private scripts attempted to get the
"privateScriptController" property off the global object without verifying if
the property actually exists on the global. If the property hasn't been set yet,
this operation could descend into the prototype chain and potentially return
a named property from the WindowProperties object, leading to release asserts
and general confusion.
BUG=668552
Review-Url: https://codereview.chromium.org/2529163002
Cr-Commit-Position: refs/heads/master@{#434627}
CWE ID: CWE-79
Target: 1
Example 2:
Code: static void *alloc_ep(int size, gfp_t gfp)
{
struct iwch_ep_common *epc;
epc = kzalloc(size, gfp);
if (epc) {
kref_init(&epc->kref);
spin_lock_init(&epc->lock);
init_waitqueue_head(&epc->waitq);
}
PDBG("%s alloc ep %p\n", __func__, epc);
return epc;
}
Commit Message: iw_cxgb3: Fix incorrectly returning error on success
The cxgb3_*_send() functions return NET_XMIT_ values, which are
positive integers values. So don't treat positive return values
as an error.
Signed-off-by: Steve Wise <[email protected]>
Signed-off-by: Hariprasad Shenai <[email protected]>
Signed-off-by: Doug Ledford <[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 ssize_t mergeable_rx_buffer_size_show(struct netdev_rx_queue *queue,
struct rx_queue_attribute *attribute, char *buf)
{
struct virtnet_info *vi = netdev_priv(queue->dev);
unsigned int queue_index = get_netdev_rx_queue_index(queue);
struct ewma *avg;
BUG_ON(queue_index >= vi->max_queue_pairs);
avg = &vi->rq[queue_index].mrg_avg_pkt_len;
return sprintf(buf, "%u\n", get_mergeable_buf_len(avg));
}
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 php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415
Target: 1
Example 2:
Code: static int php_openssl_load_rand_file(const char * file, int *egdsocket, int *seeded) /* {{{ */
{
char buffer[MAXPATHLEN];
TSRMLS_FETCH();
*egdsocket = 0;
*seeded = 0;
if (file == NULL) {
file = RAND_file_name(buffer, sizeof(buffer));
} else if (RAND_egd(file) > 0) {
/* if the given filename is an EGD socket, don't
* write anything back to it */
*egdsocket = 1;
return SUCCESS;
}
if (file == NULL || !RAND_load_file(file, -1)) {
if (RAND_status() == 0) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to load random state; not enough random data!");
return FAILURE;
}
return FAILURE;
}
*seeded = 1;
return SUCCESS;
}
/* }}} */
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: error::Error GLES2DecoderImpl::DoDrawElements(
const char* function_name,
bool instanced,
GLenum mode,
GLsizei count,
GLenum type,
int32 offset,
GLsizei primcount) {
if (ShouldDeferDraws())
return error::kDeferCommandUntilLater;
if (!bound_element_array_buffer_) {
SetGLError(GL_INVALID_OPERATION,
function_name, "No element array buffer bound");
return error::kNoError;
}
if (count < 0) {
SetGLError(GL_INVALID_VALUE, function_name, "count < 0");
return error::kNoError;
}
if (offset < 0) {
SetGLError(GL_INVALID_VALUE, function_name, "offset < 0");
return error::kNoError;
}
if (!validators_->draw_mode.IsValid(mode)) {
SetGLErrorInvalidEnum(function_name, mode, "mode");
return error::kNoError;
}
if (!validators_->index_type.IsValid(type)) {
SetGLErrorInvalidEnum(function_name, type, "type");
return error::kNoError;
}
if (primcount < 0) {
SetGLError(GL_INVALID_VALUE, function_name, "primcount < 0");
return error::kNoError;
}
if (!CheckBoundFramebuffersValid(function_name)) {
return error::kNoError;
}
if (count == 0 || (instanced && primcount == 0)) {
return error::kNoError;
}
GLuint max_vertex_accessed;
if (!bound_element_array_buffer_->GetMaxValueForRange(
offset, count, type, &max_vertex_accessed)) {
SetGLError(GL_INVALID_OPERATION,
function_name, "range out of bounds for buffer");
return error::kNoError;
}
if (IsDrawValid(function_name, max_vertex_accessed, primcount)) {
if (!ClearUnclearedTextures()) {
SetGLError(GL_INVALID_VALUE, function_name, "out of memory");
return error::kNoError;
}
bool simulated_attrib_0 = false;
if (!SimulateAttrib0(
function_name, max_vertex_accessed, &simulated_attrib_0)) {
return error::kNoError;
}
bool simulated_fixed_attribs = false;
if (SimulateFixedAttribs(
function_name, max_vertex_accessed, &simulated_fixed_attribs,
primcount)) {
bool textures_set = SetBlackTextureForNonRenderableTextures();
ApplyDirtyState();
const GLvoid* indices = reinterpret_cast<const GLvoid*>(offset);
if (!instanced) {
glDrawElements(mode, count, type, indices);
} else {
glDrawElementsInstancedANGLE(mode, count, type, indices, primcount);
}
ProcessPendingQueries();
if (textures_set) {
RestoreStateForNonRenderableTextures();
}
if (simulated_fixed_attribs) {
RestoreStateForSimulatedFixedAttribs();
}
}
if (simulated_attrib_0) {
RestoreStateForAttrib(0);
}
if (WasContextLost()) {
LOG(ERROR) << " GLES2DecoderImpl: Context lost during DrawElements.";
return error::kLostContext;
}
}
return error::kNoError;
}
Commit Message: Fix SafeAdd and SafeMultiply
BUG=145648,145544
Review URL: https://chromiumcodereview.appspot.com/10916165
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98
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: image_pixel_setf(image_pixel *this, unsigned int max)
{
this->redf = this->red / (double)max;
this->greenf = this->green / (double)max;
this->bluef = this->blue / (double)max;
this->alphaf = this->alpha / (double)max;
if (this->red < max)
this->rede = this->redf * DBL_EPSILON;
else
this->rede = 0;
if (this->green < max)
this->greene = this->greenf * DBL_EPSILON;
else
this->greene = 0;
if (this->blue < max)
this->bluee = this->bluef * DBL_EPSILON;
else
this->bluee = 0;
if (this->alpha < max)
this->alphae = this->alphaf * DBL_EPSILON;
else
this->alphae = 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: void AsyncFileSystemChromium::removeRecursively(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks> callbacks)
{
m_webFileSystem->removeRecursively(path, new WebKit::WebFileSystemCallbacksImpl(callbacks));
}
Commit Message: Remove BlobRegistry indirection since there is only one implementation.
BUG=
Review URL: https://chromiumcodereview.appspot.com/15851008
git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: struct cgroup_ops *cgfs_ops_init(void)
{
return &cgfs_ops;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
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: image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_gray_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID:
Target: 1
Example 2:
Code: AXObjectCache* Document::existingAXObjectCache() const
{
if (!axObjectCacheOwner().layoutView())
return 0;
return axObjectCacheOwner().m_axObjectCache.get();
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: WebCString WebPageSerializer::serializeToMHTML(WebView* view)
{
RefPtr<SharedBuffer> mhtml = serializePageToMHTML(toWebViewImpl(view)->page(), MHTMLArchive::UseDefaultEncoding);
return WebCString(mhtml->data(), mhtml->size());
}
Commit Message: Revert 162155 "This review merges the two existing page serializ..."
Change r162155 broke the world even though it was landed using the CQ.
> This review merges the two existing page serializers, WebPageSerializerImpl and
> PageSerializer, into one, PageSerializer. In addition to this it moves all
> the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the
> PageSerializerTest structure and splits out one test for MHTML into a new
> MHTMLTest file.
>
> Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the
> 'Save Page as MHTML' flag is enabled now uses the same code, and should thus
> have the same feature set. Meaning that both modes now should be a bit better.
>
> Detailed list of changes:
>
> - PageSerializerTest: Prepare for more DTD test
> - PageSerializerTest: Remove now unneccesary input image test
> - PageSerializerTest: Remove unused WebPageSerializer/Impl code
> - PageSerializerTest: Move data URI morph test
> - PageSerializerTest: Move data URI test
> - PageSerializerTest: Move namespace test
> - PageSerializerTest: Move SVG Image test
> - MHTMLTest: Move MHTML specific test to own test file
> - PageSerializerTest: Delete duplicate XML header test
> - PageSerializerTest: Move blank frame test
> - PageSerializerTest: Move CSS test
> - PageSerializerTest: Add frameset/frame test
> - PageSerializerTest: Move old iframe test
> - PageSerializerTest: Move old elements test
> - Use PageSerizer for saving web pages
> - PageSerializerTest: Test for rewriting links
> - PageSerializer: Add rewrite link accumulator
> - PageSerializer: Serialize images in iframes/frames src
> - PageSerializer: XHTML fix for meta tags
> - PageSerializer: Add presentation CSS
> - PageSerializer: Rename out parameter
>
> BUG=
> [email protected]
>
> Review URL: https://codereview.chromium.org/68613003
[email protected]
Review URL: https://codereview.chromium.org/73673003
git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: const CuePoint* Cues::GetFirst() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count == 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
#endif
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[0];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
return pCP;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: static struct k_itimer * alloc_posix_timer(void)
{
struct k_itimer *tmr;
tmr = kmem_cache_zalloc(posix_timers_cache, GFP_KERNEL);
if (!tmr)
return tmr;
if (unlikely(!(tmr->sigq = sigqueue_alloc()))) {
kmem_cache_free(posix_timers_cache, tmr);
return NULL;
}
clear_siginfo(&tmr->sigq->info);
return tmr;
}
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: void ResourceDispatcherHostImpl::PauseRequest(int child_id,
int request_id,
bool pause) {
GlobalRequestID global_id(child_id, request_id);
PendingRequestList::iterator i = pending_requests_.find(global_id);
if (i == pending_requests_.end()) {
DVLOG(1) << "Pausing a request that wasn't found";
return;
}
ResourceRequestInfoImpl* info =
ResourceRequestInfoImpl::ForRequest(i->second);
int pause_count = info->pause_count() + (pause ? 1 : -1);
if (pause_count < 0) {
NOTREACHED(); // Unbalanced call to pause.
return;
}
info->set_pause_count(pause_count);
VLOG(1) << "To pause (" << pause << "): " << i->second->url().spec();
if (info->pause_count() == 0) {
MessageLoop::current()->PostTask(FROM_HERE,
base::Bind(
&ResourceDispatcherHostImpl::ResumeRequest,
weak_factory_.GetWeakPtr(),
global_id));
}
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 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: XdmcpGenerateKey (XdmAuthKeyPtr key)
{
#ifndef HAVE_ARC4RANDOM_BUF
long lowbits, highbits;
srandom ((int)getpid() ^ time((Time_t *)0));
highbits = random ();
highbits = random ();
getbits (lowbits, key->data);
getbits (highbits, key->data + 4);
#else
arc4random_buf(key->data, 8);
#endif
}
Commit Message:
CWE ID: CWE-320
Target: 1
Example 2:
Code: InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
}
Commit Message: Add new MotionEvent flag for partially obscured windows.
Due to more complex window layouts resulting in lots of overlapping
windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to
only be set when the point at which the window was touched is
obscured. Unfortunately, this doesn't prevent tapjacking attacks that
overlay the dialog's text, making a potentially dangerous operation
seem innocuous. To avoid this on particularly sensitive dialogs,
introduce a new flag that really does tell you when your window is
being even partially overlapped.
We aren't exposing this as API since we plan on making the original
flag more robust. This is really a workaround for system dialogs
since we generally know their layout and screen position, and that
they're unlikely to be overlapped by other applications.
Bug: 26677796
Change-Id: I9e336afe90f262ba22015876769a9c510048fd47
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 Browser::FileSelected(const FilePath& path, int index, void* params) {
profile_->set_last_selected_directory(path.DirName());
GURL file_url = net::FilePathToFileURL(path);
if (!file_url.is_empty())
OpenURL(file_url, GURL(), CURRENT_TAB, PageTransition::TYPED);
}
Commit Message: Implement a bubble that appears at the top of the screen when a tab enters
fullscreen mode via webkitRequestFullScreen(), telling the user how to exit
fullscreen.
This is implemented as an NSView rather than an NSWindow because the floating
chrome that appears in presentation mode should overlap the bubble.
Content-initiated fullscreen mode makes use of 'presentation mode' on the Mac:
the mode in which the UI is hidden, accessible by moving the cursor to the top
of the screen. On Snow Leopard, this mode is synonymous with fullscreen mode.
On Lion, however, fullscreen mode does not imply presentation mode: in
non-presentation fullscreen mode, the chrome is permanently shown. It is
possible to switch between presentation mode and fullscreen mode using the
presentation mode UI control.
When a tab initiates fullscreen mode on Lion, we enter presentation mode if not
in presentation mode already. When the user exits fullscreen mode using Chrome
UI (i.e. keyboard shortcuts, menu items, buttons, switching tabs, etc.) we
return the user to the mode they were in before the tab entered fullscreen.
BUG=14471
TEST=Enter fullscreen mode using webkitRequestFullScreen. You should see a bubble pop down from the top of the screen.
Need to test the Lion logic somehow, with no Lion trybots.
BUG=96883
Original review http://codereview.chromium.org/7890056/
TBR=thakis
Review URL: http://codereview.chromium.org/7920024
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@101624 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type)
{
struct hexline *hx;
u8 reset;
int ret,pos=0;
hx = kmalloc(sizeof(*hx), GFP_KERNEL);
if (!hx)
return -ENOMEM;
/* stop the CPU */
reset = 1;
if ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1)
err("could not stop the USB controller CPU.");
while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) {
deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk);
ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len);
if (ret != hx->len) {
err("error while transferring firmware (transferred size: %d, block size: %d)",
ret, hx->len);
ret = -EINVAL;
break;
}
}
if (ret < 0) {
err("firmware download failed at %d with %d",pos,ret);
kfree(hx);
return ret;
}
if (ret == 0) {
/* restart the CPU */
reset = 0;
if (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) {
err("could not restart the USB controller CPU.");
ret = -EINVAL;
}
} else
ret = -EIO;
kfree(hx);
return ret;
}
Commit Message: [media] dvb-usb-firmware: don't do DMA on stack
The buffer allocation for the firmware data was changed in
commit 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load")
but the same applies for the reset value.
Fixes: 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load")
Cc: [email protected]
Signed-off-by: Stefan Brüns <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: _warc_find_eoh(const char *buf, size_t bsz)
{
static const char _marker[] = "\r\n\r\n";
const char *hit = xmemmem(buf, bsz, _marker, sizeof(_marker) - 1U);
if (hit != NULL) {
hit += sizeof(_marker) - 1U;
}
return hit;
}
Commit Message: warc: consume data once read
The warc decoder only used read ahead, it wouldn't actually consume
data that had previously been printed. This means that if you specify
an invalid content length, it will just reprint the same data over
and over and over again until it hits the desired length.
This means that a WARC resource with e.g.
Content-Length: 666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666665
but only a few hundred bytes of data, causes a quasi-infinite loop.
Consume data in subsequent calls to _warc_read.
Found with an AFL + afl-rb + qsym setup.
CWE ID: CWE-415
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static bool can_do_async_pf(struct kvm_vcpu *vcpu)
{
if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
kvm_event_needs_reinjection(vcpu)))
return false;
return kvm_x86_ops->interrupt_allowed(vcpu);
}
Commit Message: nEPT: Nested INVEPT
If we let L1 use EPT, we should probably also support the INVEPT instruction.
In our current nested EPT implementation, when L1 changes its EPT table
for L2 (i.e., EPT12), L0 modifies the shadow EPT table (EPT02), and in
the course of this modification already calls INVEPT. But if last level
of shadow page is unsync not all L1's changes to EPT12 are intercepted,
which means roots need to be synced when L1 calls INVEPT. Global INVEPT
should not be different since roots are synced by kvm_mmu_load() each
time EPTP02 changes.
Reviewed-by: Xiao Guangrong <[email protected]>
Signed-off-by: Nadav Har'El <[email protected]>
Signed-off-by: Jun Nakajima <[email protected]>
Signed-off-by: Xinhao Xu <[email protected]>
Signed-off-by: Yang Zhang <[email protected]>
Signed-off-by: Gleb Natapov <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-20
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 udf_load_logicalvol(struct super_block *sb, sector_t block,
struct kernel_lb_addr *fileset)
{
struct logicalVolDesc *lvd;
int i, j, offset;
uint8_t type;
struct udf_sb_info *sbi = UDF_SB(sb);
struct genericPartitionMap *gpm;
uint16_t ident;
struct buffer_head *bh;
unsigned int table_len;
int ret = 0;
bh = udf_read_tagged(sb, block, block, &ident);
if (!bh)
return 1;
BUG_ON(ident != TAG_IDENT_LVD);
lvd = (struct logicalVolDesc *)bh->b_data;
table_len = le32_to_cpu(lvd->mapTableLength);
if (sizeof(*lvd) + table_len > sb->s_blocksize) {
udf_err(sb, "error loading logical volume descriptor: "
"Partition table too long (%u > %lu)\n", table_len,
sb->s_blocksize - sizeof(*lvd));
goto out_bh;
}
ret = udf_sb_alloc_partition_maps(sb, le32_to_cpu(lvd->numPartitionMaps));
if (ret)
goto out_bh;
for (i = 0, offset = 0;
i < sbi->s_partitions && offset < table_len;
i++, offset += gpm->partitionMapLength) {
struct udf_part_map *map = &sbi->s_partmaps[i];
gpm = (struct genericPartitionMap *)
&(lvd->partitionMaps[offset]);
type = gpm->partitionMapType;
if (type == 1) {
struct genericPartitionMap1 *gpm1 =
(struct genericPartitionMap1 *)gpm;
map->s_partition_type = UDF_TYPE1_MAP15;
map->s_volumeseqnum = le16_to_cpu(gpm1->volSeqNum);
map->s_partition_num = le16_to_cpu(gpm1->partitionNum);
map->s_partition_func = NULL;
} else if (type == 2) {
struct udfPartitionMap2 *upm2 =
(struct udfPartitionMap2 *)gpm;
if (!strncmp(upm2->partIdent.ident, UDF_ID_VIRTUAL,
strlen(UDF_ID_VIRTUAL))) {
u16 suf =
le16_to_cpu(((__le16 *)upm2->partIdent.
identSuffix)[0]);
if (suf < 0x0200) {
map->s_partition_type =
UDF_VIRTUAL_MAP15;
map->s_partition_func =
udf_get_pblock_virt15;
} else {
map->s_partition_type =
UDF_VIRTUAL_MAP20;
map->s_partition_func =
udf_get_pblock_virt20;
}
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_SPARABLE,
strlen(UDF_ID_SPARABLE))) {
uint32_t loc;
struct sparingTable *st;
struct sparablePartitionMap *spm =
(struct sparablePartitionMap *)gpm;
map->s_partition_type = UDF_SPARABLE_MAP15;
map->s_type_specific.s_sparing.s_packet_len =
le16_to_cpu(spm->packetLength);
for (j = 0; j < spm->numSparingTables; j++) {
struct buffer_head *bh2;
loc = le32_to_cpu(
spm->locSparingTable[j]);
bh2 = udf_read_tagged(sb, loc, loc,
&ident);
map->s_type_specific.s_sparing.
s_spar_map[j] = bh2;
if (bh2 == NULL)
continue;
st = (struct sparingTable *)bh2->b_data;
if (ident != 0 || strncmp(
st->sparingIdent.ident,
UDF_ID_SPARING,
strlen(UDF_ID_SPARING))) {
brelse(bh2);
map->s_type_specific.s_sparing.
s_spar_map[j] = NULL;
}
}
map->s_partition_func = udf_get_pblock_spar15;
} else if (!strncmp(upm2->partIdent.ident,
UDF_ID_METADATA,
strlen(UDF_ID_METADATA))) {
struct udf_meta_data *mdata =
&map->s_type_specific.s_metadata;
struct metadataPartitionMap *mdm =
(struct metadataPartitionMap *)
&(lvd->partitionMaps[offset]);
udf_debug("Parsing Logical vol part %d type %d id=%s\n",
i, type, UDF_ID_METADATA);
map->s_partition_type = UDF_METADATA_MAP25;
map->s_partition_func = udf_get_pblock_meta25;
mdata->s_meta_file_loc =
le32_to_cpu(mdm->metadataFileLoc);
mdata->s_mirror_file_loc =
le32_to_cpu(mdm->metadataMirrorFileLoc);
mdata->s_bitmap_file_loc =
le32_to_cpu(mdm->metadataBitmapFileLoc);
mdata->s_alloc_unit_size =
le32_to_cpu(mdm->allocUnitSize);
mdata->s_align_unit_size =
le16_to_cpu(mdm->alignUnitSize);
if (mdm->flags & 0x01)
mdata->s_flags |= MF_DUPLICATE_MD;
udf_debug("Metadata Ident suffix=0x%x\n",
le16_to_cpu(*(__le16 *)
mdm->partIdent.identSuffix));
udf_debug("Metadata part num=%d\n",
le16_to_cpu(mdm->partitionNum));
udf_debug("Metadata part alloc unit size=%d\n",
le32_to_cpu(mdm->allocUnitSize));
udf_debug("Metadata file loc=%d\n",
le32_to_cpu(mdm->metadataFileLoc));
udf_debug("Mirror file loc=%d\n",
le32_to_cpu(mdm->metadataMirrorFileLoc));
udf_debug("Bitmap file loc=%d\n",
le32_to_cpu(mdm->metadataBitmapFileLoc));
udf_debug("Flags: %d %d\n",
mdata->s_flags, mdm->flags);
} else {
udf_debug("Unknown ident: %s\n",
upm2->partIdent.ident);
continue;
}
map->s_volumeseqnum = le16_to_cpu(upm2->volSeqNum);
map->s_partition_num = le16_to_cpu(upm2->partitionNum);
}
udf_debug("Partition (%d:%d) type %d on volume %d\n",
i, map->s_partition_num, type, map->s_volumeseqnum);
}
if (fileset) {
struct long_ad *la = (struct long_ad *)&(lvd->logicalVolContentsUse[0]);
*fileset = lelb_to_cpu(la->extLocation);
udf_debug("FileSet found in LogicalVolDesc at block=%d, partition=%d\n",
fileset->logicalBlockNum,
fileset->partitionReferenceNum);
}
if (lvd->integritySeqExt.extLength)
udf_load_logicalvolint(sb, leea_to_cpu(lvd->integritySeqExt));
out_bh:
brelse(bh);
return ret;
}
Commit Message: udf: Fortify loading of sparing table
Add sanity checks when loading sparing table from disk to avoid accessing
unallocated memory or writing to it.
Signed-off-by: Jan Kara <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: void V8TestObject::ActivityLoggingGetterPerWorldBindingsLongAttributeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_TestObject_activityLoggingGetterPerWorldBindingsLongAttribute_Getter");
ScriptState* script_state = ScriptState::ForRelevantRealm(info);
V8PerContextData* context_data = script_state->PerContextData();
if (context_data && context_data->ActivityLogger()) {
context_data->ActivityLogger()->LogGetter("TestObject.activityLoggingGetterPerWorldBindingsLongAttribute");
}
test_object_v8_internal::ActivityLoggingGetterPerWorldBindingsLongAttributeAttributeGetter(info);
}
Commit Message: bindings: Support "attribute FrozenArray<T>?"
Adds a quick hack to support a case of "attribute FrozenArray<T>?".
Bug: 1028047
Change-Id: Ib3cecc4beb6bcc0fb0dbc667aca595454cc90c86
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1933866
Reviewed-by: Hitoshi Yoshida <[email protected]>
Commit-Queue: Yuki Shiino <[email protected]>
Cr-Commit-Position: refs/heads/master@{#718676}
CWE ID:
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: WM_SYMBOL midi *WildMidi_Open(const char *midifile) {
uint8_t *mididata = NULL;
uint32_t midisize = 0;
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midifile == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL filename)", 0);
return (NULL);
}
if ((mididata = (uint8_t *) _WM_BufferFile(midifile, &midisize)) == NULL) {
return (NULL);
}
if (memcmp(mididata,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(mididata, midisize);
} else if (memcmp(mididata, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(mididata, midisize);
} else if (memcmp(mididata, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(mididata, midisize);
} else if (memcmp(mididata, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(mididata, midisize);
} else {
ret = (void *) _WM_ParseNewMidi(mididata, midisize);
}
free(mididata);
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input
Fixes bug #178.
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: AudioParameters GetInputParametersOnDeviceThread(AudioManager* audio_manager,
const std::string& device_id) {
DCHECK(audio_manager->GetTaskRunner()->BelongsToCurrentThread());
if (!audio_manager->HasAudioInputDevices())
return AudioParameters();
return audio_manager->GetInputStreamParameters(device_id);
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=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
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
CWE ID:
Target: 1
Example 2:
Code: void DrawingBuffer::SetBufferClearNeeded(bool flag) {
if (preserve_drawing_buffer_ == kDiscard) {
buffer_clear_needed_ = flag;
} else {
DCHECK(!buffer_clear_needed_);
}
}
Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later.
BUG=740603
TEST=new conformance test
[email protected],[email protected]
Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4
Reviewed-on: https://chromium-review.googlesource.com/570840
Reviewed-by: Antoine Labour <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Commit-Queue: Zhenyao Mo <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486518}
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: juniper_monitor_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, register const u_char *p)
{
struct juniper_l2info_t l2info;
struct juniper_monitor_header {
uint8_t pkt_type;
uint8_t padding;
uint8_t iif[2];
uint8_t service_id[4];
};
const struct juniper_monitor_header *mh;
l2info.pictype = DLT_JUNIPER_MONITOR;
if (juniper_parse_header(ndo, p, h, &l2info) == 0)
return l2info.header_len;
p+=l2info.header_len;
mh = (const struct juniper_monitor_header *)p;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ",
EXTRACT_32BITS(&mh->service_id),
EXTRACT_16BITS(&mh->iif),
mh->pkt_type));
/* no proto field - lets guess by first byte of IP header*/
ip_heuristic_guess (ndo, p, l2info.length);
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
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 fe_netjoin_deinit(void)
{
while (joinservers != NULL)
netjoin_server_remove(joinservers->data);
if (join_tag != -1) {
g_source_remove(join_tag);
signal_remove("print starting", (SIGNAL_FUNC) sig_print_starting);
}
signal_remove("setup changed", (SIGNAL_FUNC) read_settings);
signal_remove("message quit", (SIGNAL_FUNC) msg_quit);
signal_remove("message join", (SIGNAL_FUNC) msg_join);
signal_remove("message irc mode", (SIGNAL_FUNC) msg_mode);
}
Commit Message: Merge branch 'netjoin-timeout' into 'master'
fe-netjoin: remove irc servers on "server disconnected" signal
Closes #7
See merge request !10
CWE ID: CWE-416
Target: 1
Example 2:
Code: void PreconnectManager::PreconnectUrl(
const GURL& url,
int num_sockets,
bool allow_credentials,
const net::NetworkIsolationKey& network_isolation_key) const {
DCHECK(url.GetOrigin() == url);
DCHECK(url.SchemeIsHTTPOrHTTPS());
if (observer_)
observer_->OnPreconnectUrl(url, num_sockets, allow_credentials);
auto* network_context = GetNetworkContext();
if (!network_context)
return;
network_context->PreconnectSockets(num_sockets, url, allow_credentials,
network_isolation_key);
}
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: static const char *check_secret(int module, const char *user, const char *group,
const char *challenge, const char *pass)
{
char line[1024];
char pass2[MAX_DIGEST_LEN*2];
const char *fname = lp_secrets_file(module);
STRUCT_STAT st;
int fd, ok = 1;
int user_len = strlen(user);
int group_len = group ? strlen(group) : 0;
char *err;
if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0)
return "no secrets file";
if (do_fstat(fd, &st) == -1) {
rsyserr(FLOG, errno, "fstat(%s)", fname);
ok = 0;
} else if (lp_strict_modes(module)) {
rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n");
ok = 0;
} else if (MY_UID() == 0 && st.st_uid != 0) {
rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n");
ok = 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: bool WebRtcAudioRenderer::Initialize(WebRtcAudioRendererSource* source) {
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, UNINITIALIZED);
DCHECK(source);
DCHECK(!sink_);
DCHECK(!source_);
sink_ = AudioDeviceFactory::NewOutputDevice();
DCHECK(sink_);
int sample_rate = GetAudioOutputSampleRate();
DVLOG(1) << "Audio output hardware sample rate: " << sample_rate;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputSampleRate",
sample_rate, media::kUnexpectedAudioSampleRate);
if (std::find(&kValidOutputRates[0],
&kValidOutputRates[0] + arraysize(kValidOutputRates),
sample_rate) ==
&kValidOutputRates[arraysize(kValidOutputRates)]) {
DLOG(ERROR) << sample_rate << " is not a supported output rate.";
return false;
}
media::ChannelLayout channel_layout = media::CHANNEL_LAYOUT_STEREO;
int buffer_size = 0;
#if defined(OS_WIN)
channel_layout = media::CHANNEL_LAYOUT_STEREO;
if (sample_rate == 96000 || sample_rate == 48000) {
buffer_size = (sample_rate / 100);
} else {
buffer_size = 2 * 440;
}
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
buffer_size = 3 * buffer_size;
DLOG(WARNING) << "Extending the output buffer size by a factor of three "
<< "since Windows XP has been detected.";
}
#elif defined(OS_MACOSX)
channel_layout = media::CHANNEL_LAYOUT_MONO;
if (sample_rate == 48000) {
buffer_size = 480;
} else {
buffer_size = 440;
}
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
channel_layout = media::CHANNEL_LAYOUT_MONO;
buffer_size = 480;
#else
DLOG(ERROR) << "Unsupported platform";
return false;
#endif
params_.Reset(media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout,
sample_rate, 16, buffer_size);
buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]);
source_ = source;
source->SetRenderFormat(params_);
sink_->Initialize(params_, this);
sink_->SetSourceRenderView(source_render_view_id_);
sink_->Start();
state_ = PAUSED;
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputChannelLayout",
channel_layout, media::CHANNEL_LAYOUT_MAX);
UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioOutputFramesPerBuffer",
buffer_size, kUnexpectedAudioBufferSize);
AddHistogramFramesPerBuffer(buffer_size);
return true;
}
Commit Message: Avoids crash in WebRTC audio clients for 96kHz render rate on Mac OSX.
TBR=xians
BUG=166523
TEST=Misc set of WebRTC audio clients on Mac.
Review URL: https://codereview.chromium.org/11773017
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@175323 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119
Target: 1
Example 2:
Code: MockNetworkQualityProvider& mock_network_quality_provider() {
return mock_network_quality_provider_;
}
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: static inline int mount_entry_on_generic(struct mntent *mntent,
const char* path)
{
unsigned long mntflags;
char *mntdata;
int ret;
bool optional = hasmntopt(mntent, "optional") != NULL;
ret = mount_entry_create_dir_file(mntent, path);
if (ret < 0)
return optional ? 0 : -1;
cull_mntent_opt(mntent);
if (parse_mntopts(mntent->mnt_opts, &mntflags, &mntdata) < 0) {
free(mntdata);
return -1;
}
ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type,
mntflags, mntdata, optional);
free(mntdata);
return ret;
}
Commit Message: CVE-2015-1335: Protect container mounts against symlinks
When a container starts up, lxc sets up the container's inital fstree
by doing a bunch of mounting, guided by the container configuration
file. The container config is owned by the admin or user on the host,
so we do not try to guard against bad entries. However, since the
mount target is in the container, it's possible that the container admin
could divert the mount with symbolic links. This could bypass proper
container startup (i.e. confinement of a root-owned container by the
restrictive apparmor policy, by diverting the required write to
/proc/self/attr/current), or bypass the (path-based) apparmor policy
by diverting, say, /proc to /mnt in the container.
To prevent this,
1. do not allow mounts to paths containing symbolic links
2. do not allow bind mounts from relative paths containing symbolic
links.
Details:
Define safe_mount which ensures that the container has not inserted any
symbolic links into any mount targets for mounts to be done during
container setup.
The host's mount path may contain symbolic links. As it is under the
control of the administrator, that's ok. So safe_mount begins the check
for symbolic links after the rootfs->mount, by opening that directory.
It opens each directory along the path using openat() relative to the
parent directory using O_NOFOLLOW. When the target is reached, it
mounts onto /proc/self/fd/<targetfd>.
Use safe_mount() in mount_entry(), when mounting container proc,
and when needed. In particular, safe_mount() need not be used in
any case where:
1. the mount is done in the container's namespace
2. the mount is for the container's rootfs
3. the mount is relative to a tmpfs or proc/sysfs which we have
just safe_mount()ed ourselves
Since we were using proc/net as a temporary placeholder for /proc/sys/net
during container startup, and proc/net is a symbolic link, use proc/tty
instead.
Update the lxc.container.conf manpage with details about the new
restrictions.
Finally, add a testcase to test some symbolic link possibilities.
Reported-by: Roman Fiedler
Signed-off-by: Serge Hallyn <[email protected]>
Acked-by: Stéphane Graber <[email protected]>
CWE ID: CWE-59
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: tBTA_AV_EVT bta_av_proc_meta_cmd(tAVRC_RESPONSE* p_rc_rsp,
tBTA_AV_RC_MSG* p_msg, uint8_t* p_ctype) {
tBTA_AV_EVT evt = BTA_AV_META_MSG_EVT;
uint8_t u8, pdu, *p;
uint16_t u16;
tAVRC_MSG_VENDOR* p_vendor = &p_msg->msg.vendor;
pdu = *(p_vendor->p_vendor_data);
p_rc_rsp->pdu = pdu;
*p_ctype = AVRC_RSP_REJ;
/* Check to ansure a valid minimum meta data length */
if ((AVRC_MIN_META_CMD_LEN + p_vendor->vendor_len) > AVRC_META_CMD_BUF_SIZE) {
/* reject it */
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
APPL_TRACE_ERROR("%s: Invalid meta-command length: %d", __func__,
p_vendor->vendor_len);
return 0;
}
/* Metadata messages only use PANEL sub-unit type */
if (p_vendor->hdr.subunit_type != AVRC_SUB_PANEL) {
APPL_TRACE_DEBUG("%s: SUBUNIT must be PANEL", __func__);
/* reject it */
evt = 0;
p_vendor->hdr.ctype = AVRC_RSP_NOT_IMPL;
p_vendor->vendor_len = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_PARAM;
} else if (!AVRC_IsValidAvcType(pdu, p_vendor->hdr.ctype)) {
APPL_TRACE_DEBUG("%s: Invalid pdu/ctype: 0x%x, %d", __func__, pdu,
p_vendor->hdr.ctype);
/* reject invalid message without reporting to app */
evt = 0;
p_rc_rsp->rsp.status = AVRC_STS_BAD_CMD;
} else {
switch (pdu) {
case AVRC_PDU_GET_CAPABILITIES:
/* process GetCapabilities command without reporting the event to app */
evt = 0;
u8 = *(p_vendor->p_vendor_data + 4);
p = p_vendor->p_vendor_data + 2;
p_rc_rsp->get_caps.capability_id = u8;
BE_STREAM_TO_UINT16(u16, p);
if ((u16 != 1) || (p_vendor->vendor_len != 5)) {
p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR;
} else {
p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR;
if (u8 == AVRC_CAP_COMPANY_ID) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_co_ids;
memcpy(p_rc_rsp->get_caps.param.company_id,
p_bta_av_cfg->p_meta_co_ids,
(p_bta_av_cfg->num_co_ids << 2));
} else if (u8 == AVRC_CAP_EVENTS_SUPPORTED) {
*p_ctype = AVRC_RSP_IMPL_STBL;
p_rc_rsp->get_caps.count = p_bta_av_cfg->num_evt_ids;
memcpy(p_rc_rsp->get_caps.param.event_id,
p_bta_av_cfg->p_meta_evt_ids, p_bta_av_cfg->num_evt_ids);
} else {
APPL_TRACE_DEBUG("%s: Invalid capability ID: 0x%x", __func__, u8);
/* reject - unknown capability ID */
p_rc_rsp->get_caps.status = AVRC_STS_BAD_PARAM;
}
}
break;
case AVRC_PDU_REGISTER_NOTIFICATION:
/* make sure the event_id is implemented */
p_rc_rsp->rsp.status = bta_av_chk_notif_evt_id(p_vendor);
if (p_rc_rsp->rsp.status != BTA_AV_STS_NO_RSP) evt = 0;
break;
}
}
return evt;
}
Commit Message: Check packet length in bta_av_proc_meta_cmd
Bug: 111893951
Test: manual - connect A2DP
Change-Id: Ibbf347863dfd29ea3385312e9dde1082bc90d2f3
(cherry picked from commit ed51887f921263219bcd2fbf6650ead5ec8d334e)
CWE ID: CWE-125
Target: 1
Example 2:
Code: void http_return_srv_error(struct stream *s, struct stream_interface *si)
{
int err_type = si->err_type;
/* set s->txn->status for http_error_message(s) */
s->txn->status = 503;
if (err_type & SI_ET_QUEUE_ABRT)
http_server_error(s, si, SF_ERR_CLICL, SF_FINST_Q,
http_error_message(s));
else if (err_type & SI_ET_CONN_ABRT)
http_server_error(s, si, SF_ERR_CLICL, SF_FINST_C,
(s->txn->flags & TX_NOT_FIRST) ? NULL :
http_error_message(s));
else if (err_type & SI_ET_QUEUE_TO)
http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_Q,
http_error_message(s));
else if (err_type & SI_ET_QUEUE_ERR)
http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_Q,
http_error_message(s));
else if (err_type & SI_ET_CONN_TO)
http_server_error(s, si, SF_ERR_SRVTO, SF_FINST_C,
(s->txn->flags & TX_NOT_FIRST) ? NULL :
http_error_message(s));
else if (err_type & SI_ET_CONN_ERR)
http_server_error(s, si, SF_ERR_SRVCL, SF_FINST_C,
(s->flags & SF_SRV_REUSED) ? NULL :
http_error_message(s));
else if (err_type & SI_ET_CONN_RES)
http_server_error(s, si, SF_ERR_RESOURCE, SF_FINST_C,
(s->txn->flags & TX_NOT_FIRST) ? NULL :
http_error_message(s));
else { /* SI_ET_CONN_OTHER and others */
s->txn->status = 500;
http_server_error(s, si, SF_ERR_INTERNAL, SF_FINST_C,
http_error_message(s));
}
}
Commit Message:
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: queryin(char *buf)
{
QPRS_STATE state;
int32 i;
ltxtquery *query;
int32 commonlen;
ITEM *ptr;
NODE *tmp;
int32 pos = 0;
#ifdef BS_DEBUG
char pbuf[16384],
*cur;
#endif
/* init state */
state.buf = buf;
state.state = WAITOPERAND;
state.count = 0;
state.num = 0;
state.str = NULL;
/* init list of operand */
state.sumlen = 0;
state.lenop = 64;
state.curop = state.op = (char *) palloc(state.lenop);
*(state.curop) = '\0';
/* parse query & make polish notation (postfix, but in reverse order) */
makepol(&state);
if (!state.num)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("syntax error"),
errdetail("Empty query.")));
/* make finish struct */
commonlen = COMPUTESIZE(state.num, state.sumlen);
query = (ltxtquery *) palloc(commonlen);
SET_VARSIZE(query, commonlen);
query->size = state.num;
ptr = GETQUERY(query);
/* set item in polish notation */
for (i = 0; i < state.num; i++)
{
ptr[i].type = state.str->type;
ptr[i].val = state.str->val;
ptr[i].distance = state.str->distance;
ptr[i].length = state.str->length;
ptr[i].flag = state.str->flag;
tmp = state.str->next;
pfree(state.str);
state.str = tmp;
}
/* set user friendly-operand view */
memcpy((void *) GETOPERAND(query), (void *) state.op, state.sumlen);
pfree(state.op);
/* set left operand's position for every operator */
pos = 0;
findoprnd(ptr, &pos);
return query;
}
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: | 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 ih264d_rest_of_residual_cav_chroma_dc_block(UWORD32 u4_total_coeff_trail_one,
dec_bit_stream_t *ps_bitstrm)
{
UWORD32 u4_total_zeroes;
WORD16 i;
UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer;
UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst;
UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF;
UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16;
WORD16 i2_level_arr[4];
tu_sblk4x4_coeff_data_t *ps_tu_4x4;
WORD16 *pi2_coeff_data;
dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle;
ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data;
ps_tu_4x4->u2_sig_coeff_map = 0;
pi2_coeff_data = &ps_tu_4x4->ai2_level[0];
i = u4_total_coeff - 1;
if(u4_trailing_ones)
{
/*********************************************************************/
/* Decode Trailing Ones */
/* read the sign of T1's and put them in level array */
/*********************************************************************/
UWORD32 u4_signs, u4_cnt = u4_trailing_ones;
WORD16 (*ppi2_trlone_lkup)[3] =
(WORD16 (*)[3])gai2_ih264d_trailing_one_level;
WORD16 *pi2_trlone_lkup;
GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt);
pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs];
while(u4_cnt--)
i2_level_arr[i--] = *pi2_trlone_lkup++;
}
/****************************************************************/
/* Decoding Levels Begins */
/****************************************************************/
if(i >= 0)
{
/****************************************************************/
/* First level is decoded outside the loop as it has lot of */
/* special cases. */
/****************************************************************/
UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size;
UWORD16 u2_lev_code, u2_abs_value;
UWORD32 u4_lev_prefix;
/***************************************************************/
/* u4_suffix_len = 0, Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
/*********************************************************/
/* Special decoding case when trailing ones are 3 */
/*********************************************************/
u2_lev_code = MIN(15, u4_lev_prefix);
u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2);
if(14 == u4_lev_prefix)
u4_lev_suffix_size = 4;
else if(15 <= u4_lev_prefix)
{
u2_lev_code += 15;
u4_lev_suffix_size = u4_lev_prefix - 3;
}
else
u4_lev_suffix_size = 0;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
if(u4_lev_suffix_size)
{
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code += u4_lev_suffix;
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
u4_suffix_len = (u2_abs_value > 3) ? 2 : 1;
/*********************************************************/
/* Now loop over the remaining levels */
/*********************************************************/
while(i >= 0)
{
/***************************************************************/
/* Find leading zeros in next 32 bits */
/***************************************************************/
FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset,
pu4_bitstrm_buf);
u4_lev_suffix_size =
(15 <= u4_lev_prefix) ?
(u4_lev_prefix - 3) : u4_suffix_len;
/*********************************************************/
/* Compute level code using prefix and suffix */
/*********************************************************/
GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf,
u4_lev_suffix_size);
u2_lev_code = (MIN(u4_lev_prefix,15) << u4_suffix_len)
+ u4_lev_suffix;
if(16 <= u4_lev_prefix)
{
u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096);
}
u2_abs_value = (u2_lev_code + 2) >> 1;
/*********************************************************/
/* If Level code is odd, level is negative else positive */
/*********************************************************/
i2_level_arr[i--] =
(u2_lev_code & 1) ? -u2_abs_value : u2_abs_value;
/*********************************************************/
/* Increment suffix length if required */
/*********************************************************/
u4_suffix_len += (u2_abs_value > (3 << (u4_suffix_len - 1)));
}
/****************************************************************/
/* Decoding Levels Ends */
/****************************************************************/
}
if(u4_total_coeff < 4)
{
UWORD32 u4_max_ldz = (4 - u4_total_coeff);
FIND_ONE_IN_STREAM_LEN(u4_total_zeroes, u4_bitstream_offset,
pu4_bitstrm_buf, u4_max_ldz);
}
else
u4_total_zeroes = 0;
/**************************************************************/
/* Decode the runs and form the coefficient buffer */
/**************************************************************/
{
const UWORD8 *pu1_table_runbefore;
UWORD32 u4_run;
UWORD32 u4_scan_pos = (u4_total_coeff + u4_total_zeroes - 1);
UWORD32 u4_zeroes_left = u4_total_zeroes;
i = u4_total_coeff - 1;
/**************************************************************/
/* Decoding Runs for 0 < zeros left <=6 */
/**************************************************************/
pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before;
while(u4_zeroes_left && i)
{
UWORD32 u4_code;
NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3);
u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)];
u4_run = u4_code >> 2;
FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03));
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_zeroes_left -= u4_run;
u4_scan_pos -= (u4_run + 1);
}
/**************************************************************/
/* Decoding Runs End */
/**************************************************************/
/**************************************************************/
/* Copy the remaining coefficients */
/**************************************************************/
while(i >= 0)
{
SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos);
*pi2_coeff_data++ = i2_level_arr[i--];
u4_scan_pos--;
}
}
{
WORD32 offset;
offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4;
offset = ALIGN4(offset);
ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset);
}
ps_bitstrm->u4_ofst = u4_bitstream_offset;
}
Commit Message: Decoder: Fix stack underflow in CAVLC 4x4 parse functions
Bug: 26399350
Change-Id: Id768751672a7b093ab6e53d4fc0b3188d470920e
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int tg3_get_rxfh_indir(struct net_device *dev, u32 *indir)
{
struct tg3 *tp = netdev_priv(dev);
int i;
for (i = 0; i < TG3_RSS_INDIR_TBL_SIZE; i++)
indir[i] = tp->rss_ind_tbl[i];
return 0;
}
Commit Message: tg3: fix length overflow in VPD firmware parsing
Commit 184b89044fb6e2a74611dafa69b1dce0d98612c6 ("tg3: Use VPD fw version
when present") introduced VPD parsing that contained a potential length
overflow.
Limit the hardware's reported firmware string length (max 255 bytes) to
stay inside the driver's firmware string length (32 bytes). On overflow,
truncate the formatted firmware string instead of potentially overwriting
portions of the tg3 struct.
http://cansecwest.com/slides/2013/PrivateCore%20CSW%202013.pdf
Signed-off-by: Kees Cook <[email protected]>
Reported-by: Oded Horovitz <[email protected]>
Reported-by: Brad Spengler <[email protected]>
Cc: [email protected]
Cc: Matt Carlson <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void op_addXopCC(MCInst *MI, int v)
{
if (MI->csh->detail) {
MI->flat_insn->detail->x86.xop_cc = v;
}
}
Commit Message: x86: fast path checking for X86_insn_reg_intel()
CWE ID: CWE-125
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static unsigned int help(struct sk_buff *skb,
enum ip_conntrack_info ctinfo,
unsigned int protoff,
unsigned int matchoff,
unsigned int matchlen,
struct nf_conntrack_expect *exp)
{
char buffer[sizeof("4294967296 65635")];
u_int16_t port;
unsigned int ret;
/* Reply comes from server. */
exp->saved_proto.tcp.port = exp->tuple.dst.u.tcp.port;
exp->dir = IP_CT_DIR_REPLY;
exp->expectfn = nf_nat_follow_master;
/* Try to get same port: if not, try to change it. */
for (port = ntohs(exp->saved_proto.tcp.port); port != 0; port++) {
int ret;
exp->tuple.dst.u.tcp.port = htons(port);
ret = nf_ct_expect_related(exp);
if (ret == 0)
break;
else if (ret != -EBUSY) {
port = 0;
break;
}
}
if (port == 0) {
nf_ct_helper_log(skb, exp->master, "all ports in use");
return NF_DROP;
}
ret = nf_nat_mangle_tcp_packet(skb, exp->master, ctinfo,
protoff, matchoff, matchlen, buffer,
strlen(buffer));
if (ret != NF_ACCEPT) {
nf_ct_helper_log(skb, exp->master, "cannot mangle packet");
nf_ct_unexpect_related(exp);
}
return ret;
}
Commit Message: netfilter: nf_nat: fix access to uninitialized buffer in IRC NAT helper
Commit 5901b6be885e attempted to introduce IPv6 support into
IRC NAT helper. By doing so, the following code seemed to be removed
by accident:
ip = ntohl(exp->master->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3.ip);
sprintf(buffer, "%u %u", ip, port);
pr_debug("nf_nat_irc: inserting '%s' == %pI4, port %u\n", buffer, &ip, port);
This leads to the fact that buffer[] was left uninitialized and
contained some stack value. When we call nf_nat_mangle_tcp_packet(),
we call strlen(buffer) on excatly this uninitialized buffer. If we
are unlucky and the skb has enough tailroom, we overwrite resp. leak
contents with values that sit on our stack into the packet and send
that out to the receiver.
Since the rather informal DCC spec [1] does not seem to specify
IPv6 support right now, we log such occurences so that admins can
act accordingly, and drop the packet. I've looked into XChat source,
and IPv6 is not supported there: addresses are in u32 and print
via %u format string.
Therefore, restore old behaviour as in IPv4, use snprintf(). The
IRC helper does not support IPv6 by now. By this, we can safely use
strlen(buffer) in nf_nat_mangle_tcp_packet() and prevent a buffer
overflow. Also simplify some code as we now have ct variable anyway.
[1] http://www.irchelp.org/irchelp/rfc/ctcpspec.html
Fixes: 5901b6be885e ("netfilter: nf_nat: support IPv6 in IRC NAT helper")
Signed-off-by: Daniel Borkmann <[email protected]>
Cc: Harald Welte <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: LayoutUnit RenderBlock::availableLogicalWidth() const
{
if (hasColumns())
return desiredColumnWidth();
return RenderBox::availableLogicalWidth();
}
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: static int filter_frame(AVFilterLink *inlink, AVFrame *in)
{
unsigned x, y;
AVFilterContext *ctx = inlink->dst;
VignetteContext *s = ctx->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *out;
out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!out) {
av_frame_free(&in);
return AVERROR(ENOMEM);
}
av_frame_copy_props(out, in);
if (s->eval_mode == EVAL_MODE_FRAME)
update_context(s, inlink, in);
if (s->desc->flags & AV_PIX_FMT_FLAG_RGB) {
uint8_t *dst = out->data[0];
const uint8_t *src = in ->data[0];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[0];
const int src_linesize = in ->linesize[0];
const int fmap_linesize = s->fmap_linesize;
for (y = 0; y < inlink->h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < inlink->w; x++, dstp += 3, srcp += 3) {
const float f = fmap[x];
dstp[0] = av_clip_uint8(srcp[0] * f + get_dither_value(s));
dstp[1] = av_clip_uint8(srcp[1] * f + get_dither_value(s));
dstp[2] = av_clip_uint8(srcp[2] * f + get_dither_value(s));
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize;
}
} else {
int plane;
for (plane = 0; plane < 4 && in->data[plane]; plane++) {
uint8_t *dst = out->data[plane];
const uint8_t *src = in ->data[plane];
const float *fmap = s->fmap;
const int dst_linesize = out->linesize[plane];
const int src_linesize = in ->linesize[plane];
const int fmap_linesize = s->fmap_linesize;
const int chroma = plane == 1 || plane == 2;
const int hsub = chroma ? s->desc->log2_chroma_w : 0;
const int vsub = chroma ? s->desc->log2_chroma_h : 0;
const int w = FF_CEIL_RSHIFT(inlink->w, hsub);
const int h = FF_CEIL_RSHIFT(inlink->h, vsub);
for (y = 0; y < h; y++) {
uint8_t *dstp = dst;
const uint8_t *srcp = src;
for (x = 0; x < w; x++) {
const double dv = get_dither_value(s);
if (chroma) *dstp++ = av_clip_uint8(fmap[x << hsub] * (*srcp++ - 127) + 127 + dv);
else *dstp++ = av_clip_uint8(fmap[x ] * *srcp++ + dv);
}
dst += dst_linesize;
src += src_linesize;
fmap += fmap_linesize << vsub;
}
}
}
return ff_filter_frame(outlink, out);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[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 CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
} else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
}
Commit Message: Fixed possible foveon buffer overrun (Secunia SA750000)
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void delayed_calls_add(int type, gpointer data)
{
DelayedCall *dcall = NPW_MemNew(DelayedCall, 1);
if (dcall == NULL)
return;
dcall->type = type;
dcall->data = data;
g_delayed_calls = g_list_append(g_delayed_calls, dcall);
if (g_delayed_calls_id == 0)
g_delayed_calls_id = g_idle_add_full(G_PRIORITY_LOW,
delayed_calls_process_cb, NULL, NULL);
}
Commit Message: Support all the new variables added
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 sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415
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 mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
mbedtls_md_type_t md_alg )
{
int ret;
mbedtls_hmac_drbg_context rng_ctx;
unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
size_t grp_len = ( grp->nbits + 7 ) / 8;
const mbedtls_md_info_t *md_info;
mbedtls_mpi h;
if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
mbedtls_mpi_init( &h );
mbedtls_hmac_drbg_init( &rng_ctx );
/* Use private key and message hash (reduced) to initialize HMAC_DRBG */
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );
MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );
mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len );
ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
mbedtls_hmac_drbg_random, &rng_ctx );
cleanup:
mbedtls_hmac_drbg_free( &rng_ctx );
mbedtls_mpi_free( &h );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200
Target: 1
Example 2:
Code: pch_char (lin line)
{
return p_Char[line];
}
Commit Message:
CWE ID: CWE-78
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: get_chainname_rulenum(const struct ip6t_entry *s, const struct ip6t_entry *e,
const char *hookname, const char **chainname,
const char **comment, unsigned int *rulenum)
{
const struct xt_standard_target *t = (void *)ip6t_get_target_c(s);
if (strcmp(t->target.u.kernel.target->name, XT_ERROR_TARGET) == 0) {
/* Head of user chain: ERROR target with chainname */
*chainname = t->target.data;
(*rulenum) = 0;
} else if (s == e) {
(*rulenum)++;
if (s->target_offset == sizeof(struct ip6t_entry) &&
strcmp(t->target.u.kernel.target->name,
XT_STANDARD_TARGET) == 0 &&
t->verdict < 0 &&
unconditional(&s->ipv6)) {
/* Tail of chains: STANDARD target (return/policy) */
*comment = *chainname == hookname
? comments[NF_IP6_TRACE_COMMENT_POLICY]
: comments[NF_IP6_TRACE_COMMENT_RETURN];
}
return 1;
} else
(*rulenum)++;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static bool ndp_msg_check_valid(struct ndp_msg *msg)
{
size_t len = ndp_msg_payload_len(msg);
enum ndp_msg_type msg_type = ndp_msg_type(msg);
if (len < ndp_msg_type_info(msg_type)->raw_struct_size)
return false;
return true;
}
Commit Message: libndb: reject redirect and router advertisements from non-link-local
RFC4861 suggests that these messages should only originate from
link-local addresses in 6.1.2 (RA) and 8.1. (redirect):
Mitigates CVE-2016-3698.
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284
Target: 1
Example 2:
Code: static int nfs_idmap_prepare_message(char *desc, struct idmap *idmap,
struct idmap_msg *im,
struct rpc_pipe_msg *msg)
{
substring_t substr;
int token, ret;
im->im_type = IDMAP_TYPE_GROUP;
token = match_token(desc, nfs_idmap_tokens, &substr);
switch (token) {
case Opt_find_uid:
im->im_type = IDMAP_TYPE_USER;
case Opt_find_gid:
im->im_conv = IDMAP_CONV_NAMETOID;
ret = match_strlcpy(im->im_name, &substr, IDMAP_NAMESZ);
break;
case Opt_find_user:
im->im_type = IDMAP_TYPE_USER;
case Opt_find_group:
im->im_conv = IDMAP_CONV_IDTONAME;
ret = match_int(&substr, &im->im_id);
break;
default:
ret = -EINVAL;
goto out;
}
msg->data = im;
msg->len = sizeof(struct idmap_msg);
out:
return ret;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476
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 Equalizer_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
int32_t param2;
char *name;
switch (param) {
case EQ_PARAM_NUM_BANDS:
case EQ_PARAM_CUR_PRESET:
case EQ_PARAM_GET_NUM_OF_PRESETS:
case EQ_PARAM_BAND_LEVEL:
case EQ_PARAM_GET_BAND:
if (*pValueSize < sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case EQ_PARAM_LEVEL_RANGE:
if (*pValueSize < 2 * sizeof(int16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int16_t);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
if (*pValueSize < 2 * sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 3 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = 2 * sizeof(int32_t);
break;
case EQ_PARAM_CENTER_FREQ:
if (*pValueSize < sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 5 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
case EQ_PARAM_GET_PRESET_NAME:
break;
case EQ_PARAM_PROPERTIES:
if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) {
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param) {
case EQ_PARAM_NUM_BANDS:
*(uint16_t *)pValue = (uint16_t)FIVEBAND_NUMBANDS;
break;
case EQ_PARAM_LEVEL_RANGE:
*(int16_t *)pValue = -1500;
*((int16_t *)pValue + 1) = 1500;
break;
case EQ_PARAM_BAND_LEVEL:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32438598");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d", param2);
}
break;
}
*(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2);
break;
case EQ_PARAM_CENTER_FREQ:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32436341");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d", param2);
}
break;
}
*(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2);
break;
case EQ_PARAM_BAND_FREQ_RANGE:
param2 = *pParamTemp;
if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
if (param2 < 0) {
android_errorWriteLog(0x534e4554, "32247948");
ALOGW("\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d", param2);
}
break;
}
EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1));
break;
case EQ_PARAM_GET_BAND:
param2 = *pParamTemp;
*(uint16_t *)pValue = (uint16_t)EqualizerGetBand(pContext, param2);
break;
case EQ_PARAM_CUR_PRESET:
*(uint16_t *)pValue = (uint16_t)EqualizerGetPreset(pContext);
break;
case EQ_PARAM_GET_NUM_OF_PRESETS:
*(uint16_t *)pValue = (uint16_t)EqualizerGetNumPresets();
break;
case EQ_PARAM_GET_PRESET_NAME:
param2 = *pParamTemp;
if (param2 >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
name = (char *)pValue;
strncpy(name, EqualizerGetPresetName(param2), *pValueSize - 1);
name[*pValueSize - 1] = 0;
*pValueSize = strlen(name) + 1;
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
ALOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES");
p[0] = (int16_t)EqualizerGetPreset(pContext);
p[1] = (int16_t)FIVEBAND_NUMBANDS;
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
p[2 + i] = (int16_t)EqualizerGetBandLevel(pContext, i);
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_getParameter */
int Equalizer_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int32_t preset;
int32_t band;
int32_t level;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param) {
case EQ_PARAM_CUR_PRESET:
preset = (int32_t)(*(uint16_t *)pValue);
if ((preset >= EqualizerGetNumPresets())||(preset < 0)) {
status = -EINVAL;
break;
}
EqualizerSetPreset(pContext, preset);
break;
case EQ_PARAM_BAND_LEVEL:
band = *pParamTemp;
level = (int32_t)(*(int16_t *)pValue);
if (band >= FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
EqualizerSetBandLevel(pContext, band, level);
break;
case EQ_PARAM_PROPERTIES: {
int16_t *p = (int16_t *)pValue;
if ((int)p[0] >= EqualizerGetNumPresets()) {
status = -EINVAL;
break;
}
if (p[0] >= 0) {
EqualizerSetPreset(pContext, (int)p[0]);
} else {
if ((int)p[1] != FIVEBAND_NUMBANDS) {
status = -EINVAL;
break;
}
for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
EqualizerSetBandLevel(pContext, i, (int)p[2 + i]);
}
}
} break;
default:
ALOGV("\tLVM_ERROR : Equalizer_setParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Equalizer_setParameter */
int Volume_getParameter(EffectContext *pContext,
void *pParam,
uint32_t *pValueSize,
void *pValue){
int status = 0;
int bMute = 0;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;;
char *name;
switch (param){
case VOLUME_PARAM_LEVEL:
case VOLUME_PARAM_MAXLEVEL:
case VOLUME_PARAM_STEREOPOSITION:
if (*pValueSize != sizeof(int16_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 1 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int16_t);
break;
case VOLUME_PARAM_MUTE:
case VOLUME_PARAM_ENABLESTEREOPOSITION:
if (*pValueSize < sizeof(int32_t)){
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid pValueSize 2 %d", *pValueSize);
return -EINVAL;
}
*pValueSize = sizeof(int32_t);
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter unknown param %d", param);
return -EINVAL;
}
switch (param){
case VOLUME_PARAM_LEVEL:
status = VolumeGetVolumeLevel(pContext, (int16_t *)(pValue));
break;
case VOLUME_PARAM_MAXLEVEL:
*(int16_t *)pValue = 0;
break;
case VOLUME_PARAM_STEREOPOSITION:
VolumeGetStereoPosition(pContext, (int16_t *)pValue);
break;
case VOLUME_PARAM_MUTE:
status = VolumeGetMute(pContext, (uint32_t *)pValue);
ALOGV("\tVolume_getParameter() VOLUME_PARAM_MUTE Value is %d",
*(uint32_t *)pValue);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
*(int32_t *)pValue = pContext->pBundledContext->bStereoPositionEnabled;
break;
default:
ALOGV("\tLVM_ERROR : Volume_getParameter() invalid param %d", param);
status = -EINVAL;
break;
}
return status;
} /* end Volume_getParameter */
int Volume_setParameter (EffectContext *pContext, void *pParam, void *pValue){
int status = 0;
int16_t level;
int16_t position;
uint32_t mute;
uint32_t positionEnabled;
int32_t *pParamTemp = (int32_t *)pParam;
int32_t param = *pParamTemp++;
switch (param){
case VOLUME_PARAM_LEVEL:
level = *(int16_t *)pValue;
status = VolumeSetVolumeLevel(pContext, (int16_t)level);
break;
case VOLUME_PARAM_MUTE:
mute = *(uint32_t *)pValue;
status = VolumeSetMute(pContext, mute);
break;
case VOLUME_PARAM_ENABLESTEREOPOSITION:
positionEnabled = *(uint32_t *)pValue;
status = VolumeEnableStereoPosition(pContext, positionEnabled);
status = VolumeSetStereoPosition(pContext, pContext->pBundledContext->positionSaved);
break;
case VOLUME_PARAM_STEREOPOSITION:
position = *(int16_t *)pValue;
status = VolumeSetStereoPosition(pContext, (int16_t)position);
break;
default:
ALOGV("\tLVM_ERROR : Volume_setParameter() invalid param %d", param);
break;
}
return status;
} /* end Volume_setParameter */
/****************************************************************************************
* Name : LVC_ToDB_s32Tos16()
* Input : Signed 32-bit integer
* Output : Signed 16-bit integer
* MSB (16) = sign bit
* (15->05) = integer part
* (04->01) = decimal part
* Returns : Db value with respect to full scale
* Description :
* Remarks :
****************************************************************************************/
LVM_INT16 LVC_ToDB_s32Tos16(LVM_INT32 Lin_fix)
{
LVM_INT16 db_fix;
LVM_INT16 Shift;
LVM_INT16 SmallRemainder;
LVM_UINT32 Remainder = (LVM_UINT32)Lin_fix;
/* Count leading bits, 1 cycle in assembly*/
for (Shift = 0; Shift<32; Shift++)
{
if ((Remainder & 0x80000000U)!=0)
{
break;
}
Remainder = Remainder << 1;
}
/*
* Based on the approximation equation (for Q11.4 format):
*
* dB = -96 * Shift + 16 * (8 * Remainder - 2 * Remainder^2)
*/
db_fix = (LVM_INT16)(-96 * Shift); /* Six dB steps in Q11.4 format*/
SmallRemainder = (LVM_INT16)((Remainder & 0x7fffffff) >> 24);
db_fix = (LVM_INT16)(db_fix + SmallRemainder );
SmallRemainder = (LVM_INT16)(SmallRemainder * SmallRemainder);
db_fix = (LVM_INT16)(db_fix - (LVM_INT16)((LVM_UINT16)SmallRemainder >> 9));
/* Correct for small offset */
db_fix = (LVM_INT16)(db_fix - 5);
return db_fix;
}
int Effect_setEnabled(EffectContext *pContext, bool enabled)
{
ALOGV("\tEffect_setEnabled() type %d, enabled %d", pContext->EffectType, enabled);
if (enabled) {
bool tempDisabled = false;
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountBb <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountBb =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bBassEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bBassTempDisabled;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountEq <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountEq =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bEqualizerEnabled = LVM_TRUE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already enabled");
return -EINVAL;
}
if(pContext->pBundledContext->SamplesToExitCountVirt <= 0){
pContext->pBundledContext->NumberEffectsEnabled++;
}
pContext->pBundledContext->SamplesToExitCountVirt =
(LVM_INT32)(pContext->pBundledContext->SamplesPerSecond*0.1);
pContext->pBundledContext->bVirtualizerEnabled = LVM_TRUE;
tempDisabled = pContext->pBundledContext->bVirtualizerTempDisabled;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_TRUE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already enabled");
return -EINVAL;
}
pContext->pBundledContext->NumberEffectsEnabled++;
pContext->pBundledContext->bVolumeEnabled = LVM_TRUE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
if (!tempDisabled) {
LvmEffect_enable(pContext);
}
} else {
switch (pContext->EffectType) {
case LVM_BASS_BOOST:
if (pContext->pBundledContext->bBassEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_BASS_BOOST is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bBassEnabled = LVM_FALSE;
break;
case LVM_EQUALIZER:
if (pContext->pBundledContext->bEqualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_EQUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bEqualizerEnabled = LVM_FALSE;
break;
case LVM_VIRTUALIZER:
if (pContext->pBundledContext->bVirtualizerEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VIRTUALIZER is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVirtualizerEnabled = LVM_FALSE;
break;
case LVM_VOLUME:
if (pContext->pBundledContext->bVolumeEnabled == LVM_FALSE) {
ALOGV("\tEffect_setEnabled() LVM_VOLUME is already disabled");
return -EINVAL;
}
pContext->pBundledContext->bVolumeEnabled = LVM_FALSE;
break;
default:
ALOGV("\tEffect_setEnabled() invalid effect type");
return -EINVAL;
}
LvmEffect_disable(pContext);
}
return 0;
}
int16_t LVC_Convert_VolToDb(uint32_t vol){
int16_t dB;
dB = LVC_ToDB_s32Tos16(vol <<7);
dB = (dB +8)>>4;
dB = (dB <-96) ? -96 : dB ;
return dB;
}
} // namespace
Commit Message: Fix security vulnerability: Effect command might allow negative indexes
Bug: 32448258
Bug: 32095626
Test: Use POC bug or cts security test
Change-Id: I69f24eac5866f8d9090fc4c0ebe58c2c297b63df
(cherry picked from commit 01183402d757f0c28bfd5e3b127b3809dfd67459)
CWE ID: CWE-200
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: virtual void SetUp() {
const tuple<int, int, VarianceFunctionType>& params = this->GetParam();
log2width_ = get<0>(params);
width_ = 1 << log2width_;
log2height_ = get<1>(params);
height_ = 1 << log2height_;
variance_ = get<2>(params);
rnd(ACMRandom::DeterministicSeed());
block_size_ = width_ * height_;
src_ = new uint8_t[block_size_];
ref_ = new uint8_t[block_size_];
ASSERT_TRUE(src_ != NULL);
ASSERT_TRUE(ref_ != NULL);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
server->allowAnonymous = 0;
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: int propagate_mnt(struct mount *dest_mnt, struct mountpoint *dest_mp,
struct mount *source_mnt, struct hlist_head *tree_list)
{
struct mount *m, *n;
int ret = 0;
/*
* we don't want to bother passing tons of arguments to
* propagate_one(); everything is serialized by namespace_sem,
* so globals will do just fine.
*/
user_ns = current->nsproxy->mnt_ns->user_ns;
last_dest = dest_mnt;
last_source = source_mnt;
mp = dest_mp;
list = tree_list;
dest_master = dest_mnt->mnt_master;
/* all peers of dest_mnt, except dest_mnt itself */
for (n = next_peer(dest_mnt); n != dest_mnt; n = next_peer(n)) {
ret = propagate_one(n);
if (ret)
goto out;
}
/* all slave groups */
for (m = next_group(dest_mnt, dest_mnt); m;
m = next_group(m, dest_mnt)) {
/* everything in that slave group */
n = m;
do {
ret = propagate_one(n);
if (ret)
goto out;
n = next_peer(n);
} while (n != m);
}
out:
read_seqlock_excl(&mount_lock);
hlist_for_each_entry(n, tree_list, mnt_hash) {
m = n->mnt_parent;
if (m->mnt_master != dest_mnt->mnt_master)
CLEAR_MNT_MARK(m->mnt_master);
}
read_sequnlock_excl(&mount_lock);
return ret;
}
Commit Message: propogate_mnt: Handle the first propogated copy being a slave
When the first propgated copy was a slave the following oops would result:
> BUG: unable to handle kernel NULL pointer dereference at 0000000000000010
> IP: [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> PGD bacd4067 PUD bac66067 PMD 0
> Oops: 0000 [#1] SMP
> Modules linked in:
> CPU: 1 PID: 824 Comm: mount Not tainted 4.6.0-rc5userns+ #1523
> Hardware name: Bochs Bochs, BIOS Bochs 01/01/2007
> task: ffff8800bb0a8000 ti: ffff8800bac3c000 task.ti: ffff8800bac3c000
> RIP: 0010:[<ffffffff811fba4e>] [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> RSP: 0018:ffff8800bac3fd38 EFLAGS: 00010283
> RAX: 0000000000000000 RBX: ffff8800bb77ec00 RCX: 0000000000000010
> RDX: 0000000000000000 RSI: ffff8800bb58c000 RDI: ffff8800bb58c480
> RBP: ffff8800bac3fd48 R08: 0000000000000001 R09: 0000000000000000
> R10: 0000000000001ca1 R11: 0000000000001c9d R12: 0000000000000000
> R13: ffff8800ba713800 R14: ffff8800bac3fda0 R15: ffff8800bb77ec00
> FS: 00007f3c0cd9b7e0(0000) GS:ffff8800bfb00000(0000) knlGS:0000000000000000
> CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
> CR2: 0000000000000010 CR3: 00000000bb79d000 CR4: 00000000000006e0
> Stack:
> ffff8800bb77ec00 0000000000000000 ffff8800bac3fd88 ffffffff811fbf85
> ffff8800bac3fd98 ffff8800bb77f080 ffff8800ba713800 ffff8800bb262b40
> 0000000000000000 0000000000000000 ffff8800bac3fdd8 ffffffff811f1da0
> Call Trace:
> [<ffffffff811fbf85>] propagate_mnt+0x105/0x140
> [<ffffffff811f1da0>] attach_recursive_mnt+0x120/0x1e0
> [<ffffffff811f1ec3>] graft_tree+0x63/0x70
> [<ffffffff811f1f6b>] do_add_mount+0x9b/0x100
> [<ffffffff811f2c1a>] do_mount+0x2aa/0xdf0
> [<ffffffff8117efbe>] ? strndup_user+0x4e/0x70
> [<ffffffff811f3a45>] SyS_mount+0x75/0xc0
> [<ffffffff8100242b>] do_syscall_64+0x4b/0xa0
> [<ffffffff81988f3c>] entry_SYSCALL64_slow_path+0x25/0x25
> Code: 00 00 75 ec 48 89 0d 02 22 22 01 8b 89 10 01 00 00 48 89 05 fd 21 22 01 39 8e 10 01 00 00 0f 84 e0 00 00 00 48 8b 80 d8 00 00 00 <48> 8b 50 10 48 89 05 df 21 22 01 48 89 15 d0 21 22 01 8b 53 30
> RIP [<ffffffff811fba4e>] propagate_one+0xbe/0x1c0
> RSP <ffff8800bac3fd38>
> CR2: 0000000000000010
> ---[ end trace 2725ecd95164f217 ]---
This oops happens with the namespace_sem held and can be triggered by
non-root users. An all around not pleasant experience.
To avoid this scenario when finding the appropriate source mount to
copy stop the walk up the mnt_master chain when the first source mount
is encountered.
Further rewrite the walk up the last_source mnt_master chain so that
it is clear what is going on.
The reason why the first source mount is special is that it it's
mnt_parent is not a mount in the dest_mnt propagation tree, and as
such termination conditions based up on the dest_mnt mount propgation
tree do not make sense.
To avoid other kinds of confusion last_dest is not changed when
computing last_source. last_dest is only used once in propagate_one
and that is above the point of the code being modified, so changing
the global variable is meaningless and confusing.
Cc: [email protected]
fixes: f2ebb3a921c1ca1e2ddd9242e95a1989a50c4c68 ("smarter propagate_mnt()")
Reported-by: Tycho Andersen <[email protected]>
Reviewed-by: Seth Forshee <[email protected]>
Tested-by: Seth Forshee <[email protected]>
Signed-off-by: "Eric W. Biederman" <[email protected]>
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: uint8_t* FAST_FUNC udhcp_get_option32(struct dhcp_packet *packet, int code)
{
uint8_t *r = udhcp_get_option(packet, code);
if (r) {
if (r[-1] != 4)
r = NULL;
}
return r;
}
Commit Message:
CWE ID: CWE-125
Target: 1
Example 2:
Code: void MockDaemonProcess::SendToNetwork(IPC::Message* message) {
Sent(*message);
delete message;
}
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: 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 avr_custom_spm_page_fill(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut64 addr, page_size_bits, i;
ut8 r0, r1;
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r0 = i;
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r1 = i;
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
addr &= (MASK (page_size_bits) ^ 1);
r_anal_esil_mem_write (esil, addr++, &r0, 1);
r_anal_esil_mem_write (esil, addr++, &r1, 1);
return true;
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
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: int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
skb_orphan(skb);
if (!(dev->flags & IFF_UP))
return NET_RX_DROP;
if (skb->len > (dev->mtu + dev->hard_header_len))
return NET_RX_DROP;
skb_set_dev(skb, dev);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, dev);
return netif_rx(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: 1
Example 2:
Code: xmlXPtrGetNthChild(xmlNodePtr cur, int no) {
int i;
if (cur == NULL)
return(cur);
cur = cur->children;
for (i = 0;i <= no;cur = cur->next) {
if (cur == NULL)
return(cur);
if ((cur->type == XML_ELEMENT_NODE) ||
(cur->type == XML_DOCUMENT_NODE) ||
(cur->type == XML_HTML_DOCUMENT_NODE)) {
i++;
if (i == no)
break;
}
}
return(cur);
}
Commit Message: Fix XPointer bug.
BUG=125462
[email protected]
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10344022
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@135174 0039d316-1c4b-4281-b951-d872f2087c98
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: MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const ssize_t offset,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
zero;
MagickRealType
number_pixels;
ssize_t
y;
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);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if (width == 0)
return(threshold_image);
if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse)
{
InheritException(exception,&threshold_image->exception);
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Local adaptive threshold.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(image,&zero);
number_pixels=(MagickRealType) (width*height);
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
MagickPixelPacket
channel_bias,
channel_sum;
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p,
*magick_restrict r;
register IndexPacket
*magick_restrict threshold_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
ssize_t
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
height/2L,image->columns+width,height,exception);
q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1,
exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view);
channel_bias=zero;
channel_sum=zero;
r=p;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
{
channel_bias.red+=r[u].red;
channel_bias.green+=r[u].green;
channel_bias.blue+=r[u].blue;
channel_bias.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType)
GetPixelIndex(indexes+(r-p)+u);
}
channel_sum.red+=r[u].red;
channel_sum.green+=r[u].green;
channel_sum.blue+=r[u].blue;
channel_sum.opacity+=r[u].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+(r-p)+u);
}
r+=image->columns+width;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickPixelPacket
mean;
mean=zero;
r=p;
channel_sum.red-=channel_bias.red;
channel_sum.green-=channel_bias.green;
channel_sum.blue-=channel_bias.blue;
channel_sum.opacity-=channel_bias.opacity;
channel_sum.index-=channel_bias.index;
channel_bias=zero;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias.red+=r[0].red;
channel_bias.green+=r[0].green;
channel_bias.blue+=r[0].blue;
channel_bias.opacity+=r[0].opacity;
if (image->colorspace == CMYKColorspace)
channel_bias.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+0);
channel_sum.red+=r[width-1].red;
channel_sum.green+=r[width-1].green;
channel_sum.blue+=r[width-1].blue;
channel_sum.opacity+=r[width-1].opacity;
if (image->colorspace == CMYKColorspace)
channel_sum.index=(MagickRealType) GetPixelIndex(indexes+x+(r-p)+
width-1);
r+=image->columns+width;
}
mean.red=(MagickRealType) (channel_sum.red/number_pixels+offset);
mean.green=(MagickRealType) (channel_sum.green/number_pixels+offset);
mean.blue=(MagickRealType) (channel_sum.blue/number_pixels+offset);
mean.opacity=(MagickRealType) (channel_sum.opacity/number_pixels+offset);
if (image->colorspace == CMYKColorspace)
mean.index=(MagickRealType) (channel_sum.index/number_pixels+offset);
SetPixelRed(q,((MagickRealType) GetPixelRed(q) <= mean.red) ?
0 : QuantumRange);
SetPixelGreen(q,((MagickRealType) GetPixelGreen(q) <= mean.green) ?
0 : QuantumRange);
SetPixelBlue(q,((MagickRealType) GetPixelBlue(q) <= mean.blue) ?
0 : QuantumRange);
SetPixelOpacity(q,((MagickRealType) GetPixelOpacity(q) <= mean.opacity) ?
0 : QuantumRange);
if (image->colorspace == CMYKColorspace)
SetPixelIndex(threshold_indexes+x,(((MagickRealType) GetPixelIndex(
threshold_indexes+x) <= mean.index) ? 0 : QuantumRange));
p++;
q++;
}
sync=SyncCacheViewAuthenticPixels(threshold_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609
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 irqreturn_t i8042_interrupt(int irq, void *dev_id)
{
struct i8042_port *port;
struct serio *serio;
unsigned long flags;
unsigned char str, data;
unsigned int dfl;
unsigned int port_no;
bool filtered;
int ret = 1;
spin_lock_irqsave(&i8042_lock, flags);
str = i8042_read_status();
if (unlikely(~str & I8042_STR_OBF)) {
spin_unlock_irqrestore(&i8042_lock, flags);
if (irq)
dbg("Interrupt %d, without any data\n", irq);
ret = 0;
goto out;
}
data = i8042_read_data();
if (i8042_mux_present && (str & I8042_STR_AUXDATA)) {
static unsigned long last_transmit;
static unsigned char last_str;
dfl = 0;
if (str & I8042_STR_MUXERR) {
dbg("MUX error, status is %02x, data is %02x\n",
str, data);
/*
* When MUXERR condition is signalled the data register can only contain
* 0xfd, 0xfe or 0xff if implementation follows the spec. Unfortunately
* it is not always the case. Some KBCs also report 0xfc when there is
* nothing connected to the port while others sometimes get confused which
* port the data came from and signal error leaving the data intact. They
* _do not_ revert to legacy mode (actually I've never seen KBC reverting
* to legacy mode yet, when we see one we'll add proper handling).
* Anyway, we process 0xfc, 0xfd, 0xfe and 0xff as timeouts, and for the
* rest assume that the data came from the same serio last byte
* was transmitted (if transmission happened not too long ago).
*/
switch (data) {
default:
if (time_before(jiffies, last_transmit + HZ/10)) {
str = last_str;
break;
}
/* fall through - report timeout */
case 0xfc:
case 0xfd:
case 0xfe: dfl = SERIO_TIMEOUT; data = 0xfe; break;
case 0xff: dfl = SERIO_PARITY; data = 0xfe; break;
}
}
port_no = I8042_MUX_PORT_NO + ((str >> 6) & 3);
last_str = str;
last_transmit = jiffies;
} else {
dfl = ((str & I8042_STR_PARITY) ? SERIO_PARITY : 0) |
((str & I8042_STR_TIMEOUT && !i8042_notimeout) ? SERIO_TIMEOUT : 0);
port_no = (str & I8042_STR_AUXDATA) ?
I8042_AUX_PORT_NO : I8042_KBD_PORT_NO;
}
port = &i8042_ports[port_no];
serio = port->exists ? port->serio : NULL;
filter_dbg(port->driver_bound, data, "<- i8042 (interrupt, %d, %d%s%s)\n",
port_no, irq,
dfl & SERIO_PARITY ? ", bad parity" : "",
dfl & SERIO_TIMEOUT ? ", timeout" : "");
filtered = i8042_filter(data, str, serio);
spin_unlock_irqrestore(&i8042_lock, flags);
if (likely(port->exists && !filtered))
serio_interrupt(serio, data, dfl);
out:
return IRQ_RETVAL(ret);
}
Commit Message: Input: i8042 - fix crash at boot time
The driver checks port->exists twice in i8042_interrupt(), first when
trying to assign temporary "serio" variable, and second time when deciding
whether it should call serio_interrupt(). The value of port->exists may
change between the 2 checks, and we may end up calling serio_interrupt()
with a NULL pointer:
BUG: unable to handle kernel NULL pointer dereference at 0000000000000050
IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
PGD 0
Oops: 0002 [#1] SMP
last sysfs file:
CPU 0
Modules linked in:
Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996)
RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40
RSP: 0018:ffff880028203cc0 EFLAGS: 00010082
RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000
RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050
RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0
R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050
R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098
FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500)
Stack:
ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000
<d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098
<d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac
Call Trace:
<IRQ>
[<ffffffff813de186>] serio_interrupt+0x36/0xa0
[<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0
[<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20
[<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10
[<ffffffff810e1640>] handle_IRQ_event+0x60/0x170
[<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50
[<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180
[<ffffffff8100de89>] handle_irq+0x49/0xa0
[<ffffffff81516c8c>] do_IRQ+0x6c/0xf0
[<ffffffff8100b9d3>] ret_from_intr+0x0/0x11
[<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0
[<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260
[<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30
[<ffffffff8100de05>] ? do_softirq+0x65/0xa0
[<ffffffff81076d95>] ? irq_exit+0x85/0x90
[<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b
[<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20
To avoid the issue let's change the second check to test whether serio is
NULL or not.
Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of
trying to be overly smart and using memory barriers.
Signed-off-by: Chen Hong <[email protected]>
[dtor: take lock in i8042_start()/i8042_stop()]
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: GfxDeviceGrayColorSpace::~GfxDeviceGrayColorSpace() {
}
Commit Message:
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: choose_filters(struct archive_read *a)
{
int number_bidders, i, bid, best_bid;
struct archive_read_filter_bidder *bidder, *best_bidder;
struct archive_read_filter *filter;
ssize_t avail;
int r;
for (;;) {
number_bidders = sizeof(a->bidders) / sizeof(a->bidders[0]);
best_bid = 0;
best_bidder = NULL;
bidder = a->bidders;
for (i = 0; i < number_bidders; i++, bidder++) {
if (bidder->bid != NULL) {
bid = (bidder->bid)(bidder, a->filter);
if (bid > best_bid) {
best_bid = bid;
best_bidder = bidder;
}
}
}
/* If no bidder, we're done. */
if (best_bidder == NULL) {
/* Verify the filter by asking it for some data. */
__archive_read_filter_ahead(a->filter, 1, &avail);
if (avail < 0) {
__archive_read_close_filters(a);
__archive_read_free_filters(a);
return (ARCHIVE_FATAL);
}
a->archive.compression_name = a->filter->name;
a->archive.compression_code = a->filter->code;
return (ARCHIVE_OK);
}
filter
= (struct archive_read_filter *)calloc(1, sizeof(*filter));
if (filter == NULL)
return (ARCHIVE_FATAL);
filter->bidder = best_bidder;
filter->archive = a;
filter->upstream = a->filter;
a->filter = filter;
r = (best_bidder->init)(a->filter);
if (r != ARCHIVE_OK) {
__archive_read_close_filters(a);
__archive_read_free_filters(a);
return (ARCHIVE_FATAL);
}
}
}
Commit Message: Fix a potential crash issue discovered by Alexander Cherepanov:
It seems bsdtar automatically handles stacked compression. This is a
nice feature but it could be problematic when it's completely
unlimited. Most clearly it's illustrated with quines:
$ curl -sRO http://www.maximumcompression.com/selfgz.gz
$ (ulimit -v 10000000 && bsdtar -tvf selfgz.gz)
bsdtar: Error opening archive: Can't allocate data for gzip decompression
Without ulimit, bsdtar will eat all available memory. This could also
be a problem for other applications using libarchive.
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int __key_instantiate_and_link(struct key *key,
struct key_preparsed_payload *prep,
struct key *keyring,
struct key *authkey,
struct assoc_array_edit **_edit)
{
int ret, awaken;
key_check(key);
key_check(keyring);
awaken = 0;
ret = -EBUSY;
mutex_lock(&key_construction_mutex);
/* can't instantiate twice */
if (!test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) {
/* instantiate the key */
ret = key->type->instantiate(key, prep);
if (ret == 0) {
/* mark the key as being instantiated */
atomic_inc(&key->user->nikeys);
set_bit(KEY_FLAG_INSTANTIATED, &key->flags);
if (test_and_clear_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags))
awaken = 1;
/* and link it into the destination keyring */
if (keyring) {
if (test_bit(KEY_FLAG_KEEP, &keyring->flags))
set_bit(KEY_FLAG_KEEP, &key->flags);
__key_link(key, _edit);
}
/* disable the authorisation key */
if (authkey)
key_revoke(authkey);
if (prep->expiry != TIME_T_MAX) {
key->expiry = prep->expiry;
key_schedule_gc(prep->expiry + key_gc_delay);
}
}
}
mutex_unlock(&key_construction_mutex);
/* wake up anyone waiting for a key to be constructed */
if (awaken)
wake_up_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT);
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: ExtensionFunction::ResponseAction TabsGoForwardFunction::Run() {
std::unique_ptr<tabs::GoForward::Params> params(
tabs::GoForward::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
int tab_id = params->tab_id ? *params->tab_id : -1;
std::string error;
WebContents* web_contents =
GetTabsAPIDefaultWebContents(this, tab_id, &error);
if (!web_contents)
return RespondNow(Error(error));
NavigationController& controller = web_contents->GetController();
if (!controller.CanGoForward())
return RespondNow(Error(tabs_constants::kNotFoundNextPageError));
controller.GoForward();
return RespondNow(NoArguments());
}
Commit Message: Call CanCaptureVisiblePage in page capture API.
Currently the pageCapture permission allows access
to arbitrary local files and chrome:// pages which
can be a security concern. In order to address this,
the page capture API needs to be changed similar to
the captureVisibleTab API. The API will now only allow
extensions to capture otherwise-restricted URLs if the
user has granted activeTab. In addition, file:// URLs are
only capturable with the "Allow on file URLs" option enabled.
Bug: 893087
Change-Id: I6d6225a3efb70fc033e2e1c031c633869afac624
Reviewed-on: https://chromium-review.googlesource.com/c/1330689
Commit-Queue: Bettina Dea <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Varun Khaneja <[email protected]>
Cr-Commit-Position: refs/heads/master@{#615248}
CWE ID: CWE-20
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 TestAppInstancesHelper(const std::string& app_name) {
LOG(INFO) << "Start of test.";
extensions::ProcessMap* process_map =
extensions::ProcessMap::Get(browser()->profile());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII(app_name)));
const Extension* extension = GetSingleLoadedExtension();
GURL base_url = GetTestBaseURL(app_name);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
LOG(INFO) << "Nav 1.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(1)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI());
content::WindowedNotificationObserver tab_added_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::NotificationService::AllSources());
chrome::NewTab(browser());
tab_added_observer.Wait();
LOG(INFO) << "New tab.";
ui_test_utils::NavigateToURL(browser(),
base_url.Resolve("path2/empty.html"));
LOG(INFO) << "Nav 2.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(2)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI());
ASSERT_EQ(3, browser()->tab_strip_model()->count());
WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1);
WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2);
EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost());
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, NULL);
LOG(INFO) << "WindowOpenHelper 1.";
OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, NULL);
LOG(INFO) << "End of test.";
UnloadExtension(extension->id());
}
Commit Message: [Extensions] Update navigations across hypothetical extension extents
Update code to treat navigations across hypothetical extension extents
(e.g. for nonexistent extensions) the same as we do for navigations
crossing installed extension extents.
Bug: 598265
Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b
Reviewed-on: https://chromium-review.googlesource.com/617180
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#495779}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: status_t OMXNodeInstance::emptyBuffer(
OMX::buffer_id buffer,
OMX_U32 rangeOffset, OMX_U32 rangeLength,
OMX_U32 flags, OMX_TICKS timestamp, int fenceFd) {
Mutex::Autolock autoLock(mLock);
if (getGraphicBufferSource() != NULL) {
android_errorWriteLog(0x534e4554, "29422020");
return INVALID_OPERATION;
}
OMX_BUFFERHEADERTYPE *header = findBufferHeader(buffer, kPortIndexInput);
if (header == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
BufferMeta *buffer_meta =
static_cast<BufferMeta *>(header->pAppPrivate);
sp<ABuffer> backup = buffer_meta->getBuffer(header, true /* backup */, false /* limit */);
sp<ABuffer> codec = buffer_meta->getBuffer(header, false /* backup */, false /* limit */);
if (mMetadataType[kPortIndexInput] == kMetadataBufferTypeGrallocSource
&& backup->capacity() >= sizeof(VideoNativeMetadata)
&& codec->capacity() >= sizeof(VideoGrallocMetadata)
&& ((VideoNativeMetadata *)backup->base())->eType
== kMetadataBufferTypeANWBuffer) {
VideoNativeMetadata &backupMeta = *(VideoNativeMetadata *)backup->base();
VideoGrallocMetadata &codecMeta = *(VideoGrallocMetadata *)codec->base();
CLOG_BUFFER(emptyBuffer, "converting ANWB %p to handle %p",
backupMeta.pBuffer, backupMeta.pBuffer->handle);
codecMeta.pHandle = backupMeta.pBuffer != NULL ? backupMeta.pBuffer->handle : NULL;
codecMeta.eType = kMetadataBufferTypeGrallocSource;
header->nFilledLen = rangeLength ? sizeof(codecMeta) : 0;
header->nOffset = 0;
} else {
if (rangeOffset > header->nAllocLen
|| rangeLength > header->nAllocLen - rangeOffset) {
CLOG_ERROR(emptyBuffer, OMX_ErrorBadParameter, FULL_BUFFER(NULL, header, fenceFd));
if (fenceFd >= 0) {
::close(fenceFd);
}
return BAD_VALUE;
}
header->nFilledLen = rangeLength;
header->nOffset = rangeOffset;
buffer_meta->CopyToOMX(header);
}
return emptyBuffer_l(header, flags, timestamp, (intptr_t)buffer, fenceFd);
}
Commit Message: IOMX: do not convert ANWB to gralloc source in emptyBuffer
Bug: 29422020
Bug: 31412859
Change-Id: If48e3e0b6f1af99a459fdc3f6f03744bbf0dc375
(cherry picked from commit 534bb6132a6a664f90b42b3ef81298b42efb3dc2)
CWE ID: CWE-200
Target: 1
Example 2:
Code: static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
{
return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
vcpu->run->request_interrupt_window &&
kvm_arch_interrupt_allowed(vcpu));
}
Commit Message: KVM: Ensure all vcpus are consistent with in-kernel irqchip settings
(cherry picked from commit 3e515705a1f46beb1c942bb8043c16f8ac7b1e9e)
If some vcpus are created before KVM_CREATE_IRQCHIP, then
irqchip_in_kernel() and vcpu->arch.apic will be inconsistent, leading
to potential NULL pointer dereferences.
Fix by:
- ensuring that no vcpus are installed when KVM_CREATE_IRQCHIP is called
- ensuring that a vcpu has an apic if it is installed after KVM_CREATE_IRQCHIP
This is somewhat long winded because vcpu->arch.apic is created without
kvm->lock held.
Based on earlier patch by Michael Ellerman.
Signed-off-by: Michael Ellerman <[email protected]>
Signed-off-by: Avi Kivity <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int pmcraid_reset_bringdown(struct pmcraid_instance *pinstance)
{
return pmcraid_reset_reload(pinstance,
SHUTDOWN_NORMAL,
IOA_STATE_UNKNOWN);
}
Commit Message: [SCSI] pmcraid: reject negative request size
There's a code path in pmcraid that can be reached via device ioctl that
causes all sorts of ugliness, including heap corruption or triggering the
OOM killer due to consecutive allocation of large numbers of pages.
First, the user can call pmcraid_chr_ioctl(), with a type
PMCRAID_PASSTHROUGH_IOCTL. This calls through to
pmcraid_ioctl_passthrough(). Next, a pmcraid_passthrough_ioctl_buffer
is copied in, and the request_size variable is set to
buffer->ioarcb.data_transfer_length, which is an arbitrary 32-bit
signed value provided by the user. If a negative value is provided
here, bad things can happen. For example,
pmcraid_build_passthrough_ioadls() is called with this request_size,
which immediately calls pmcraid_alloc_sglist() with a negative size.
The resulting math on allocating a scatter list can result in an
overflow in the kzalloc() call (if num_elem is 0, the sglist will be
smaller than expected), or if num_elem is unexpectedly large the
subsequent loop will call alloc_pages() repeatedly, a high number of
pages will be allocated and the OOM killer might be invoked.
It looks like preventing this value from being negative in
pmcraid_ioctl_passthrough() would be sufficient.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: James Bottomley <[email protected]>
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: int lock_flags) __releases(RCU)
{
struct inode *inode = VFS_I(ip);
struct xfs_mount *mp = ip->i_mount;
int error;
/*
* check for re-use of an inode within an RCU grace period due to the
* radix tree nodes not being updated yet. We monitor for this by
* setting the inode number to zero before freeing the inode structure.
* If the inode has been reallocated and set up, then the inode number
* will not match, so check for that, too.
*/
spin_lock(&ip->i_flags_lock);
if (ip->i_ino != ino) {
trace_xfs_iget_skip(ip);
XFS_STATS_INC(mp, xs_ig_frecycle);
error = -EAGAIN;
goto out_error;
}
/*
* If we are racing with another cache hit that is currently
* instantiating this inode or currently recycling it out of
* reclaimabe state, wait for the initialisation to complete
* before continuing.
*
* XXX(hch): eventually we should do something equivalent to
* wait_on_inode to wait for these flags to be cleared
* instead of polling for it.
*/
if (ip->i_flags & (XFS_INEW|XFS_IRECLAIM)) {
trace_xfs_iget_skip(ip);
XFS_STATS_INC(mp, xs_ig_frecycle);
error = -EAGAIN;
goto out_error;
}
/*
* If lookup is racing with unlink return an error immediately.
*/
if (VFS_I(ip)->i_mode == 0 && !(flags & XFS_IGET_CREATE)) {
error = -ENOENT;
goto out_error;
}
/*
* If IRECLAIMABLE is set, we've torn down the VFS inode already.
* Need to carefully get it back into useable state.
*/
if (ip->i_flags & XFS_IRECLAIMABLE) {
trace_xfs_iget_reclaim(ip);
if (flags & XFS_IGET_INCORE) {
error = -EAGAIN;
goto out_error;
}
/*
* We need to set XFS_IRECLAIM to prevent xfs_reclaim_inode
* from stomping over us while we recycle the inode. We can't
* clear the radix tree reclaimable tag yet as it requires
* pag_ici_lock to be held exclusive.
*/
ip->i_flags |= XFS_IRECLAIM;
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
error = xfs_reinit_inode(mp, inode);
if (error) {
bool wake;
/*
* Re-initializing the inode failed, and we are in deep
* trouble. Try to re-add it to the reclaim list.
*/
rcu_read_lock();
spin_lock(&ip->i_flags_lock);
wake = !!__xfs_iflags_test(ip, XFS_INEW);
ip->i_flags &= ~(XFS_INEW | XFS_IRECLAIM);
if (wake)
wake_up_bit(&ip->i_flags, __XFS_INEW_BIT);
ASSERT(ip->i_flags & XFS_IRECLAIMABLE);
trace_xfs_iget_reclaim_fail(ip);
goto out_error;
}
spin_lock(&pag->pag_ici_lock);
spin_lock(&ip->i_flags_lock);
/*
* Clear the per-lifetime state in the inode as we are now
* effectively a new inode and need to return to the initial
* state before reuse occurs.
*/
ip->i_flags &= ~XFS_IRECLAIM_RESET_FLAGS;
ip->i_flags |= XFS_INEW;
xfs_inode_clear_reclaim_tag(pag, ip->i_ino);
inode->i_state = I_NEW;
ASSERT(!rwsem_is_locked(&inode->i_rwsem));
init_rwsem(&inode->i_rwsem);
spin_unlock(&ip->i_flags_lock);
spin_unlock(&pag->pag_ici_lock);
} else {
/* If the VFS inode is being torn down, pause and try again. */
if (!igrab(inode)) {
trace_xfs_iget_skip(ip);
error = -EAGAIN;
goto out_error;
}
/* We've got a live one. */
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
trace_xfs_iget_hit(ip);
}
if (lock_flags != 0)
xfs_ilock(ip, lock_flags);
if (!(flags & XFS_IGET_INCORE))
xfs_iflags_clear(ip, XFS_ISTALE | XFS_IDONTCACHE);
XFS_STATS_INC(mp, xs_ig_found);
return 0;
out_error:
spin_unlock(&ip->i_flags_lock);
rcu_read_unlock();
return error;
}
Commit Message: xfs: validate cached inodes are free when allocated
A recent fuzzed filesystem image cached random dcache corruption
when the reproducer was run. This often showed up as panics in
lookup_slow() on a null inode->i_ops pointer when doing pathwalks.
BUG: unable to handle kernel NULL pointer dereference at 0000000000000000
....
Call Trace:
lookup_slow+0x44/0x60
walk_component+0x3dd/0x9f0
link_path_walk+0x4a7/0x830
path_lookupat+0xc1/0x470
filename_lookup+0x129/0x270
user_path_at_empty+0x36/0x40
path_listxattr+0x98/0x110
SyS_listxattr+0x13/0x20
do_syscall_64+0xf5/0x280
entry_SYSCALL_64_after_hwframe+0x42/0xb7
but had many different failure modes including deadlocks trying to
lock the inode that was just allocated or KASAN reports of
use-after-free violations.
The cause of the problem was a corrupt INOBT on a v4 fs where the
root inode was marked as free in the inobt record. Hence when we
allocated an inode, it chose the root inode to allocate, found it in
the cache and re-initialised it.
We recently fixed a similar inode allocation issue caused by inobt
record corruption problem in xfs_iget_cache_miss() in commit
ee457001ed6c ("xfs: catch inode allocation state mismatch
corruption"). This change adds similar checks to the cache-hit path
to catch it, and turns the reproducer into a corruption shutdown
situation.
Reported-by: Wen Xu <[email protected]>
Signed-Off-By: Dave Chinner <[email protected]>
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Carlos Maiolino <[email protected]>
Reviewed-by: Darrick J. Wong <[email protected]>
[darrick: fix typos in comment]
Signed-off-by: Darrick J. Wong <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
const struct ofp11_queue_stats *qs11)
{
enum ofperr error;
error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
if (error) {
return error;
}
oqs->queue_id = ntohl(qs11->queue_id);
oqs->tx_bytes = ntohll(qs11->tx_bytes);
oqs->tx_packets = ntohll(qs11->tx_packets);
oqs->tx_errors = ntohll(qs11->tx_errors);
oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
return 0;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void GetCSI(const v8::FunctionCallbackInfo<v8::Value>& args) {
WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext();
if (frame) {
WebDataSource* data_source = frame->dataSource();
if (data_source) {
DocumentState* document_state =
DocumentState::FromDataSource(data_source);
v8::Isolate* isolate = args.GetIsolate();
v8::Local<v8::Object> csi = v8::Object::New(isolate);
base::Time now = base::Time::Now();
base::Time start = document_state->request_time().is_null() ?
document_state->start_load_time() :
document_state->request_time();
base::Time onload = document_state->finish_document_load_time();
base::TimeDelta page = now - start;
csi->Set(v8::String::NewFromUtf8(isolate, "startE"),
v8::Number::New(isolate, floor(start.ToDoubleT() * 1000)));
csi->Set(v8::String::NewFromUtf8(isolate, "onloadT"),
v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000)));
csi->Set(v8::String::NewFromUtf8(isolate, "pageT"),
v8::Number::New(isolate, page.InMillisecondsF()));
csi->Set(
v8::String::NewFromUtf8(isolate, "tran"),
v8::Number::New(
isolate, GetCSITransitionType(data_source->navigationType())));
args.GetReturnValue().Set(csi);
return;
}
}
args.GetReturnValue().SetNull();
return;
}
Commit Message: Cache csi info before passing it to JS setters.
JS setters invalidate the pointers frame, data_source and document_state.
BUG=590455
Review URL: https://codereview.chromium.org/1751553002
Cr-Commit-Position: refs/heads/master@{#379047}
CWE ID:
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void WritePixel(struct ngiflib_img * i, struct ngiflib_decode_context * context, u8 v) {
struct ngiflib_gif * p = i->parent;
if(v!=i->gce.transparent_color || !i->gce.transparent_flag) {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
*context->frbuff_p.p8 = v;
#ifndef NGIFLIB_INDEXED_ONLY
} else
*context->frbuff_p.p32 =
GifIndexToTrueColor(i->palette, v);
#endif /* NGIFLIB_INDEXED_ONLY */
}
if(--(context->Xtogo) <= 0) {
#ifdef NGIFLIB_ENABLE_CALLBACKS
if(p->line_cb) p->line_cb(p, context->line_p, context->curY);
#endif /* NGIFLIB_ENABLE_CALLBACKS */
context->Xtogo = i->width;
switch(context->pass) {
case 0:
context->curY++;
break;
case 1: /* 1st pass : every eighth row starting from 0 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 4;
}
break;
case 2: /* 2nd pass : every eighth row starting from 4 */
context->curY += 8;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 2;
}
break;
case 3: /* 3rd pass : every fourth row starting from 2 */
context->curY += 4;
if(context->curY >= p->height) {
context->pass++;
context->curY = i->posY + 1;
}
break;
case 4: /* 4th pass : every odd row */
context->curY += 2;
break;
}
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;
context->frbuff_p.p8 = context->line_p.p8 + i->posX;
#else
context->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
#ifndef NGIFLIB_INDEXED_ONLY
} else {
#ifdef NGIFLIB_ENABLE_CALLBACKS
context->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;
context->frbuff_p.p32 = context->line_p.p32 + i->posX;
#else
context->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;
#endif /* NGIFLIB_ENABLE_CALLBACKS */
}
#endif /* NGIFLIB_INDEXED_ONLY */
} else {
#ifndef NGIFLIB_INDEXED_ONLY
if(p->mode & NGIFLIB_MODE_INDEXED) {
#endif /* NGIFLIB_INDEXED_ONLY */
context->frbuff_p.p8++;
#ifndef NGIFLIB_INDEXED_ONLY
} else {
context->frbuff_p.p32++;
}
#endif /* NGIFLIB_INDEXED_ONLY */
}
}
Commit Message: fix deinterlacing for small pictures
fixes #12
CWE ID: CWE-119
Target: 1
Example 2:
Code: bool in_mouse_drag() const { return in_mouse_drag_; }
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
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 pdo_stmt_init(TSRMLS_D)
{
zend_class_entry ce;
INIT_CLASS_ENTRY(ce, "PDOStatement", pdo_dbstmt_functions);
pdo_dbstmt_ce = zend_register_internal_class(&ce TSRMLS_CC);
pdo_dbstmt_ce->get_iterator = pdo_stmt_iter_get;
pdo_dbstmt_ce->create_object = pdo_dbstmt_new;
zend_class_implements(pdo_dbstmt_ce TSRMLS_CC, 1, zend_ce_traversable);
zend_declare_property_null(pdo_dbstmt_ce, "queryString", sizeof("queryString")-1, ZEND_ACC_PUBLIC TSRMLS_CC);
memcpy(&pdo_dbstmt_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
pdo_dbstmt_object_handlers.write_property = dbstmt_prop_write;
pdo_dbstmt_object_handlers.unset_property = dbstmt_prop_delete;
pdo_dbstmt_object_handlers.get_method = dbstmt_method_get;
pdo_dbstmt_object_handlers.compare_objects = dbstmt_compare;
pdo_dbstmt_object_handlers.clone_obj = dbstmt_clone_obj;
INIT_CLASS_ENTRY(ce, "PDORow", pdo_row_functions);
pdo_row_ce = zend_register_internal_class(&ce TSRMLS_CC);
pdo_row_ce->ce_flags |= ZEND_ACC_FINAL_CLASS; /* when removing this a lot of handlers need to be redone */
pdo_row_ce->create_object = pdo_row_new;
pdo_row_ce->serialize = pdo_row_serialize;
}
Commit Message: Fix bug #73331 - do not try to serialize/unserialize objects wddx can not handle
Proper soltion would be to call serialize/unserialize and deal with the result,
but this requires more work that should be done by wddx maintainer (not me).
CWE ID: CWE-476
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static int futex_wait(u32 __user *uaddr, int fshared,
u32 val, ktime_t *abs_time, u32 bitset, int clockrt)
{
struct hrtimer_sleeper timeout, *to = NULL;
struct restart_block *restart;
struct futex_hash_bucket *hb;
struct futex_q q;
int ret;
if (!bitset)
return -EINVAL;
q.pi_state = NULL;
q.bitset = bitset;
q.rt_waiter = NULL;
q.requeue_pi_key = NULL;
if (abs_time) {
to = &timeout;
hrtimer_init_on_stack(&to->timer, clockrt ? CLOCK_REALTIME :
CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
hrtimer_init_sleeper(to, current);
hrtimer_set_expires_range_ns(&to->timer, *abs_time,
current->timer_slack_ns);
}
retry:
/* Prepare to wait on uaddr. */
ret = futex_wait_setup(uaddr, val, fshared, &q, &hb);
if (ret)
goto out;
/* queue_me and wait for wakeup, timeout, or a signal. */
futex_wait_queue_me(hb, &q, to);
/* If we were woken (and unqueued), we succeeded, whatever. */
ret = 0;
if (!unqueue_me(&q))
goto out_put_key;
ret = -ETIMEDOUT;
if (to && !to->task)
goto out_put_key;
/*
* We expect signal_pending(current), but we might be the
* victim of a spurious wakeup as well.
*/
if (!signal_pending(current)) {
put_futex_key(fshared, &q.key);
goto retry;
}
ret = -ERESTARTSYS;
if (!abs_time)
goto out_put_key;
restart = ¤t_thread_info()->restart_block;
restart->fn = futex_wait_restart;
restart->futex.uaddr = (u32 *)uaddr;
restart->futex.val = val;
restart->futex.time = abs_time->tv64;
restart->futex.bitset = bitset;
restart->futex.flags = FLAGS_HAS_TIMEOUT;
if (fshared)
restart->futex.flags |= FLAGS_SHARED;
if (clockrt)
restart->futex.flags |= FLAGS_CLOCKRT;
ret = -ERESTART_RESTARTBLOCK;
out_put_key:
put_futex_key(fshared, &q.key);
out:
if (to) {
hrtimer_cancel(&to->timer);
destroy_hrtimer_on_stack(&to->timer);
}
return ret;
}
Commit Message: futex: Fix errors in nested key ref-counting
futex_wait() is leaking key references due to futex_wait_setup()
acquiring an additional reference via the queue_lock() routine. The
nested key ref-counting has been masking bugs and complicating code
analysis. queue_lock() is only called with a previously ref-counted
key, so remove the additional ref-counting from the queue_(un)lock()
functions.
Also futex_wait_requeue_pi() drops one key reference too many in
unqueue_me_pi(). Remove the key reference handling from
unqueue_me_pi(). This was paired with a queue_lock() in
futex_lock_pi(), so the count remains unchanged.
Document remaining nested key ref-counting sites.
Signed-off-by: Darren Hart <[email protected]>
Reported-and-tested-by: Matthieu Fertré<[email protected]>
Reported-by: Louis Rilling<[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Eric Dumazet <[email protected]>
Cc: John Kacur <[email protected]>
Cc: Rusty Russell <[email protected]>
LKML-Reference: <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Cc: [email protected]
CWE ID: CWE-119
Target: 1
Example 2:
Code: xmlParse3986DecOctet(const char **str) {
const char *cur = *str;
if (!(ISA_DIGIT(cur)))
return(1);
if (!ISA_DIGIT(cur+1))
cur++;
else if ((*cur != '0') && (ISA_DIGIT(cur + 1)) && (!ISA_DIGIT(cur+2)))
cur += 2;
else if ((*cur == '1') && (ISA_DIGIT(cur + 1)) && (ISA_DIGIT(cur + 2)))
cur += 3;
else if ((*cur == '2') && (*(cur + 1) >= '0') &&
(*(cur + 1) <= '4') && (ISA_DIGIT(cur + 2)))
cur += 3;
else if ((*cur == '2') && (*(cur + 1) == '5') &&
(*(cur + 2) >= '0') && (*(cur + 1) <= '5'))
cur += 3;
else
return(1);
*str = cur;
return(0);
}
Commit Message: DO NOT MERGE: Use correct limit for port values
no upstream report yet, add it here when we have it
issue found & patch by nmehta@
Bug: 36555370
Change-Id: Ibf1efea554b95f514e23e939363d608021de4614
(cherry picked from commit b62884fb49fe92081e414966d9b5fe58250ae53c)
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: tt_size_done( FT_Size ttsize ) /* TT_Size */
{
TT_Size size = (TT_Size)ttsize;
#ifdef TT_USE_BYTECODE_INTERPRETER
tt_size_done_bytecode( ttsize );
#endif
size->ttmetrics.valid = FALSE;
}
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: void MaintainContentLengthPrefsForDateChange(
base::ListValue* original_update,
base::ListValue* received_update,
int days_since_last_update) {
if (days_since_last_update == -1) {
days_since_last_update = 0;
} else if (days_since_last_update < -1) {
original_update->Clear();
received_update->Clear();
days_since_last_update = kNumDaysInHistory;
//// DailyContentLengthUpdate maintains a data saving pref. The pref is a list
//// of |kNumDaysInHistory| elements of daily total content lengths for the past
//// |kNumDaysInHistory| days.
}
DCHECK_GE(days_since_last_update, 0);
for (int i = 0;
i < days_since_last_update && i < static_cast<int>(kNumDaysInHistory);
++i) {
original_update->AppendString(base::Int64ToString(0));
received_update->AppendString(base::Int64ToString(0));
}
MaintainContentLengthPrefsWindow(original_update, kNumDaysInHistory);
MaintainContentLengthPrefsWindow(received_update, kNumDaysInHistory);
}
Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled.
BUG=325325
Review URL: https://codereview.chromium.org/106113002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-416
Target: 1
Example 2:
Code: int UDPSocketLibevent::SetMulticastLoopbackMode(bool loopback) {
DCHECK(CalledOnValidThread());
if (is_connected())
return ERR_SOCKET_IS_CONNECTED;
if (loopback)
socket_options_ |= SOCKET_OPTION_MULTICAST_LOOP;
else
socket_options_ &= ~SOCKET_OPTION_MULTICAST_LOOP;
return OK;
}
Commit Message: Map posix error codes in bind better, and fix one windows mapping.
r=wtc
BUG=330233
Review URL: https://codereview.chromium.org/101193008
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98
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: push_callout(i_ctx_t *i_ctx_p, const char *callout_name)
{
int code;
check_estack(1);
code = name_enter_string(imemory, callout_name, esp + 1);
if (code < 0)
return code;
++esp;
r_set_attrs(esp, a_executable);
return o_push_estack;
}
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 RenderFrameDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetRenderer(frame_host_ ? frame_host_->GetProcess() : nullptr,
frame_host_);
protocol::EmulationHandler* emulation_handler =
new protocol::EmulationHandler();
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::DOMHandler()));
session->AddHandler(base::WrapUnique(emulation_handler));
session->AddHandler(base::WrapUnique(new protocol::InputHandler()));
session->AddHandler(base::WrapUnique(new protocol::InspectorHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId())));
session->AddHandler(base::WrapUnique(new protocol::SchemaHandler()));
session->AddHandler(base::WrapUnique(new protocol::ServiceWorkerHandler()));
session->AddHandler(base::WrapUnique(new protocol::StorageHandler()));
session->AddHandler(base::WrapUnique(new protocol::TargetHandler()));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Renderer,
frame_tree_node_ ? frame_tree_node_->frame_tree_node_id() : 0,
GetIOContext())));
if (frame_tree_node_ && !frame_tree_node_->parent()) {
session->AddHandler(
base::WrapUnique(new protocol::PageHandler(emulation_handler)));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
}
if (EnsureAgent())
session->AttachToAgent(agent_ptr_);
if (sessions().size() == 1) {
frame_trace_recorder_.reset(new DevToolsFrameTraceRecorder());
GrantPolicy();
#if defined(OS_ANDROID)
GetWakeLock()->RequestWakeLock();
#endif
}
}
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: OPJ_BOOL opj_tcd_copy_tile_data ( opj_tcd_t *p_tcd,
OPJ_BYTE * p_src,
OPJ_UINT32 p_src_length )
{
OPJ_UINT32 i,j,l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_nb_elem;
l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
if (l_data_size != p_src_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i=0;i<p_tcd->image->numcomps;++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0));
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1:
{
OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
}
else {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (*(l_src_ptr++))&0xff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 2:
{
OPJ_INT32 * l_dest_ptr = l_tilec->data;
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
if (l_img_comp->sgnd) {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
}
else {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (*(l_src_ptr++))&0xffff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4:
{
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
Commit Message: Add sanity check for tile coordinates (#823)
Coordinates are casted from OPJ_UINT32 to OPJ_INT32
Add sanity check for negative values and upper bound becoming lower
than lower bound.
See also
https://pdfium.googlesource.com/pdfium/+/b6befb2ed2485a3805cddea86dc7574510178ea9
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 get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,
indx, 0, data, size, 500);
}
Commit Message: rtl8150: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119
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 install_process_keyring(void)
{
struct cred *new;
int ret;
new = prepare_creds();
if (!new)
return -ENOMEM;
ret = install_process_keyring_to_cred(new);
if (ret < 0) {
abort_creds(new);
return ret != -EEXIST ? ret : 0;
}
return commit_creds(new);
}
Commit Message: KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings
This fixes CVE-2017-7472.
Running the following program as an unprivileged user exhausts kernel
memory by leaking thread keyrings:
#include <keyutils.h>
int main()
{
for (;;)
keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING);
}
Fix it by only creating a new thread keyring if there wasn't one before.
To make things more consistent, make install_thread_keyring_to_cred()
and install_process_keyring_to_cred() both return 0 if the corresponding
keyring is already present.
Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials")
Cc: [email protected] # 2.6.29+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-404
Target: 1
Example 2:
Code: static int ok_to_run(const char *program) {
if (strstr(program, "/")) {
if (access(program, X_OK) == 0) // it will also dereference symlinks
return 1;
}
else { // search $PATH
char *path1 = getenv("PATH");
if (path1) {
if (arg_debug)
printf("Searching $PATH for %s\n", program);
char *path2 = strdup(path1);
if (!path2)
errExit("strdup");
char *ptr = strtok(path2, ":");
while (ptr) {
char *fname;
if (asprintf(&fname, "%s/%s", ptr, program) == -1)
errExit("asprintf");
if (arg_debug)
printf("trying #%s#\n", fname);
struct stat s;
int rv = stat(fname, &s);
if (rv == 0) {
if (access(fname, X_OK) == 0) {
free(path2);
free(fname);
return 1;
}
else
fprintf(stderr, "Error: execute permission denied for %s\n", fname);
free(fname);
break;
}
free(fname);
ptr = strtok(NULL, ":");
}
free(path2);
}
}
return 0;
}
Commit Message: mount runtime seccomp files read-only (#2602)
avoid creating locations in the file system that are both writable and
executable (in this case for processes with euid of the user).
for the same reason also remove user owned libfiles
when it is not needed any more
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: SWFShape_setLineStyle2filled_internal(SWFShape shape, unsigned short width,
SWFFillStyle fill,
int flags, float miterLimit)
{
int line;
if ( shape->isEnded )
return;
for ( line=0; line<shape->nLines; ++line )
{
if ( SWFLineStyle_equals2filled(shape->lines[line], width, fill, flags) )
break;
}
if ( line == shape->nLines )
line = SWFShape_addLineStyle2filled(shape, width, fill, flags, miterLimit);
else
++line;
finishSetLine(shape, line, width);
}
Commit Message: SWFShape_setLeftFillStyle: prevent fill overflow
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: bool_t xdr_nullstring(XDR *xdrs, char **objp)
{
u_int size;
if (xdrs->x_op == XDR_ENCODE) {
if (*objp == NULL)
size = 0;
else
size = strlen(*objp) + 1;
}
if (! xdr_u_int(xdrs, &size)) {
return FALSE;
}
switch (xdrs->x_op) {
case XDR_DECODE:
if (size == 0) {
*objp = NULL;
return TRUE;
} else if (*objp == NULL) {
*objp = (char *) mem_alloc(size);
if (*objp == NULL) {
errno = ENOMEM;
return FALSE;
}
}
return (xdr_opaque(xdrs, *objp, size));
case XDR_ENCODE:
if (size != 0)
return (xdr_opaque(xdrs, *objp, size));
return TRUE;
case XDR_FREE:
if (*objp != NULL)
mem_free(*objp, size);
*objp = NULL;
return TRUE;
}
return FALSE;
}
Commit Message: Verify decoded kadmin C strings [CVE-2015-8629]
In xdr_nullstring(), check that the decoded string is terminated with
a zero byte and does not contain any internal zero bytes.
CVE-2015-8629:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to read beyond the end of allocated memory by sending a string
without a terminating zero byte. Information leakage may be possible
for an attacker with permission to modify the database.
CVSSv2 Vector: AV:N/AC:H/Au:S/C:P/I:N/A:N/E:POC/RL:OF/RC:C
ticket: 8341 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119
Target: 1
Example 2:
Code: void WebContentsImpl::WasShown() {
controller_.SetActive(true);
RenderWidgetHostViewPort* rwhv =
RenderWidgetHostViewPort::FromRWHV(GetRenderWidgetHostView());
if (rwhv) {
rwhv->WasShown();
#if defined(OS_MACOSX)
rwhv->SetActive(true);
#endif
}
last_selected_time_ = base::TimeTicks::Now();
FOR_EACH_OBSERVER(WebContentsObserver, observers_, WasShown());
RenderViewHostImpl* rvh =
static_cast<RenderViewHostImpl*>(GetRenderViewHost());
if (rvh) {
rvh->ResizeRectChanged(GetRootWindowResizerRect());
}
should_normally_be_visible_ = true;
NotificationService::current()->Notify(
NOTIFICATION_WEB_CONTENTS_VISIBILITY_CHANGED,
Source<WebContents>(this),
Details<const bool>(&should_normally_be_visible_));
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 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 const char *parse_array( cJSON *item, const char *value )
{
cJSON *child;
if ( *value != '[' ) {
/* Not an array! */
ep = value;
return 0;
}
item->type = cJSON_Array;
value = skip( value + 1 );
if ( *value == ']' )
return value + 1; /* empty array. */
if ( ! ( item->child = child = cJSON_New_Item() ) )
return 0; /* memory fail */
if ( ! ( value = skip( parse_value( child, skip( value ) ) ) ) )
return 0;
while ( *value == ',' ) {
cJSON *new_item;
if ( ! ( new_item = cJSON_New_Item() ) )
return 0; /* memory fail */
child->next = new_item;
new_item->prev = child;
child = new_item;
if ( ! ( value = skip( parse_value( child, skip( value+1 ) ) ) ) )
return 0; /* memory fail */
}
if ( *value == ']' )
return value + 1; /* end of array */
/* Malformed. */
ep = value;
return 0;
}
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: static int hls_slice_header(HEVCContext *s)
{
GetBitContext *gb = &s->HEVClc->gb;
SliceHeader *sh = &s->sh;
int i, ret;
sh->first_slice_in_pic_flag = get_bits1(gb);
if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) {
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
if (IS_IDR(s))
ff_hevc_clear_refs(s);
}
sh->no_output_of_prior_pics_flag = 0;
if (IS_IRAP(s))
sh->no_output_of_prior_pics_flag = get_bits1(gb);
sh->pps_id = get_ue_golomb_long(gb);
if (sh->pps_id >= HEVC_MAX_PPS_COUNT || !s->ps.pps_list[sh->pps_id]) {
av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);
return AVERROR_INVALIDDATA;
}
if (!sh->first_slice_in_pic_flag &&
s->ps.pps != (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data) {
av_log(s->avctx, AV_LOG_ERROR, "PPS changed between slices.\n");
return AVERROR_INVALIDDATA;
}
s->ps.pps = (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data;
if (s->nal_unit_type == HEVC_NAL_CRA_NUT && s->last_eos == 1)
sh->no_output_of_prior_pics_flag = 1;
if (s->ps.sps != (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data) {
const HEVCSPS *sps = (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data;
const HEVCSPS *last_sps = s->ps.sps;
enum AVPixelFormat pix_fmt;
if (last_sps && IS_IRAP(s) && s->nal_unit_type != HEVC_NAL_CRA_NUT) {
if (sps->width != last_sps->width || sps->height != last_sps->height ||
sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering !=
last_sps->temporal_layer[last_sps->max_sub_layers - 1].max_dec_pic_buffering)
sh->no_output_of_prior_pics_flag = 0;
}
ff_hevc_clear_refs(s);
ret = set_sps(s, sps, sps->pix_fmt);
if (ret < 0)
return ret;
pix_fmt = get_format(s, sps);
if (pix_fmt < 0)
return pix_fmt;
s->avctx->pix_fmt = pix_fmt;
s->seq_decode = (s->seq_decode + 1) & 0xff;
s->max_ra = INT_MAX;
}
sh->dependent_slice_segment_flag = 0;
if (!sh->first_slice_in_pic_flag) {
int slice_address_length;
if (s->ps.pps->dependent_slice_segments_enabled_flag)
sh->dependent_slice_segment_flag = get_bits1(gb);
slice_address_length = av_ceil_log2(s->ps.sps->ctb_width *
s->ps.sps->ctb_height);
sh->slice_segment_addr = get_bitsz(gb, slice_address_length);
if (sh->slice_segment_addr >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid slice segment address: %u.\n",
sh->slice_segment_addr);
return AVERROR_INVALIDDATA;
}
if (!sh->dependent_slice_segment_flag) {
sh->slice_addr = sh->slice_segment_addr;
s->slice_idx++;
}
} else {
sh->slice_segment_addr = sh->slice_addr = 0;
s->slice_idx = 0;
s->slice_initialized = 0;
}
if (!sh->dependent_slice_segment_flag) {
s->slice_initialized = 0;
for (i = 0; i < s->ps.pps->num_extra_slice_header_bits; i++)
skip_bits(gb, 1); // slice_reserved_undetermined_flag[]
sh->slice_type = get_ue_golomb_long(gb);
if (!(sh->slice_type == HEVC_SLICE_I ||
sh->slice_type == HEVC_SLICE_P ||
sh->slice_type == HEVC_SLICE_B)) {
av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",
sh->slice_type);
return AVERROR_INVALIDDATA;
}
if (IS_IRAP(s) && sh->slice_type != HEVC_SLICE_I) {
av_log(s->avctx, AV_LOG_ERROR, "Inter slices in an IRAP frame.\n");
return AVERROR_INVALIDDATA;
}
sh->pic_output_flag = 1;
if (s->ps.pps->output_flag_present_flag)
sh->pic_output_flag = get_bits1(gb);
if (s->ps.sps->separate_colour_plane_flag)
sh->colour_plane_id = get_bits(gb, 2);
if (!IS_IDR(s)) {
int poc, pos;
sh->pic_order_cnt_lsb = get_bits(gb, s->ps.sps->log2_max_poc_lsb);
poc = ff_hevc_compute_poc(s->ps.sps, s->pocTid0, sh->pic_order_cnt_lsb, s->nal_unit_type);
if (!sh->first_slice_in_pic_flag && poc != s->poc) {
av_log(s->avctx, AV_LOG_WARNING,
"Ignoring POC change between slices: %d -> %d\n", s->poc, poc);
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return AVERROR_INVALIDDATA;
poc = s->poc;
}
s->poc = poc;
sh->short_term_ref_pic_set_sps_flag = get_bits1(gb);
pos = get_bits_left(gb);
if (!sh->short_term_ref_pic_set_sps_flag) {
ret = ff_hevc_decode_short_term_rps(gb, s->avctx, &sh->slice_rps, s->ps.sps, 1);
if (ret < 0)
return ret;
sh->short_term_rps = &sh->slice_rps;
} else {
int numbits, rps_idx;
if (!s->ps.sps->nb_st_rps) {
av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n");
return AVERROR_INVALIDDATA;
}
numbits = av_ceil_log2(s->ps.sps->nb_st_rps);
rps_idx = numbits > 0 ? get_bits(gb, numbits) : 0;
sh->short_term_rps = &s->ps.sps->st_rps[rps_idx];
}
sh->short_term_ref_pic_set_size = pos - get_bits_left(gb);
pos = get_bits_left(gb);
ret = decode_lt_rps(s, &sh->long_term_rps, gb);
if (ret < 0) {
av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n");
if (s->avctx->err_recognition & AV_EF_EXPLODE)
return AVERROR_INVALIDDATA;
}
sh->long_term_ref_pic_set_size = pos - get_bits_left(gb);
if (s->ps.sps->sps_temporal_mvp_enabled_flag)
sh->slice_temporal_mvp_enabled_flag = get_bits1(gb);
else
sh->slice_temporal_mvp_enabled_flag = 0;
} else {
s->sh.short_term_rps = NULL;
s->poc = 0;
}
/* 8.3.1 */
if (sh->first_slice_in_pic_flag && s->temporal_id == 0 &&
s->nal_unit_type != HEVC_NAL_TRAIL_N &&
s->nal_unit_type != HEVC_NAL_TSA_N &&
s->nal_unit_type != HEVC_NAL_STSA_N &&
s->nal_unit_type != HEVC_NAL_RADL_N &&
s->nal_unit_type != HEVC_NAL_RADL_R &&
s->nal_unit_type != HEVC_NAL_RASL_N &&
s->nal_unit_type != HEVC_NAL_RASL_R)
s->pocTid0 = s->poc;
if (s->ps.sps->sao_enabled) {
sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb);
if (s->ps.sps->chroma_format_idc) {
sh->slice_sample_adaptive_offset_flag[1] =
sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb);
}
} else {
sh->slice_sample_adaptive_offset_flag[0] = 0;
sh->slice_sample_adaptive_offset_flag[1] = 0;
sh->slice_sample_adaptive_offset_flag[2] = 0;
}
sh->nb_refs[L0] = sh->nb_refs[L1] = 0;
if (sh->slice_type == HEVC_SLICE_P || sh->slice_type == HEVC_SLICE_B) {
int nb_refs;
sh->nb_refs[L0] = s->ps.pps->num_ref_idx_l0_default_active;
if (sh->slice_type == HEVC_SLICE_B)
sh->nb_refs[L1] = s->ps.pps->num_ref_idx_l1_default_active;
if (get_bits1(gb)) { // num_ref_idx_active_override_flag
sh->nb_refs[L0] = get_ue_golomb_long(gb) + 1;
if (sh->slice_type == HEVC_SLICE_B)
sh->nb_refs[L1] = get_ue_golomb_long(gb) + 1;
}
if (sh->nb_refs[L0] > HEVC_MAX_REFS || sh->nb_refs[L1] > HEVC_MAX_REFS) {
av_log(s->avctx, AV_LOG_ERROR, "Too many refs: %d/%d.\n",
sh->nb_refs[L0], sh->nb_refs[L1]);
return AVERROR_INVALIDDATA;
}
sh->rpl_modification_flag[0] = 0;
sh->rpl_modification_flag[1] = 0;
nb_refs = ff_hevc_frame_nb_refs(s);
if (!nb_refs) {
av_log(s->avctx, AV_LOG_ERROR, "Zero refs for a frame with P or B slices.\n");
return AVERROR_INVALIDDATA;
}
if (s->ps.pps->lists_modification_present_flag && nb_refs > 1) {
sh->rpl_modification_flag[0] = get_bits1(gb);
if (sh->rpl_modification_flag[0]) {
for (i = 0; i < sh->nb_refs[L0]; i++)
sh->list_entry_lx[0][i] = get_bits(gb, av_ceil_log2(nb_refs));
}
if (sh->slice_type == HEVC_SLICE_B) {
sh->rpl_modification_flag[1] = get_bits1(gb);
if (sh->rpl_modification_flag[1] == 1)
for (i = 0; i < sh->nb_refs[L1]; i++)
sh->list_entry_lx[1][i] = get_bits(gb, av_ceil_log2(nb_refs));
}
}
if (sh->slice_type == HEVC_SLICE_B)
sh->mvd_l1_zero_flag = get_bits1(gb);
if (s->ps.pps->cabac_init_present_flag)
sh->cabac_init_flag = get_bits1(gb);
else
sh->cabac_init_flag = 0;
sh->collocated_ref_idx = 0;
if (sh->slice_temporal_mvp_enabled_flag) {
sh->collocated_list = L0;
if (sh->slice_type == HEVC_SLICE_B)
sh->collocated_list = !get_bits1(gb);
if (sh->nb_refs[sh->collocated_list] > 1) {
sh->collocated_ref_idx = get_ue_golomb_long(gb);
if (sh->collocated_ref_idx >= sh->nb_refs[sh->collocated_list]) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid collocated_ref_idx: %d.\n",
sh->collocated_ref_idx);
return AVERROR_INVALIDDATA;
}
}
}
if ((s->ps.pps->weighted_pred_flag && sh->slice_type == HEVC_SLICE_P) ||
(s->ps.pps->weighted_bipred_flag && sh->slice_type == HEVC_SLICE_B)) {
int ret = pred_weight_table(s, gb);
if (ret < 0)
return ret;
}
sh->max_num_merge_cand = 5 - get_ue_golomb_long(gb);
if (sh->max_num_merge_cand < 1 || sh->max_num_merge_cand > 5) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid number of merging MVP candidates: %d.\n",
sh->max_num_merge_cand);
return AVERROR_INVALIDDATA;
}
}
sh->slice_qp_delta = get_se_golomb(gb);
if (s->ps.pps->pic_slice_level_chroma_qp_offsets_present_flag) {
sh->slice_cb_qp_offset = get_se_golomb(gb);
sh->slice_cr_qp_offset = get_se_golomb(gb);
} else {
sh->slice_cb_qp_offset = 0;
sh->slice_cr_qp_offset = 0;
}
if (s->ps.pps->chroma_qp_offset_list_enabled_flag)
sh->cu_chroma_qp_offset_enabled_flag = get_bits1(gb);
else
sh->cu_chroma_qp_offset_enabled_flag = 0;
if (s->ps.pps->deblocking_filter_control_present_flag) {
int deblocking_filter_override_flag = 0;
if (s->ps.pps->deblocking_filter_override_enabled_flag)
deblocking_filter_override_flag = get_bits1(gb);
if (deblocking_filter_override_flag) {
sh->disable_deblocking_filter_flag = get_bits1(gb);
if (!sh->disable_deblocking_filter_flag) {
int beta_offset_div2 = get_se_golomb(gb);
int tc_offset_div2 = get_se_golomb(gb) ;
if (beta_offset_div2 < -6 || beta_offset_div2 > 6 ||
tc_offset_div2 < -6 || tc_offset_div2 > 6) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid deblock filter offsets: %d, %d\n",
beta_offset_div2, tc_offset_div2);
return AVERROR_INVALIDDATA;
}
sh->beta_offset = beta_offset_div2 * 2;
sh->tc_offset = tc_offset_div2 * 2;
}
} else {
sh->disable_deblocking_filter_flag = s->ps.pps->disable_dbf;
sh->beta_offset = s->ps.pps->beta_offset;
sh->tc_offset = s->ps.pps->tc_offset;
}
} else {
sh->disable_deblocking_filter_flag = 0;
sh->beta_offset = 0;
sh->tc_offset = 0;
}
if (s->ps.pps->seq_loop_filter_across_slices_enabled_flag &&
(sh->slice_sample_adaptive_offset_flag[0] ||
sh->slice_sample_adaptive_offset_flag[1] ||
!sh->disable_deblocking_filter_flag)) {
sh->slice_loop_filter_across_slices_enabled_flag = get_bits1(gb);
} else {
sh->slice_loop_filter_across_slices_enabled_flag = s->ps.pps->seq_loop_filter_across_slices_enabled_flag;
}
} else if (!s->slice_initialized) {
av_log(s->avctx, AV_LOG_ERROR, "Independent slice segment missing.\n");
return AVERROR_INVALIDDATA;
}
sh->num_entry_point_offsets = 0;
if (s->ps.pps->tiles_enabled_flag || s->ps.pps->entropy_coding_sync_enabled_flag) {
unsigned num_entry_point_offsets = get_ue_golomb_long(gb);
if (num_entry_point_offsets > get_bits_left(gb)) {
av_log(s->avctx, AV_LOG_ERROR, "num_entry_point_offsets %d is invalid\n", num_entry_point_offsets);
return AVERROR_INVALIDDATA;
}
sh->num_entry_point_offsets = num_entry_point_offsets;
if (sh->num_entry_point_offsets > 0) {
int offset_len = get_ue_golomb_long(gb) + 1;
if (offset_len < 1 || offset_len > 32) {
sh->num_entry_point_offsets = 0;
av_log(s->avctx, AV_LOG_ERROR, "offset_len %d is invalid\n", offset_len);
return AVERROR_INVALIDDATA;
}
av_freep(&sh->entry_point_offset);
av_freep(&sh->offset);
av_freep(&sh->size);
sh->entry_point_offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(unsigned));
sh->offset = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));
sh->size = av_malloc_array(sh->num_entry_point_offsets, sizeof(int));
if (!sh->entry_point_offset || !sh->offset || !sh->size) {
sh->num_entry_point_offsets = 0;
av_log(s->avctx, AV_LOG_ERROR, "Failed to allocate memory\n");
return AVERROR(ENOMEM);
}
for (i = 0; i < sh->num_entry_point_offsets; i++) {
unsigned val = get_bits_long(gb, offset_len);
sh->entry_point_offset[i] = val + 1; // +1; // +1 to get the size
}
if (s->threads_number > 1 && (s->ps.pps->num_tile_rows > 1 || s->ps.pps->num_tile_columns > 1)) {
s->enable_parallel_tiles = 0; // TODO: you can enable tiles in parallel here
s->threads_number = 1;
} else
s->enable_parallel_tiles = 0;
} else
s->enable_parallel_tiles = 0;
}
if (s->ps.pps->slice_header_extension_present_flag) {
unsigned int length = get_ue_golomb_long(gb);
if (length*8LL > get_bits_left(gb)) {
av_log(s->avctx, AV_LOG_ERROR, "too many slice_header_extension_data_bytes\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i < length; i++)
skip_bits(gb, 8); // slice_header_extension_data_byte
}
sh->slice_qp = 26U + s->ps.pps->pic_init_qp_minus26 + sh->slice_qp_delta;
if (sh->slice_qp > 51 ||
sh->slice_qp < -s->ps.sps->qp_bd_offset) {
av_log(s->avctx, AV_LOG_ERROR,
"The slice_qp %d is outside the valid range "
"[%d, 51].\n",
sh->slice_qp,
-s->ps.sps->qp_bd_offset);
return AVERROR_INVALIDDATA;
}
sh->slice_ctb_addr_rs = sh->slice_segment_addr;
if (!s->sh.slice_ctb_addr_rs && s->sh.dependent_slice_segment_flag) {
av_log(s->avctx, AV_LOG_ERROR, "Impossible slice segment.\n");
return AVERROR_INVALIDDATA;
}
if (get_bits_left(gb) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Overread slice header by %d bits\n", -get_bits_left(gb));
return AVERROR_INVALIDDATA;
}
s->HEVClc->first_qp_group = !s->sh.dependent_slice_segment_flag;
if (!s->ps.pps->cu_qp_delta_enabled_flag)
s->HEVClc->qp_y = s->sh.slice_qp;
s->slice_initialized = 1;
s->HEVClc->tu.cu_qp_offset_cb = 0;
s->HEVClc->tu.cu_qp_offset_cr = 0;
return 0;
}
Commit Message: avcodec/hevcdec: Avoid only partly skiping duplicate first slices
Fixes: NULL pointer dereference and out of array access
Fixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432
Fixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304
This also fixes the return code for explode mode
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg
Reviewed-by: James Almer <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
Profile* profile = Profile::FromBrowserContext(
rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
BrowsingDataRemover* remover =
BrowsingDataRemover::CreateForUnboundedRange(profile);
int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
}
Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances.
BUG=174943
TEST=Can't post message to CWS. See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12301013
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 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: GLuint GLES2Implementation::GetMaxValueInBufferCHROMIUM(GLuint buffer_id,
GLsizei count,
GLenum type,
GLuint offset) {
GPU_CLIENT_SINGLE_THREAD_CHECK();
GPU_CLIENT_LOG("[" << GetLogPrefix() << "] glGetMaxValueInBufferCHROMIUM("
<< buffer_id << ", " << count << ", "
<< GLES2Util::GetStringGetMaxIndexType(type) << ", "
<< offset << ")");
GLuint result =
GetMaxValueInBufferCHROMIUMHelper(buffer_id, count, type, offset);
GPU_CLIENT_LOG("returned " << result);
CheckGLError();
return result;
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416
Output: | 0 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static v8::Handle<v8::Value> convert4Callback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.convert4");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(d*, , V8d::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8d::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0);
imp->convert4();
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: static int hns_roce_register_device(struct hns_roce_dev *hr_dev)
{
int ret;
struct hns_roce_ib_iboe *iboe = NULL;
struct ib_device *ib_dev = NULL;
struct device *dev = hr_dev->dev;
iboe = &hr_dev->iboe;
spin_lock_init(&iboe->lock);
ib_dev = &hr_dev->ib_dev;
strlcpy(ib_dev->name, "hns_%d", IB_DEVICE_NAME_MAX);
ib_dev->owner = THIS_MODULE;
ib_dev->node_type = RDMA_NODE_IB_CA;
ib_dev->dev.parent = dev;
ib_dev->phys_port_cnt = hr_dev->caps.num_ports;
ib_dev->local_dma_lkey = hr_dev->caps.reserved_lkey;
ib_dev->num_comp_vectors = hr_dev->caps.num_comp_vectors;
ib_dev->uverbs_abi_ver = 1;
ib_dev->uverbs_cmd_mask =
(1ULL << IB_USER_VERBS_CMD_GET_CONTEXT) |
(1ULL << IB_USER_VERBS_CMD_QUERY_DEVICE) |
(1ULL << IB_USER_VERBS_CMD_QUERY_PORT) |
(1ULL << IB_USER_VERBS_CMD_ALLOC_PD) |
(1ULL << IB_USER_VERBS_CMD_DEALLOC_PD) |
(1ULL << IB_USER_VERBS_CMD_REG_MR) |
(1ULL << IB_USER_VERBS_CMD_DEREG_MR) |
(1ULL << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) |
(1ULL << IB_USER_VERBS_CMD_CREATE_CQ) |
(1ULL << IB_USER_VERBS_CMD_DESTROY_CQ) |
(1ULL << IB_USER_VERBS_CMD_CREATE_QP) |
(1ULL << IB_USER_VERBS_CMD_MODIFY_QP) |
(1ULL << IB_USER_VERBS_CMD_QUERY_QP) |
(1ULL << IB_USER_VERBS_CMD_DESTROY_QP);
/* HCA||device||port */
ib_dev->modify_device = hns_roce_modify_device;
ib_dev->query_device = hns_roce_query_device;
ib_dev->query_port = hns_roce_query_port;
ib_dev->modify_port = hns_roce_modify_port;
ib_dev->get_link_layer = hns_roce_get_link_layer;
ib_dev->get_netdev = hns_roce_get_netdev;
ib_dev->query_gid = hns_roce_query_gid;
ib_dev->add_gid = hns_roce_add_gid;
ib_dev->del_gid = hns_roce_del_gid;
ib_dev->query_pkey = hns_roce_query_pkey;
ib_dev->alloc_ucontext = hns_roce_alloc_ucontext;
ib_dev->dealloc_ucontext = hns_roce_dealloc_ucontext;
ib_dev->mmap = hns_roce_mmap;
/* PD */
ib_dev->alloc_pd = hns_roce_alloc_pd;
ib_dev->dealloc_pd = hns_roce_dealloc_pd;
/* AH */
ib_dev->create_ah = hns_roce_create_ah;
ib_dev->query_ah = hns_roce_query_ah;
ib_dev->destroy_ah = hns_roce_destroy_ah;
/* QP */
ib_dev->create_qp = hns_roce_create_qp;
ib_dev->modify_qp = hns_roce_modify_qp;
ib_dev->query_qp = hr_dev->hw->query_qp;
ib_dev->destroy_qp = hr_dev->hw->destroy_qp;
ib_dev->post_send = hr_dev->hw->post_send;
ib_dev->post_recv = hr_dev->hw->post_recv;
/* CQ */
ib_dev->create_cq = hns_roce_ib_create_cq;
ib_dev->modify_cq = hr_dev->hw->modify_cq;
ib_dev->destroy_cq = hns_roce_ib_destroy_cq;
ib_dev->req_notify_cq = hr_dev->hw->req_notify_cq;
ib_dev->poll_cq = hr_dev->hw->poll_cq;
/* MR */
ib_dev->get_dma_mr = hns_roce_get_dma_mr;
ib_dev->reg_user_mr = hns_roce_reg_user_mr;
ib_dev->dereg_mr = hns_roce_dereg_mr;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_REREG_MR) {
ib_dev->rereg_user_mr = hns_roce_rereg_user_mr;
ib_dev->uverbs_cmd_mask |= (1ULL << IB_USER_VERBS_CMD_REREG_MR);
}
/* OTHERS */
ib_dev->get_port_immutable = hns_roce_port_immutable;
ret = ib_register_device(ib_dev, NULL);
if (ret) {
dev_err(dev, "ib_register_device failed!\n");
return ret;
}
ret = hns_roce_setup_mtu_mac(hr_dev);
if (ret) {
dev_err(dev, "setup_mtu_mac failed!\n");
goto error_failed_setup_mtu_mac;
}
iboe->nb.notifier_call = hns_roce_netdev_event;
ret = register_netdevice_notifier(&iboe->nb);
if (ret) {
dev_err(dev, "register_netdevice_notifier failed!\n");
goto error_failed_setup_mtu_mac;
}
return 0;
error_failed_setup_mtu_mac:
ib_unregister_device(ib_dev);
return ret;
}
Commit Message: RDMA/hns: Fix init resp when alloc ucontext
The data in resp will be copied from kernel to userspace, thus it needs to
be initialized to zeros to avoid copying uninited stack memory.
Reported-by: Dan Carpenter <[email protected]>
Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space")
Signed-off-by: Yixian Liu <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-665
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 peer_recv_callback(rdpTransport* transport, wStream* s, void* extra)
{
freerdp_peer* client = (freerdp_peer*) extra;
rdpRdp* rdp = client->context->rdp;
switch (rdp->state)
{
case CONNECTION_STATE_INITIAL:
if (!rdp_server_accept_nego(rdp, s))
return -1;
if (rdp->nego->selected_protocol & PROTOCOL_NLA)
{
sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity));
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE);
credssp_free(rdp->nego->transport->credssp);
}
else
{
IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE);
}
break;
case CONNECTION_STATE_NEGO:
if (!rdp_server_accept_mcs_connect_initial(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CONNECT:
if (!rdp_server_accept_mcs_erect_domain_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ERECT_DOMAIN:
if (!rdp_server_accept_mcs_attach_user_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_ATTACH_USER:
if (!rdp_server_accept_mcs_channel_join_request(rdp, s))
return -1;
break;
case CONNECTION_STATE_MCS_CHANNEL_JOIN:
if (rdp->settings->DisableEncryption)
{
if (!rdp_server_accept_client_keys(rdp, s))
return -1;
break;
}
rdp->state = CONNECTION_STATE_ESTABLISH_KEYS;
/* FALLTHROUGH */
case CONNECTION_STATE_ESTABLISH_KEYS:
if (!rdp_server_accept_client_info(rdp, s))
return -1;
IFCALL(client->Capabilities, client);
if (!rdp_send_demand_active(rdp))
return -1;
break;
case CONNECTION_STATE_LICENSE:
if (!rdp_server_accept_confirm_active(rdp, s))
{
/**
* During reactivation sequence the client might sent some input or channel data
* before receiving the Deactivate All PDU. We need to process them as usual.
*/
Stream_SetPosition(s, 0);
return peer_recv_pdu(client, s);
}
break;
case CONNECTION_STATE_ACTIVE:
if (peer_recv_pdu(client, s) < 0)
return -1;
break;
default:
fprintf(stderr, "Invalid state %d\n", rdp->state);
return -1;
}
return 0;
}
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
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: find_referral_tgs(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request,
krb5_principal *krbtgt_princ)
{
krb5_error_code retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
char **realms = NULL, *hostname = NULL;
krb5_data srealm = request->server->realm;
if (!is_referral_req(kdc_active_realm, request))
goto cleanup;
hostname = data2string(krb5_princ_component(kdc_context,
request->server, 1));
if (hostname == NULL) {
retval = ENOMEM;
goto cleanup;
}
/* If the hostname doesn't contain a '.', it's not a FQDN. */
if (strchr(hostname, '.') == NULL)
goto cleanup;
retval = krb5_get_host_realm(kdc_context, hostname, &realms);
if (retval) {
/* no match found */
kdc_err(kdc_context, retval, "unable to find realm of host");
goto cleanup;
}
/* Don't return a referral to the empty realm or the service realm. */
if (realms == NULL || realms[0] == '\0' ||
data_eq_string(srealm, realms[0])) {
retval = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto cleanup;
}
retval = krb5_build_principal(kdc_context, krbtgt_princ,
srealm.length, srealm.data,
"krbtgt", realms[0], (char *)0);
cleanup:
krb5_free_host_realm(kdc_context, realms);
free(hostname);
return retval;
}
Commit Message: KDC null deref due to referrals [CVE-2013-1417]
An authenticated remote client can cause a KDC to crash by making a
valid TGS-REQ to a KDC serving a realm with a single-component name.
The process_tgs_req() function dereferences a null pointer because an
unusual failure condition causes a helper function to return success.
While attempting to provide cross-realm referrals for host-based
service principals, the find_referral_tgs() function could return a
TGS principal for a zero-length realm name (indicating that the
hostname in the service principal has no known realm associated with
it).
Subsequently, the find_alternate_tgs() function would attempt to
construct a path to this empty-string realm, and return success along
with a null pointer in its output parameter. This happens because
krb5_walk_realm_tree() returns a list of length one when it attempts
to construct a transit path between a single-component realm and the
empty-string realm. This list causes a loop in find_alternate_tgs()
to iterate over zero elements, resulting in the unexpected output of a
null pointer, which process_tgs_req() proceeds to dereference because
there is no error condition.
Add an error condition to find_referral_tgs() when
krb5_get_host_realm() returns an empty realm name. Also add an error
condition to find_alternate_tgs() to handle the length-one output from
krb5_walk_realm_tree().
The vulnerable configuration is not likely to arise in practice.
(Realm names that have a single component are likely to be test
realms.) Releases prior to krb5-1.11 are not vulnerable.
Thanks to Sol Jerome for reporting this problem.
CVSSv2: AV:N/AC:M/Au:S/C:N/I:N/A:P/E:H/RL:O/RC:C
(cherry picked from commit 3c7f1c21ffaaf6c90f1045f0f5440303c766acc0)
ticket: 7668
version_fixed: 1.11.4
status: resolved
CWE ID: CWE-20
Target: 1
Example 2:
Code: static bool func_states_equal(struct bpf_func_state *old,
struct bpf_func_state *cur)
{
struct idpair *idmap;
bool ret = false;
int i;
idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
/* If we failed to allocate the idmap, just say it's not safe */
if (!idmap)
return false;
for (i = 0; i < MAX_BPF_REG; i++) {
if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
goto out_free;
}
if (!stacksafe(old, cur, idmap))
goto out_free;
if (!refsafe(old, cur))
goto out_free;
ret = true;
out_free:
kfree(idmap);
return ret;
}
Commit Message: bpf: fix sanitation of alu op with pointer / scalar type from different paths
While 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer
arithmetic") took care of rejecting alu op on pointer when e.g. pointer
came from two different map values with different map properties such as
value size, Jann reported that a case was not covered yet when a given
alu op is used in both "ptr_reg += reg" and "numeric_reg += reg" from
different branches where we would incorrectly try to sanitize based
on the pointer's limit. Catch this corner case and reject the program
instead.
Fixes: 979d63d50c0c ("bpf: prevent out of bounds speculation on pointer arithmetic")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Alexei Starovoitov <[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: ModuleExport MagickBooleanType ReadPSDLayers(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,
const MagickBooleanType skip_layers,ExceptionInfo *exception)
{
char
type[4];
LayerInfo
*layer_info;
MagickSizeType
size;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
count,
j,
number_layers;
size=GetPSDSize(psd_info,image);
if (size == 0)
{
/*
Skip layers & masks.
*/
(void) ReadBlobLong(image);
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
status=MagickFalse;
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
return(MagickTrue);
else
{
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0))
size=GetPSDSize(psd_info,image);
else
return(MagickTrue);
}
}
status=MagickTrue;
if (size != 0)
{
layer_info=(LayerInfo *) NULL;
number_layers=(short) ReadBlobShort(image);
if (number_layers < 0)
{
/*
The first alpha channel in the merged result contains the
transparency data for the merged result.
*/
number_layers=MagickAbsoluteValue(number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" negative layer count corrected for");
image->matte=MagickTrue;
}
/*
We only need to know if the image has an alpha channel
*/
if (skip_layers != MagickFalse)
return(MagickTrue);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image contains %.20g layers",(double) number_layers);
if (number_layers == 0)
ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers",
image->filename);
layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers,
sizeof(*layer_info));
if (layer_info == (LayerInfo *) NULL)
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of LayerInfo failed");
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) ResetMagickMemory(layer_info,0,(size_t) number_layers*
sizeof(*layer_info));
for (i=0; i < number_layers; i++)
{
ssize_t
x,
y;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading layer #%.20g",(double) i+1);
layer_info[i].page.y=ReadBlobSignedLong(image);
layer_info[i].page.x=ReadBlobSignedLong(image);
y=ReadBlobSignedLong(image);
x=ReadBlobSignedLong(image);
layer_info[i].page.width=(size_t) (x-layer_info[i].page.x);
layer_info[i].page.height=(size_t) (y-layer_info[i].page.y);
layer_info[i].channels=ReadBlobShort(image);
if (layer_info[i].channels > MaxPSDChannels)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded",
image->filename);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g",
(double) layer_info[i].page.x,(double) layer_info[i].page.y,
(double) layer_info[i].page.height,(double)
layer_info[i].page.width,(double) layer_info[i].channels);
for (j=0; j < (ssize_t) layer_info[i].channels; j++)
{
layer_info[i].channel_info[j].type=(short) ReadBlobShort(image);
layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info,
image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" channel[%.20g]: type=%.20g, size=%.20g",(double) j,
(double) layer_info[i].channel_info[j].type,
(double) layer_info[i].channel_info[j].size);
}
count=ReadBlob(image,4,(unsigned char *) type);
ReversePSDString(image,type,4);
if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer type was %.4s instead of 8BIM", type);
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"ImproperImageHeader",
image->filename);
}
(void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey);
ReversePSDString(image,layer_info[i].blendkey,4);
layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
layer_info[i].clipping=(unsigned char) ReadBlobByte(image);
layer_info[i].flags=(unsigned char) ReadBlobByte(image);
layer_info[i].visible=!(layer_info[i].flags & 0x02);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s",
layer_info[i].blendkey,(double) layer_info[i].opacity,
layer_info[i].clipping ? "true" : "false",layer_info[i].flags,
layer_info[i].visible ? "true" : "false");
(void) ReadBlobByte(image); /* filler */
size=ReadBlobLong(image);
if (size != 0)
{
MagickSizeType
combined_length,
length;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer contains additional info");
length=ReadBlobLong(image);
combined_length=length+4;
if (length != 0)
{
/*
Layer mask info.
*/
layer_info[i].mask.page.y=ReadBlobSignedLong(image);
layer_info[i].mask.page.x=ReadBlobSignedLong(image);
layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.y);
layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)-
layer_info[i].mask.page.x);
layer_info[i].mask.background=(unsigned char) ReadBlobByte(
image);
layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image);
if (!(layer_info[i].mask.flags & 0x01))
{
layer_info[i].mask.page.y=layer_info[i].mask.page.y-
layer_info[i].page.y;
layer_info[i].mask.page.x=layer_info[i].mask.page.x-
layer_info[i].page.x;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g",
(double) layer_info[i].mask.page.x,(double)
layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,
(double) layer_info[i].mask.page.height,(double)
((MagickOffsetType) length)-18);
/*
Skip over the rest of the layer mask information.
*/
if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile",
image->filename);
}
}
length=ReadBlobLong(image);
combined_length+=length+4;
if (length != 0)
{
/*
Layer blending ranges info.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer blending ranges: length=%.20g",(double)
((MagickOffsetType) length));
/*
We read it, but don't use it...
*/
for (j=0; j < (ssize_t) length; j+=8)
{
size_t blend_source=ReadBlobLong(image);
size_t blend_dest=ReadBlobLong(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" source(%x), dest(%x)",(unsigned int)
blend_source,(unsigned int) blend_dest);
}
}
/*
Layer name.
*/
length=(MagickSizeType) ReadBlobByte(image);
combined_length+=length+1;
if (length > 0)
(void) ReadBlob(image,(size_t) length++,layer_info[i].name);
layer_info[i].name[length]='\0';
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer name: %s",layer_info[i].name);
if ((length % 4) != 0)
{
length=4-(length % 4);
combined_length+=length;
/* Skip over the padding of the layer name */
if (DiscardBlobBytes(image,length) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
length=(MagickSizeType) size-combined_length;
if (length > 0)
{
unsigned char
*info;
layer_info[i].info=AcquireStringInfo((const size_t) length);
info=GetStringInfoDatum(layer_info[i].info);
(void) ReadBlob(image,(const size_t) length,info);
}
}
}
for (i=0; i < number_layers; i++)
{
if ((layer_info[i].page.width == 0) ||
(layer_info[i].page.height == 0))
{
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" layer data is empty");
continue;
}
/*
Allocate layered image.
*/
layer_info[i].image=CloneImage(image,layer_info[i].page.width,
layer_info[i].page.height,MagickFalse,exception);
if (layer_info[i].image == (Image *) NULL)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" allocation of image for layer %.20g failed",(double) i);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
if (layer_info[i].info != (StringInfo *) NULL)
{
(void) SetImageProfile(layer_info[i].image,"psd:additional-info",
layer_info[i].info);
layer_info[i].info=DestroyStringInfo(layer_info[i].info);
}
}
if (image_info->ping == MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=0; j < layer_info[i].channels; j++)
{
if (DiscardBlobBytes(image,(MagickSizeType)
layer_info[i].channel_info[j].size) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
continue;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" reading data for layer %.20g",(double) i);
status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i],
exception);
if (status == MagickFalse)
break;
status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType)
number_layers);
if (status == MagickFalse)
break;
}
}
if (status != MagickFalse)
{
for (i=0; i < number_layers; i++)
{
if (layer_info[i].image == (Image *) NULL)
{
for (j=i; j < number_layers - 1; j++)
layer_info[j] = layer_info[j+1];
number_layers--;
i--;
}
}
if (number_layers > 0)
{
for (i=0; i < number_layers; i++)
{
if (i > 0)
layer_info[i].image->previous=layer_info[i-1].image;
if (i < (number_layers-1))
layer_info[i].image->next=layer_info[i+1].image;
layer_info[i].image->page=layer_info[i].page;
}
image->next=layer_info[0].image;
layer_info[0].image->previous=image;
}
layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info);
}
else
layer_info=DestroyLayerInfo(layer_info,number_layers);
}
return(status);
}
Commit Message: Fixed memory leak.
CWE ID: CWE-400
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static void set_pixel_format(VncState *vs,
int bits_per_pixel, int depth,
int big_endian_flag, int true_color_flag,
int red_max, int green_max, int blue_max,
int red_shift, int green_shift, int blue_shift)
{
if (!true_color_flag) {
vnc_client_error(vs);
return;
}
vs->client_pf.rmax = red_max;
vs->client_pf.rbits = hweight_long(red_max);
vs->client_pf.rshift = red_shift;
vs->client_pf.bytes_per_pixel = bits_per_pixel / 8;
vs->client_pf.depth = bits_per_pixel == 32 ? 24 : bits_per_pixel;
vs->client_be = big_endian_flag;
set_pixel_conversion(vs);
graphic_hw_invalidate(NULL);
graphic_hw_update(NULL);
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: size_t mptsas_config_ioc_3(MPTSASState *s, uint8_t **data, int address)
{
return MPTSAS_CONFIG_PACK(3, MPI_CONFIG_PAGETYPE_IOC, 0x00,
"*b*b*w");
}
Commit Message:
CWE ID: CWE-20
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int l2cap_parse_conf_req(struct sock *sk, void *data)
{
struct l2cap_pinfo *pi = l2cap_pi(sk);
struct l2cap_conf_rsp *rsp = data;
void *ptr = rsp->data;
void *req = pi->conf_req;
int len = pi->conf_len;
int type, hint, olen;
unsigned long val;
struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC };
u16 mtu = L2CAP_DEFAULT_MTU;
u16 result = L2CAP_CONF_SUCCESS;
BT_DBG("sk %p", sk);
while (len >= L2CAP_CONF_OPT_SIZE) {
len -= l2cap_get_conf_opt(&req, &type, &olen, &val);
hint = type & L2CAP_CONF_HINT;
type &= L2CAP_CONF_MASK;
switch (type) {
case L2CAP_CONF_MTU:
mtu = val;
break;
case L2CAP_CONF_FLUSH_TO:
pi->flush_to = val;
break;
case L2CAP_CONF_QOS:
break;
case L2CAP_CONF_RFC:
if (olen == sizeof(rfc))
memcpy(&rfc, (void *) val, olen);
break;
default:
if (hint)
break;
result = L2CAP_CONF_UNKNOWN;
*((u8 *) ptr++) = type;
break;
}
}
if (result == L2CAP_CONF_SUCCESS) {
/* Configure output options and let the other side know
* which ones we don't like. */
if (rfc.mode == L2CAP_MODE_BASIC) {
if (mtu < pi->omtu)
result = L2CAP_CONF_UNACCEPT;
else {
pi->omtu = mtu;
pi->conf_state |= L2CAP_CONF_OUTPUT_DONE;
}
l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu);
} else {
result = L2CAP_CONF_UNACCEPT;
memset(&rfc, 0, sizeof(rfc));
rfc.mode = L2CAP_MODE_BASIC;
l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC,
sizeof(rfc), (unsigned long) &rfc);
}
}
rsp->scid = cpu_to_le16(pi->dcid);
rsp->result = cpu_to_le16(result);
rsp->flags = cpu_to_le16(0x0000);
return ptr - data;
}
Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode
Add support to config_req and config_rsp to configure ERTM and Streaming
mode. If the remote device specifies ERTM or Streaming mode, then the
same mode is proposed. Otherwise ERTM or Basic mode is used. And in case
of a state 2 device, the remote device should propose the same mode. If
not, then the channel gets disconnected.
Signed-off-by: Gustavo F. Padovan <[email protected]>
Signed-off-by: Marcel Holtmann <[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: asn1_get_bit_der (const unsigned char *der, int der_len,
int *ret_len, unsigned char *str, int str_size,
int *bit_len)
{
int len_len, len_byte;
if (der_len <= 0)
return ASN1_GENERIC_ERROR;
len_byte = asn1_get_length_der (der, der_len, &len_len) - 1;
if (len_byte < 0)
return ASN1_DER_ERROR;
*ret_len = len_byte + len_len + 1;
*bit_len = len_byte * 8 - der[len_len];
if (str_size >= len_byte)
memcpy (str, der + len_len + 1, len_byte);
}
Commit Message:
CWE ID: CWE-189
Target: 1
Example 2:
Code: gx_dc_pattern_write_raster(gx_color_tile *ptile, int64_t offset, byte *data,
uint *psize, const gx_device *dev)
{
int size_b, size_c;
byte *dp = data;
int left = *psize;
int64_t offset1 = offset;
size_b = sizeof(gx_strip_bitmap) +
ptile->tbits.size.y * ptile->tbits.raster * ptile->tbits.num_planes;
size_c = ptile->tmask.data ? sizeof(gx_strip_bitmap) + ptile->tmask.size.y * ptile->tmask.raster : 0;
if (data == NULL) {
*psize = sizeof(gx_dc_serialized_tile_t) + size_b + size_c;
return 0;
}
if (offset1 == 0) { /* Serialize tile parameters: */
#if defined(DEBUG) || defined(PACIFY_VALGRIND) || defined(MEMENTO)
gx_dc_serialized_tile_t buf = { 0 };
gx_strip_bitmap buf1 = { 0 };
#else
gx_dc_serialized_tile_t buf;
gx_strip_bitmap buf1;
#endif
buf.id = ptile->id;
buf.size.x = 0; /* fixme: don't write with raster patterns. */
buf.size.y = 0; /* fixme: don't write with raster patterns. */
buf.size_b = size_b;
buf.size_c = size_c;
buf.step_matrix = ptile->step_matrix;
buf.bbox = ptile->bbox;
buf.flags = ptile->depth
| (ptile->tiling_type<<TILE_TYPE_SHIFT)
| (ptile->is_simple ? TILE_IS_SIMPLE : 0)
| (ptile->has_overlap ? TILE_HAS_OVERLAP : 0);
if (sizeof(buf) > left) {
/* For a while we require the client to provide enough buffer size. */
return_error(gs_error_unregistered); /* Must not happen. */
}
memcpy(dp, &buf, sizeof(buf));
left -= sizeof(buf);
dp += sizeof(buf);
offset1 += sizeof(buf);
buf1 = ptile->tbits;
buf1.data = NULL; /* fixme: we don't need to write it actually. */
if (sizeof(buf1) > left) {
/* For a while we require the client to provide enough buffer size. */
return_error(gs_error_unregistered); /* Must not happen. */
}
memcpy(dp, &buf1, sizeof(buf1));
left -= sizeof(buf1);
dp += sizeof(buf1);
offset1 += sizeof(buf1);
}
if (offset1 <= sizeof(gx_dc_serialized_tile_t) + size_b) {
int l = min((size_b - sizeof(gx_strip_bitmap)) - (offset1 - sizeof(gx_dc_serialized_tile_t) - sizeof(gx_strip_bitmap)), left);
memcpy(dp, ptile->tbits.data + (offset1 - sizeof(gx_dc_serialized_tile_t) - sizeof(gx_strip_bitmap)), l);
left -= l;
dp += l;
offset1 += l;
}
if (left == 0)
return 0;
if (size_c == 0)
return 0;
if (offset1 <= sizeof(gx_dc_serialized_tile_t) + size_b + sizeof(gx_strip_bitmap)) {
gx_strip_bitmap buf;
if (left < sizeof(buf))
return_error(gs_error_unregistered); /* Not implemented yet because cmd_put_drawing_color provides a big buffer. */
buf = ptile->tmask;
buf.data = NULL; /* fixme: we don't need to write it actually. */
memcpy(dp, &buf, sizeof(buf));
left -= sizeof(buf);
dp += sizeof(buf);
offset1 += sizeof(buf);
}
if (offset1 <= sizeof(gx_dc_serialized_tile_t) + size_b + size_c) {
int l = min(size_c - sizeof(gx_strip_bitmap), left);
memcpy(dp, ptile->tmask.data + (offset1 - sizeof(gx_dc_serialized_tile_t) - size_b - sizeof(gx_strip_bitmap)), l);
}
return 0;
}
Commit Message:
CWE ID: CWE-704
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void WebRuntimeFeatures::enableMediaCapture(bool enable)
{
RuntimeEnabledFeatures::setMediaCaptureEnabled(enable);
}
Commit Message: Remove SpeechSynthesis runtime flag (status=stable)
BUG=402536
Review URL: https://codereview.chromium.org/482273005
git-svn-id: svn://svn.chromium.org/blink/trunk@180763 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-94
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(pg_trace)
{
char *z_filename, *mode = "w";
int z_filename_len, mode_len;
zval *pgsql_link = NULL;
int id = -1, argc = ZEND_NUM_ARGS();
PGconn *pgsql;
FILE *fp = NULL;
php_stream *stream;
id = PGG(default_link);
if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) {
return;
}
if (argc < 3) {
CHECK_DEFAULT_LINK(id);
}
if (pgsql_link == NULL && id == -1) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink);
stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL);
if (!stream) {
RETURN_FALSE;
}
if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) {
php_stream_close(stream);
RETURN_FALSE;
}
php_stream_auto_cleanup(stream);
PQtrace(pgsql, fp);
RETURN_TRUE;
}
Commit Message:
CWE ID: CWE-254
Target: 1
Example 2:
Code: void CameraClient::stopRecording() {
LOG1("stopRecording (pid %d)", getCallingPid());
Mutex::Autolock lock(mLock);
if (checkPidAndHardware() != NO_ERROR) return;
disableMsgType(CAMERA_MSG_VIDEO_FRAME);
mHardware->stopRecording();
mCameraService->playSound(CameraService::SOUND_RECORDING);
mPreviewBuffer.clear();
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264
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 inline bool is_debug(u32 intr_info)
{
return is_exception_n(intr_info, DB_VECTOR);
}
Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF)
When L2 exits to L0 due to "exception or NMI", software exceptions
(#BP and #OF) for which L1 has requested an intercept should be
handled by L1 rather than L0. Previously, only hardware exceptions
were forwarded to L1.
Signed-off-by: Jim Mattson <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-388
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 lookup1_values(int entries, int dim)
{
int r = (int) floor(exp((float) log((float) entries) / dim));
if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
++r; // floor() to avoid _ftol() when non-CRT
assert(pow((float) r+1, dim) > entries);
assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
return r;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20
Target: 1
Example 2:
Code: int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
unsigned int usage )
{
unsigned int usage_must, usage_may;
unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
| MBEDTLS_X509_KU_DECIPHER_ONLY;
if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
return( 0 );
usage_must = usage & ~may_mask;
if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
usage_may = usage & may_mask;
if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
return( 0 );
}
Commit Message: Improve behaviour on fatal errors
If we didn't walk the whole chain, then there may be any kind of errors in the
part of the chain we didn't check, so setting all flags looks like the safe
thing to do.
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: modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce)
{
if (pm->current_encoding != 0)
*ce = *pm->current_encoding;
else
memset(ce, 0, sizeof *ce);
ce->gamma = pm->current_gamma;
}
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: static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
{
struct usb_device *hdev = hub->hdev;
struct usb_hcd *hcd;
int ret;
int port1;
int status;
bool need_debounce_delay = false;
unsigned delay;
/* Continue a partial initialization */
if (type == HUB_INIT2)
goto init2;
if (type == HUB_INIT3)
goto init3;
/* The superspeed hub except for root hub has to use Hub Depth
* value as an offset into the route string to locate the bits
* it uses to determine the downstream port number. So hub driver
* should send a set hub depth request to superspeed hub after
* the superspeed hub is set configuration in initialization or
* reset procedure.
*
* After a resume, port power should still be on.
* For any other type of activation, turn it on.
*/
if (type != HUB_RESUME) {
if (hdev->parent && hub_is_superspeed(hdev)) {
ret = usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_SET_DEPTH, USB_RT_HUB,
hdev->level - 1, 0, NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (ret < 0)
dev_err(hub->intfdev,
"set hub depth failed\n");
}
/* Speed up system boot by using a delayed_work for the
* hub's initial power-up delays. This is pretty awkward
* and the implementation looks like a home-brewed sort of
* setjmp/longjmp, but it saves at least 100 ms for each
* root hub (assuming usbcore is compiled into the kernel
* rather than as a module). It adds up.
*
* This can't be done for HUB_RESUME or HUB_RESET_RESUME
* because for those activation types the ports have to be
* operational when we return. In theory this could be done
* for HUB_POST_RESET, but it's easier not to.
*/
if (type == HUB_INIT) {
delay = hub_power_on_good_delay(hub);
hub_power_on(hub, false);
INIT_DELAYED_WORK(&hub->init_work, hub_init_func2);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
/* Suppress autosuspend until init is done */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
return; /* Continues at init2: below */
} else if (type == HUB_RESET_RESUME) {
/* The internal host controller state for the hub device
* may be gone after a host power loss on system resume.
* Update the device's info so the HW knows it's a hub.
*/
hcd = bus_to_hcd(hdev->bus);
if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_NOIO);
if (ret < 0) {
dev_err(hub->intfdev, "Host not "
"accepting hub info "
"update.\n");
dev_err(hub->intfdev, "LS/FS devices "
"and hubs may not work "
"under this hub\n.");
}
}
hub_power_on(hub, true);
} else {
hub_power_on(hub, true);
}
}
init2:
/*
* Check each port and set hub->change_bits to let hub_wq know
* which ports need attention.
*/
for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
struct usb_port *port_dev = hub->ports[port1 - 1];
struct usb_device *udev = port_dev->child;
u16 portstatus, portchange;
portstatus = portchange = 0;
status = hub_port_status(hub, port1, &portstatus, &portchange);
if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
dev_dbg(&port_dev->dev, "status %04x change %04x\n",
portstatus, portchange);
/*
* After anything other than HUB_RESUME (i.e., initialization
* or any sort of reset), every port should be disabled.
* Unconnected ports should likewise be disabled (paranoia),
* and so should ports for which we have no usb_device.
*/
if ((portstatus & USB_PORT_STAT_ENABLE) && (
type != HUB_RESUME ||
!(portstatus & USB_PORT_STAT_CONNECTION) ||
!udev ||
udev->state == USB_STATE_NOTATTACHED)) {
/*
* USB3 protocol ports will automatically transition
* to Enabled state when detect an USB3.0 device attach.
* Do not disable USB3 protocol ports, just pretend
* power was lost
*/
portstatus &= ~USB_PORT_STAT_ENABLE;
if (!hub_is_superspeed(hdev))
usb_clear_port_feature(hdev, port1,
USB_PORT_FEAT_ENABLE);
}
/* Clear status-change flags; we'll debounce later */
if (portchange & USB_PORT_STAT_C_CONNECTION) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
}
if (portchange & USB_PORT_STAT_C_RESET) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_RESET);
}
if ((portchange & USB_PORT_STAT_C_BH_RESET) &&
hub_is_superspeed(hub->hdev)) {
need_debounce_delay = true;
usb_clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_BH_PORT_RESET);
}
/* We can forget about a "removed" device when there's a
* physical disconnect or the connect status changes.
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (!udev || udev->state == USB_STATE_NOTATTACHED) {
/* Tell hub_wq to disconnect the device or
* check for a new connection
*/
if (udev || (portstatus & USB_PORT_STAT_CONNECTION) ||
(portstatus & USB_PORT_STAT_OVERCURRENT))
set_bit(port1, hub->change_bits);
} else if (portstatus & USB_PORT_STAT_ENABLE) {
bool port_resumed = (portstatus &
USB_PORT_STAT_LINK_STATE) ==
USB_SS_PORT_LS_U0;
/* The power session apparently survived the resume.
* If there was an overcurrent or suspend change
* (i.e., remote wakeup request), have hub_wq
* take care of it. Look at the port link state
* for USB 3.0 hubs, since they don't have a suspend
* change bit, and they don't set the port link change
* bit on device-initiated resume.
*/
if (portchange || (hub_is_superspeed(hub->hdev) &&
port_resumed))
set_bit(port1, hub->change_bits);
} else if (udev->persist_enabled) {
#ifdef CONFIG_PM
udev->reset_resume = 1;
#endif
/* Don't set the change_bits when the device
* was powered off.
*/
if (test_bit(port1, hub->power_bits))
set_bit(port1, hub->change_bits);
} else {
/* The power session is gone; tell hub_wq */
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
set_bit(port1, hub->change_bits);
}
}
/* If no port-status-change flags were set, we don't need any
* debouncing. If flags were set we can try to debounce the
* ports all at once right now, instead of letting hub_wq do them
* one at a time later on.
*
* If any port-status changes do occur during this delay, hub_wq
* will see them later and handle them normally.
*/
if (need_debounce_delay) {
delay = HUB_DEBOUNCE_STABLE;
/* Don't do a long sleep inside a workqueue routine */
if (type == HUB_INIT2) {
INIT_DELAYED_WORK(&hub->init_work, hub_init_func3);
queue_delayed_work(system_power_efficient_wq,
&hub->init_work,
msecs_to_jiffies(delay));
return; /* Continues at init3: below */
} else {
msleep(delay);
}
}
init3:
hub->quiescing = 0;
status = usb_submit_urb(hub->urb, GFP_NOIO);
if (status < 0)
dev_err(hub->intfdev, "activate --> %d\n", status);
if (hub->has_indicators && blinkenlights)
queue_delayed_work(system_power_efficient_wq,
&hub->leds, LED_CYCLE_PERIOD);
/* Scan all ports that need attention */
kick_hub_wq(hub);
/* Allow autosuspend if it was suppressed */
if (type <= HUB_INIT3)
usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
}
Commit Message: USB: fix invalid memory access in hub_activate()
Commit 8520f38099cc ("USB: change hub initialization sleeps to
delayed_work") changed the hub_activate() routine to make part of it
run in a workqueue. However, the commit failed to take a reference to
the usb_hub structure or to lock the hub interface while doing so. As
a result, if a hub is plugged in and quickly unplugged before the work
routine can run, the routine will try to access memory that has been
deallocated. Or, if the hub is unplugged while the routine is
running, the memory may be deallocated while it is in active use.
This patch fixes the problem by taking a reference to the usb_hub at
the start of hub_activate() and releasing it at the end (when the work
is finished), and by locking the hub interface while the work routine
is running. It also adds a check at the start of the routine to see
if the hub has already been disconnected, in which nothing should be
done.
Signed-off-by: Alan Stern <[email protected]>
Reported-by: Alexandru Cornea <[email protected]>
Tested-by: Alexandru Cornea <[email protected]>
Fixes: 8520f38099cc ("USB: change hub initialization sleeps to delayed_work")
CC: <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void CL_InitServerInfo( serverInfo_t *server, netadr_t *address ) {
server->adr = *address;
server->clients = 0;
server->hostName[0] = '\0';
server->mapName[0] = '\0';
server->maxClients = 0;
server->maxPing = 0;
server->minPing = 0;
server->ping = -1;
server->game[0] = '\0';
server->gameType = 0;
server->netType = 0;
server->allowAnonymous = 0;
server->friendlyFire = 0; // NERVE - SMF
server->maxlives = 0; // NERVE - SMF
server->tourney = 0; // NERVE - SMF
server->punkbuster = 0; // DHM - Nerve
server->gameName[0] = '\0'; // Arnout
server->antilag = 0;
server->g_humanplayers = 0;
server->g_needpass = 0;
}
Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s
CWE ID: CWE-269
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: my_object_emit_signals (MyObject *obj, GError **error)
{
GValue val = {0, };
g_signal_emit (obj, signals[SIG0], 0, "foo", 22, "moo");
g_value_init (&val, G_TYPE_STRING);
g_value_set_string (&val, "bar");
g_signal_emit (obj, signals[SIG1], 0, "baz", &val);
g_value_unset (&val);
return TRUE;
}
Commit Message:
CWE ID: CWE-264
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: void mca_ccb_hdl_req(tMCA_CCB* p_ccb, tMCA_CCB_EVT* p_data) {
BT_HDR* p_pkt = &p_data->hdr;
uint8_t *p, *p_start;
tMCA_DCB* p_dcb;
tMCA_CTRL evt_data;
tMCA_CCB_MSG* p_rx_msg = NULL;
uint8_t reject_code = MCA_RSP_NO_RESOURCE;
bool send_rsp = false;
bool check_req = false;
uint8_t reject_opcode;
MCA_TRACE_DEBUG("mca_ccb_hdl_req status:%d", p_ccb->status);
p_rx_msg = (tMCA_CCB_MSG*)p_pkt;
p = (uint8_t*)(p_pkt + 1) + p_pkt->offset;
evt_data.hdr.op_code = *p++;
BE_STREAM_TO_UINT16(evt_data.hdr.mdl_id, p);
reject_opcode = evt_data.hdr.op_code + 1;
MCA_TRACE_DEBUG("received mdl id: %d ", evt_data.hdr.mdl_id);
if (p_ccb->status == MCA_CCB_STAT_PENDING) {
MCA_TRACE_DEBUG("received req inpending state");
/* allow abort in pending state */
if ((p_ccb->status == MCA_CCB_STAT_PENDING) &&
(evt_data.hdr.op_code == MCA_OP_MDL_ABORT_REQ)) {
reject_code = MCA_RSP_SUCCESS;
send_rsp = true;
/* clear the pending status */
p_ccb->status = MCA_CCB_STAT_NORM;
if (p_ccb->p_tx_req &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
osi_free_and_reset((void**)&p_ccb->p_tx_req);
}
} else
reject_code = MCA_RSP_BAD_OP;
} else if (p_ccb->p_rx_msg) {
MCA_TRACE_DEBUG("still handling prev req");
/* still holding previous message, reject this new one ?? */
} else if (p_ccb->p_tx_req) {
MCA_TRACE_DEBUG("still waiting for a response ctrl_vpsm:0x%x",
p_ccb->ctrl_vpsm);
/* sent a request; waiting for response */
if (p_ccb->ctrl_vpsm == 0) {
MCA_TRACE_DEBUG("local is ACP. accept the cmd from INT");
/* local is acceptor, need to handle the request */
check_req = true;
reject_code = MCA_RSP_SUCCESS;
/* drop the previous request */
if ((p_ccb->p_tx_req->op_code == MCA_OP_MDL_CREATE_REQ) &&
((p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx)) != NULL)) {
mca_dcb_dealloc(p_dcb, NULL);
}
osi_free_and_reset((void**)&p_ccb->p_tx_req);
mca_stop_timer(p_ccb);
} else {
/* local is initiator, ignore the req */
osi_free(p_pkt);
return;
}
} else if (p_pkt->layer_specific != MCA_RSP_SUCCESS) {
reject_code = (uint8_t)p_pkt->layer_specific;
if (((evt_data.hdr.op_code >= MCA_NUM_STANDARD_OPCODE) &&
(evt_data.hdr.op_code < MCA_FIRST_SYNC_OP)) ||
(evt_data.hdr.op_code > MCA_LAST_SYNC_OP)) {
/* invalid op code */
reject_opcode = MCA_OP_ERROR_RSP;
evt_data.hdr.mdl_id = 0;
}
} else {
check_req = true;
reject_code = MCA_RSP_SUCCESS;
}
if (check_req) {
if (reject_code == MCA_RSP_SUCCESS) {
reject_code = MCA_RSP_BAD_MDL;
if (MCA_IS_VALID_MDL_ID(evt_data.hdr.mdl_id) ||
((evt_data.hdr.mdl_id == MCA_ALL_MDL_ID) &&
(evt_data.hdr.op_code == MCA_OP_MDL_DELETE_REQ))) {
reject_code = MCA_RSP_SUCCESS;
/* mdl_id is valid according to the spec */
switch (evt_data.hdr.op_code) {
case MCA_OP_MDL_CREATE_REQ:
evt_data.create_ind.dep_id = *p++;
evt_data.create_ind.cfg = *p++;
p_rx_msg->mdep_id = evt_data.create_ind.dep_id;
if (!mca_is_valid_dep_id(p_ccb->p_rcb, p_rx_msg->mdep_id)) {
MCA_TRACE_ERROR("%s: Invalid local MDEP ID %d", __func__,
p_rx_msg->mdep_id);
reject_code = MCA_RSP_BAD_MDEP;
} else if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_DEBUG("the mdl_id is currently used in the CL(create)");
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
} else {
/* check if this dep still have MDL available */
if (mca_dep_free_mdl(p_ccb, evt_data.create_ind.dep_id) == 0) {
MCA_TRACE_ERROR("%s: MAX_MDL is used by MDEP %d", __func__,
evt_data.create_ind.dep_id);
reject_code = MCA_RSP_MDEP_BUSY;
}
}
break;
case MCA_OP_MDL_RECONNECT_REQ:
if (mca_ccb_uses_mdl_id(p_ccb, evt_data.hdr.mdl_id)) {
MCA_TRACE_ERROR("%s: MDL_ID %d busy, in CL(reconn)", __func__,
evt_data.hdr.mdl_id);
reject_code = MCA_RSP_MDL_BUSY;
}
break;
case MCA_OP_MDL_ABORT_REQ:
reject_code = MCA_RSP_BAD_OP;
break;
case MCA_OP_MDL_DELETE_REQ:
/* delete the associated mdl */
mca_dcb_close_by_mdl_id(p_ccb, evt_data.hdr.mdl_id);
send_rsp = true;
break;
}
}
}
}
if (((reject_code != MCA_RSP_SUCCESS) &&
(evt_data.hdr.op_code != MCA_OP_SYNC_INFO_IND)) ||
send_rsp) {
BT_HDR* p_buf = (BT_HDR*)osi_malloc(MCA_CTRL_MTU + sizeof(BT_HDR));
p_buf->offset = L2CAP_MIN_OFFSET;
p = p_start = (uint8_t*)(p_buf + 1) + L2CAP_MIN_OFFSET;
*p++ = reject_opcode;
*p++ = reject_code;
bool valid_response = true;
switch (reject_opcode) {
case MCA_OP_ERROR_RSP:
case MCA_OP_MDL_CREATE_RSP:
case MCA_OP_MDL_RECONNECT_RSP:
case MCA_OP_MDL_ABORT_RSP:
case MCA_OP_MDL_DELETE_RSP:
UINT16_TO_BE_STREAM(p, evt_data.hdr.mdl_id);
break;
case MCA_OP_SYNC_CAP_RSP:
memset(p, 0, 7);
p += 7;
break;
case MCA_OP_SYNC_SET_RSP:
memset(p, 0, 14);
p += 14;
break;
default:
MCA_TRACE_ERROR("%s: reject_opcode 0x%02x not recognized", __func__,
reject_opcode);
valid_response = false;
break;
}
if (valid_response) {
p_buf->len = p - p_start;
MCA_TRACE_ERROR("%s: reject_opcode=0x%02x, reject_code=0x%02x, length=%d",
__func__, reject_opcode, reject_code, p_buf->len);
L2CA_DataWrite(p_ccb->lcid, p_buf);
} else {
osi_free(p_buf);
}
}
if (reject_code == MCA_RSP_SUCCESS) {
/* use the received GKI buffer to store information to double check response
* API */
p_rx_msg->op_code = evt_data.hdr.op_code;
p_rx_msg->mdl_id = evt_data.hdr.mdl_id;
p_ccb->p_rx_msg = p_rx_msg;
if (send_rsp) {
osi_free(p_pkt);
p_ccb->p_rx_msg = NULL;
}
mca_ccb_report_event(p_ccb, evt_data.hdr.op_code, &evt_data);
} else
osi_free(p_pkt);
}
Commit Message: Add packet length checks in mca_ccb_hdl_req
Bug: 110791536
Test: manual
Change-Id: Ica5d8037246682fdb190b2747a86ed8d44c2869a
(cherry picked from commit 4de7ccdd914b7a178df9180d15f675b257ea6e02)
CWE ID: CWE-125
Target: 1
Example 2:
Code: static void start_unregistering(struct ctl_table_header *p)
{
/*
* if p->used is 0, nobody will ever touch that entry again;
* we'll eliminate all paths to it before dropping sysctl_lock
*/
if (unlikely(p->used)) {
struct completion wait;
init_completion(&wait);
p->unregistering = &wait;
spin_unlock(&sysctl_lock);
wait_for_completion(&wait);
spin_lock(&sysctl_lock);
} else {
/* anything non-NULL; we'll never dereference it */
p->unregistering = ERR_PTR(-EINVAL);
}
/*
* do not remove from the list until nobody holds it; walking the
* list in do_sysctl() relies on that.
*/
list_del_init(&p->ctl_entry);
}
Commit Message: sysctl: restrict write access to dmesg_restrict
When dmesg_restrict is set to 1 CAP_SYS_ADMIN is needed to read the kernel
ring buffer. But a root user without CAP_SYS_ADMIN is able to reset
dmesg_restrict to 0.
This is an issue when e.g. LXC (Linux Containers) are used and complete
user space is running without CAP_SYS_ADMIN. A unprivileged and jailed
root user can bypass the dmesg_restrict protection.
With this patch writing to dmesg_restrict is only allowed when root has
CAP_SYS_ADMIN.
Signed-off-by: Richard Weinberger <[email protected]>
Acked-by: Dan Rosenberg <[email protected]>
Acked-by: Serge E. Hallyn <[email protected]>
Cc: Eric Paris <[email protected]>
Cc: Kees Cook <[email protected]>
Cc: James Morris <[email protected]>
Cc: Eugene Teo <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[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: ContextualSearchFieldTrial::ContextualSearchFieldTrial()
: is_resolver_url_prefix_cached_(false),
is_surrounding_size_cached_(false),
surrounding_size_(0),
is_icing_surrounding_size_cached_(false),
icing_surrounding_size_(0),
is_send_base_page_url_disabled_cached_(false),
is_send_base_page_url_disabled_(false),
is_decode_mentions_disabled_cached_(false),
is_decode_mentions_disabled_(false),
is_now_on_tap_bar_integration_enabled_cached_(false),
is_now_on_tap_bar_integration_enabled_(false) {}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID:
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 mem_check_range(struct rxe_mem *mem, u64 iova, size_t length)
{
switch (mem->type) {
case RXE_MEM_TYPE_DMA:
return 0;
case RXE_MEM_TYPE_MR:
case RXE_MEM_TYPE_FMR:
return ((iova < mem->iova) ||
((iova + length) > (mem->iova + mem->length))) ?
-EFAULT : 0;
default:
return -EFAULT;
}
}
Commit Message: IB/rxe: Fix mem_check_range integer overflow
Update the range check to avoid integer-overflow in edge case.
Resolves CVE 2016-8636.
Signed-off-by: Eyal Itkin <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Reviewed-by: Leon Romanovsky <[email protected]>
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-190
Target: 1
Example 2:
Code: url_parse::Component UTF8ComponentToUTF16Component(
const std::string& text_utf8,
const url_parse::Component& component_utf8) {
if (component_utf8.len == -1)
return url_parse::Component();
std::string before_component_string =
text_utf8.substr(0, component_utf8.begin);
std::string component_string = text_utf8.substr(component_utf8.begin,
component_utf8.len);
string16 before_component_string_16 = UTF8ToUTF16(before_component_string);
string16 component_string_16 = UTF8ToUTF16(component_string);
url_parse::Component component_16(before_component_string_16.length(),
component_string_16.length());
return component_16;
}
Commit Message: Be a little more careful whether something is an URL or a file path.
BUG=72492
Review URL: http://codereview.chromium.org/7572046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 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 rng_egd_request_entropy(RngBackend *b, size_t size,
EntropyReceiveFunc *receive_entropy,
void *opaque)
{
RngEgd *s = RNG_EGD(b);
RngRequest *req;
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
while (size > 0) {
uint8_t header[2];
req = g_malloc(sizeof(*req));
req->offset = 0;
req->size = size;
req->receive_entropy = receive_entropy;
req->opaque = opaque;
req->data = g_malloc(req->size);
size -= len;
}
s->parent.requests = g_slist_append(s->parent.requests, req);
}
Commit Message:
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: int mainloop(CLIENT *client) {
struct nbd_request request;
struct nbd_reply reply;
gboolean go_on=TRUE;
#ifdef DODBG
int i = 0;
#endif
negotiate(client->net, client, NULL);
DEBUG("Entering request loop!\n");
reply.magic = htonl(NBD_REPLY_MAGIC);
reply.error = 0;
while (go_on) {
char buf[BUFSIZE];
size_t len;
#ifdef DODBG
i++;
printf("%d: ", i);
#endif
readit(client->net, &request, sizeof(request));
request.from = ntohll(request.from);
request.type = ntohl(request.type);
if (request.type==NBD_CMD_DISC) {
msg2(LOG_INFO, "Disconnect request received.");
if (client->server->flags & F_COPYONWRITE) {
if (client->difmap) g_free(client->difmap) ;
close(client->difffile);
unlink(client->difffilename);
free(client->difffilename);
}
go_on=FALSE;
continue;
}
len = ntohl(request.len);
if (request.magic != htonl(NBD_REQUEST_MAGIC))
err("Not enough magic.");
if (len > BUFSIZE + sizeof(struct nbd_reply))
err("Request too big!");
#ifdef DODBG
printf("%s from %llu (%llu) len %d, ", request.type ? "WRITE" :
"READ", (unsigned long long)request.from,
(unsigned long long)request.from / 512, len);
#endif
memcpy(reply.handle, request.handle, sizeof(reply.handle));
if ((request.from + len) > (OFFT_MAX)) {
DEBUG("[Number too large!]");
ERROR(client, reply, EINVAL);
continue;
}
if (((ssize_t)((off_t)request.from + len) > client->exportsize)) {
DEBUG("[RANGE!]");
ERROR(client, reply, EINVAL);
continue;
}
if (request.type==NBD_CMD_WRITE) {
DEBUG("wr: net->buf, ");
readit(client->net, buf, len);
DEBUG("buf->exp, ");
if ((client->server->flags & F_READONLY) ||
(client->server->flags & F_AUTOREADONLY)) {
DEBUG("[WRITE to READONLY!]");
ERROR(client, reply, EPERM);
continue;
}
if (expwrite(request.from, buf, len, client)) {
DEBUG("Write failed: %m" );
ERROR(client, reply, errno);
continue;
}
SEND(client->net, reply);
DEBUG("OK!\n");
continue;
}
/* READ */
DEBUG("exp->buf, ");
if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) {
DEBUG("Read failed: %m");
ERROR(client, reply, errno);
continue;
}
DEBUG("buf->net, ");
memcpy(buf, &reply, sizeof(struct nbd_reply));
writeit(client->net, buf, len + sizeof(struct nbd_reply));
DEBUG("OK!\n");
}
return 0;
}
Commit Message: Fix buffer size checking
Yes, this means we've re-introduced CVE-2005-3534. Sigh.
CWE ID: CWE-119
Target: 1
Example 2:
Code: rb_simple_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
struct ring_buffer *buffer = tr->trace_buffer.buffer;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (buffer) {
mutex_lock(&trace_types_lock);
if (val) {
tracer_tracing_on(tr);
if (tr->current_trace->start)
tr->current_trace->start(tr);
} else {
tracer_tracing_off(tr);
if (tr->current_trace->stop)
tr->current_trace->stop(tr);
}
mutex_unlock(&trace_types_lock);
}
(*ppos)++;
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
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 crypto_pcomp_report(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_comp rpcomp;
snprintf(rpcomp.type, CRYPTO_MAX_ALG_NAME, "%s", "pcomp");
if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS,
sizeof(struct crypto_report_comp), &rpcomp))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix info leaks in report API
Three errors resulting in kernel memory disclosure:
1/ The structures used for the netlink based crypto algorithm report API
are located on the stack. As snprintf() does not fill the remainder of
the buffer with null bytes, those stack bytes will be disclosed to users
of the API. Switch to strncpy() to fix this.
2/ crypto_report_one() does not initialize all field of struct
crypto_user_alg. Fix this to fix the heap info leak.
3/ For the module name we should copy only as many bytes as
module_name() returns -- not as much as the destination buffer could
hold. But the current code does not and therefore copies random data
from behind the end of the module name, as the module name is always
shorter than CRYPTO_MAX_ALG_NAME.
Also switch to use strncpy() to copy the algorithm's name and
driver_name. They are strings, after all.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-310
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 size_t WritePSDChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
Image
*mask;
MagickOffsetType
rows_offset;
size_t
channels,
count,
length,
offset_length;
unsigned char
*compact_pixels;
count=0;
offset_length=0;
rows_offset=0;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(image,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
channels=1;
if (separate == MagickFalse)
{
if (next_image->storage_class != PseudoClass)
{
if (IsImageGray(next_image) == MagickFalse)
channels=next_image->colorspace == CMYKColorspace ? 4 : 3;
if (next_image->alpha_trait != UndefinedPixelTrait)
channels++;
}
rows_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,channels);
offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4));
}
size_offset+=2;
if (next_image->storage_class == PseudoClass)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
IndexQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (IsImageGray(next_image) != MagickFalse)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
GrayQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
length=WritePSDChannel(psd_info,image_info,image,next_image,
RedQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
GreenQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlueQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
if (next_image->colorspace == CMYKColorspace)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
BlackQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
if (next_image->alpha_trait != UndefinedPixelTrait)
{
length=WritePSDChannel(psd_info,image_info,image,next_image,
AlphaQuantum,compact_pixels,rows_offset,separate,exception);
if (separate != MagickFalse)
size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2;
else
rows_offset+=offset_length;
count+=length;
}
}
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (separate != MagickFalse)
{
const char
*property;
property=GetImageArtifact(next_image,"psd:opacity-mask");
if (property != (const char *) NULL)
{
mask=(Image *) GetImageRegistry(ImageRegistryType,property,
exception);
if (mask != (Image *) NULL)
{
if (mask->compression == RLECompression)
{
compact_pixels=AcquireCompactPixels(mask,exception);
if (compact_pixels == (unsigned char *) NULL)
return(0);
}
length=WritePSDChannel(psd_info,image_info,image,mask,
RedQuantum,compact_pixels,rows_offset,MagickTrue,exception);
(void) WritePSDSize(psd_info,image,length,size_offset);
count+=length;
compact_pixels=(unsigned char *) RelinquishMagickMemory(
compact_pixels);
}
}
}
return(count);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350
CWE ID: CWE-787
Target: 1
Example 2:
Code: static int crc32c_intel_setkey(struct crypto_shash *hash, const u8 *key,
unsigned int keylen)
{
u32 *mctx = crypto_shash_ctx(hash);
if (keylen != sizeof(u32)) {
crypto_shash_set_flags(hash, CRYPTO_TFM_RES_BAD_KEY_LEN);
return -EINVAL;
}
*mctx = le32_to_cpup((__le32 *)key);
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
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: ReadUserLogState::ReadUserLogState( void )
: ReadUserLogFileState( )
{
m_update_time = 0;
Reset( RESET_INIT );
}
Commit Message:
CWE ID: CWE-134
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 FidoCableHandshakeHandler::ValidateAuthenticatorHandshakeMessage(
base::span<const uint8_t> response) {
crypto::HMAC hmac(crypto::HMAC::SHA256);
if (!hmac.Init(handshake_key_))
return false;
if (response.size() != kCableAuthenticatorHandshakeMessageSize) {
return false;
}
const auto authenticator_hello = response.first(
kCableAuthenticatorHandshakeMessageSize - kCableHandshakeMacMessageSize);
if (!hmac.VerifyTruncated(
fido_parsing_utils::ConvertToStringPiece(authenticator_hello),
fido_parsing_utils::ConvertToStringPiece(
response.subspan(authenticator_hello.size())))) {
return false;
}
const auto authenticator_hello_cbor =
cbor::CBORReader::Read(authenticator_hello);
if (!authenticator_hello_cbor || !authenticator_hello_cbor->is_map() ||
authenticator_hello_cbor->GetMap().size() != 2) {
return false;
}
const auto authenticator_hello_msg =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(0));
if (authenticator_hello_msg == authenticator_hello_cbor->GetMap().end() ||
!authenticator_hello_msg->second.is_string() ||
authenticator_hello_msg->second.GetString() !=
kCableAuthenticatorHelloMessage) {
return false;
}
const auto authenticator_random_nonce =
authenticator_hello_cbor->GetMap().find(cbor::CBORValue(1));
if (authenticator_random_nonce == authenticator_hello_cbor->GetMap().end() ||
!authenticator_random_nonce->second.is_bytestring() ||
authenticator_random_nonce->second.GetBytestring().size() != 16) {
return false;
}
cable_device_->SetEncryptionData(
GetEncryptionKeyAfterSuccessfulHandshake(
authenticator_random_nonce->second.GetBytestring()),
nonce_);
return true;
}
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657}
CWE ID: CWE-22
Target: 1
Example 2:
Code: visit_corrupt (const bson_iter_t *iter, void *data)
{
*((bool *) data) = true;
}
Commit Message: Fix for CVE-2018-16790 -- Verify bounds before binary length read.
As reported here: https://jira.mongodb.org/browse/CDRIVER-2819,
a heap overread occurs due a failure to correctly verify data
bounds.
In the original check, len - o returns the data left including the
sizeof(l) we just read. Instead, the comparison should check
against the data left NOT including the binary int32, i.e. just
subtype (byte*) instead of int32 subtype (byte*).
Added in test for corrupted BSON example.
CWE ID: CWE-125
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 ImageCapture::ResolveWithMediaTrackConstraints(
MediaTrackConstraints constraints,
ScriptPromiseResolver* resolver) {
DCHECK(resolver);
resolver->Resolve(constraints);
}
Commit Message: Convert MediaTrackConstraints to a ScriptValue
IDLDictionaries such as MediaTrackConstraints should not be stored on
the heap which would happen when binding one as a parameter to a
callback. This change converts the object to a ScriptValue ahead of
time. This is fine because the value will be passed to a
ScriptPromiseResolver that will converted it to a V8 value if it
isn't already.
Bug: 759457
Change-Id: I3009a0f7711cc264aeaae07a36c18a6db8c915c8
Reviewed-on: https://chromium-review.googlesource.com/701358
Reviewed-by: Kentaro Hara <[email protected]>
Commit-Queue: Reilly Grant <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507177}
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: int vrend_create_shader(struct vrend_context *ctx,
uint32_t handle,
const struct pipe_stream_output_info *so_info,
const char *shd_text, uint32_t offlen, uint32_t num_tokens,
uint32_t type, uint32_t pkt_length)
{
struct vrend_shader_selector *sel = NULL;
int ret_handle;
bool new_shader = true, long_shader = false;
bool finished = false;
int ret;
if (type > PIPE_SHADER_GEOMETRY)
return EINVAL;
if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT)
new_shader = false;
else if (((offlen + 3) / 4) > pkt_length)
long_shader = true;
/* if we have an in progress one - don't allow a new shader
of that type or a different handle. */
if (ctx->sub->long_shader_in_progress_handle[type]) {
if (new_shader == true)
return EINVAL;
if (handle != ctx->sub->long_shader_in_progress_handle[type])
return EINVAL;
}
if (new_shader) {
sel = vrend_create_shader_state(ctx, so_info, type);
if (sel == NULL)
return ENOMEM;
if (long_shader) {
sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */
sel->tmp_buf = malloc(sel->buf_len);
if (!sel->tmp_buf) {
ret = ENOMEM;
goto error;
}
memcpy(sel->tmp_buf, shd_text, pkt_length * 4);
sel->buf_offset = pkt_length * 4;
ctx->sub->long_shader_in_progress_handle[type] = handle;
} else
finished = true;
} else {
sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER);
if (!sel) {
fprintf(stderr, "got continuation without original shader %d\n", handle);
ret = EINVAL;
goto error;
}
offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT;
if (offlen != sel->buf_offset) {
fprintf(stderr, "Got mismatched shader continuation %d vs %d\n",
offlen, sel->buf_offset);
ret = EINVAL;
goto error;
}
if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) {
fprintf(stderr, "Got too large shader continuation %d vs %d\n",
pkt_length * 4 + sel->buf_offset, sel->buf_len);
shd_text = sel->tmp_buf;
}
}
if (finished) {
struct tgsi_token *tokens;
tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token));
if (!tokens) {
ret = ENOMEM;
goto error;
}
if (vrend_dump_shaders)
fprintf(stderr,"shader\n%s\n", shd_text);
if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) {
free(tokens);
ret = EINVAL;
goto error;
}
if (vrend_finish_shader(ctx, sel, tokens)) {
free(tokens);
ret = EINVAL;
goto error;
} else {
free(sel->tmp_buf);
sel->tmp_buf = NULL;
}
free(tokens);
ctx->sub->long_shader_in_progress_handle[type] = 0;
}
if (new_shader) {
ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER);
if (ret_handle == 0) {
ret = ENOMEM;
goto error;
}
}
return 0;
error:
if (new_shader)
vrend_destroy_shader_selector(sel);
else
vrend_renderer_object_destroy(ctx, handle);
return ret;
}
Commit Message:
CWE ID: CWE-190
Target: 1
Example 2:
Code: static int fid_to_qid(V9fsPDU *pdu, V9fsFidState *fidp, V9fsQID *qidp)
{
struct stat stbuf;
int err;
err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);
if (err < 0) {
return err;
}
stat_to_qid(&stbuf, qidp);
return 0;
}
Commit Message:
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: ModuleExport void UnregisterINLINEImage(void)
{
(void) UnregisterMagickInfo("INLINE");
(void) UnregisterMagickInfo("DATA");
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/572
CWE ID: CWE-772
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 CreateOAuth2ServiceDelegate(
signin::AccountConsistencyMethod account_consistency) {
oauth2_service_delegate_.reset(new MutableProfileOAuth2TokenServiceDelegate(
client_.get(), &signin_error_controller_, &account_tracker_service_,
token_web_data_, account_consistency, revoke_all_tokens_on_load_,
true /* can_revoke_credantials */));
base::RunLoop().RunUntilIdle();
oauth2_service_delegate_->AddObserver(this);
}
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: 1
Example 2:
Code: static int rfcomm_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
if (!rfcomm_pi(sk)->channel) {
bdaddr_t *src = &rfcomm_pi(sk)->src;
u8 channel;
err = -EINVAL;
write_lock(&rfcomm_sk_list.lock);
for (channel = 1; channel < 31; channel++)
if (!__rfcomm_get_sock_by_addr(channel, src)) {
rfcomm_pi(sk)->channel = channel;
err = 0;
break;
}
write_unlock(&rfcomm_sk_list.lock);
if (err < 0)
goto done;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
done:
release_sock(sk);
return err;
}
Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic
This patch now always passes msg->msg_namelen as 0. recvmsg handlers must
set msg_namelen to the proper size <= sizeof(struct sockaddr_storage)
to return msg_name to the user.
This prevents numerous uninitialized memory leaks we had in the
recvmsg handlers and makes it harder for new code to accidentally leak
uninitialized memory.
Optimize for the case recvfrom is called with NULL as address. We don't
need to copy the address at all, so set it to NULL before invoking the
recvmsg handler. We can do so, because all the recvmsg handlers must
cope with the case a plain read() is called on them. read() also sets
msg_name to NULL.
Also document these changes in include/linux/net.h as suggested by David
Miller.
Changes since RFC:
Set msg->msg_name = NULL if user specified a NULL in msg_name but had a
non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't
affect sendto as it would bail out earlier while trying to copy-in the
address. It also more naturally reflects the logic by the callers of
verify_iovec.
With this change in place I could remove "
if (!uaddr || msg_sys->msg_namelen == 0)
msg->msg_name = NULL
".
This change does not alter the user visible error logic as we ignore
msg_namelen as long as msg_name is NULL.
Also remove two unnecessary curly brackets in ___sys_recvmsg and change
comments to netdev style.
Cc: David Miller <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20
Target: 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: ~CreateFileResult()
{
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: std::string MakeMediaAccessRequest(int index) {
const int render_process_id = 1;
const int render_frame_id = 1;
const int page_request_id = 1;
const url::Origin security_origin;
MediaStreamManager::MediaAccessRequestCallback callback =
base::BindOnce(&MediaStreamManagerTest::ResponseCallback,
base::Unretained(this), index);
StreamControls controls(true, true);
return media_stream_manager_->MakeMediaAccessRequest(
render_process_id, render_frame_id, page_request_id, controls,
security_origin, std::move(callback));
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int ax25_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sk_buff *skb;
struct sock *newsk;
DEFINE_WAIT(wait);
struct sock *sk;
int err = 0;
if (sock->state != SS_UNCONNECTED)
return -EINVAL;
if ((sk = sock->sk) == NULL)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EOPNOTSUPP;
goto out;
}
if (sk->sk_state != TCP_LISTEN) {
err = -EINVAL;
goto out;
}
/*
* The read queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
if (flags & O_NONBLOCK) {
err = -EWOULDBLOCK;
break;
}
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out;
newsk = skb->sk;
sock_graft(newsk, newsock);
/* Now attach up the new socket */
kfree_skb(skb);
sk->sk_ack_backlog--;
newsock->state = SS_CONNECTED;
out:
release_sock(sk);
return err;
}
Commit Message: ax25: fix info leak via msg_name in ax25_recvmsg()
When msg_namelen is non-zero the sockaddr info gets filled out, as
requested, but the code fails to initialize the padding bytes of struct
sockaddr_ax25 inserted by the compiler for alignment. Additionally the
msg_namelen value is updated to sizeof(struct full_sockaddr_ax25) but is
not always filled up to this size.
Both issues lead to the fact that the code will leak uninitialized
kernel stack bytes in net/socket.c.
Fix both issues by initializing the memory 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: 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: LogLuvClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
*/
td->td_samplesperpixel =
(td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
td->td_bitspersample = 16;
td->td_sampleformat = SAMPLEFORMAT_INT;
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125
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 DebuggerAttachFunction::RunAsync() {
scoped_ptr<Attach::Params> params(Attach::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
CopyDebuggee(&debuggee_, params->target);
if (!InitAgentHost())
return false;
if (!DevToolsHttpHandler::IsSupportedProtocolVersion(
params->required_version)) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kProtocolVersionNotSupportedError,
params->required_version);
return false;
}
if (agent_host_->IsAttached()) {
FormatErrorMessage(keys::kAlreadyAttachedError);
return false;
}
infobars::InfoBar* infobar = NULL;
if (!CommandLine::ForCurrentProcess()->
HasSwitch(switches::kSilentDebuggerExtensionAPI)) {
infobar = ExtensionDevToolsInfoBarDelegate::Create(
agent_host_->GetRenderViewHost(), GetExtension()->name());
if (!infobar) {
error_ = ErrorUtils::FormatErrorMessage(
keys::kSilentDebuggingRequired,
switches::kSilentDebuggerExtensionAPI);
return false;
}
}
new ExtensionDevToolsClientHost(GetProfile(),
agent_host_.get(),
GetExtension()->id(),
GetExtension()->name(),
debuggee_,
infobar);
SendResponse(true);
return true;
}
Commit Message: Have the Debugger extension api check that it has access to the tab
Check PermissionsData::CanAccessTab() prior to attaching the debugger.
BUG=367567
Review URL: https://codereview.chromium.org/352523003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264
Target: 1
Example 2:
Code: make_echo_reply(const struct ofp_header *rq)
{
struct ofpbuf rq_buf = ofpbuf_const_initializer(rq, ntohs(rq->length));
ofpraw_pull_assert(&rq_buf);
struct ofpbuf *reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY,
rq, rq_buf.size);
ofpbuf_put(reply, rq_buf.data, rq_buf.size);
return reply;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: bool omx_vdec::ts_arr_list::pop_min_ts(OMX_TICKS &ts)
{
bool ret = true;
int min_idx = -1;
OMX_TICKS min_ts = 0;
int idx = 0;
for ( ; idx < MAX_NUM_INPUT_OUTPUT_BUFFERS; idx++) {
if (m_ts_arr_list[idx].valid) {
if (min_idx < 0) {
min_ts = m_ts_arr_list[idx].timestamp;
min_idx = idx;
} else if (m_ts_arr_list[idx].timestamp < min_ts) {
min_ts = m_ts_arr_list[idx].timestamp;
min_idx = idx;
}
}
}
if (min_idx < 0) {
DEBUG_PRINT_LOW("Timestamp array list is empty. Unsuccessful pop");
ts = 0;
ret = false;
} else {
ts = m_ts_arr_list[min_idx].timestamp;
m_ts_arr_list[min_idx].valid = false;
DEBUG_PRINT_LOW("Pop_min_ts:Timestamp (%lld), index(%d)",
ts, min_idx);
}
return ret;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
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 jffs2_create(struct inode *dir_i, struct dentry *dentry, int mode,
struct nameidata *nd)
{
struct jffs2_raw_inode *ri;
struct jffs2_inode_info *f, *dir_f;
struct jffs2_sb_info *c;
struct inode *inode;
int ret;
ri = jffs2_alloc_raw_inode();
return -ENOMEM;
c = JFFS2_SB_INFO(dir_i->i_sb);
D1(printk(KERN_DEBUG "jffs2_create()\n"));
inode = jffs2_new_inode(dir_i, mode, ri);
if (IS_ERR(inode)) {
D1(printk(KERN_DEBUG "jffs2_new_inode() failed\n"));
return PTR_ERR(inode);
}
inode->i_op = &jffs2_file_inode_operations;
inode->i_fop = &jffs2_file_operations;
inode->i_mapping->a_ops = &jffs2_file_address_operations;
inode->i_mapping->nrpages = 0;
f = JFFS2_INODE_INFO(inode);
dir_f = JFFS2_INODE_INFO(dir_i);
ret = jffs2_do_create(c, dir_f, f, ri,
dentry->d_name.name, dentry->d_name.len);
dentry->d_name.name, dentry->d_name.len);
if (ret)
goto fail;
ret = jffs2_init_security(inode, dir_i);
if (ret)
goto fail;
ret = jffs2_init_acl(inode, dir_i);
if (ret)
goto fail;
jffs2_free_raw_inode(ri);
d_instantiate(dentry, inode);
D1(printk(KERN_DEBUG "jffs2_create: Created ino #%lu with mode %o, nlink %d(%d). nrpages %ld\n",
inode->i_ino, inode->i_mode, inode->i_nlink, f->inocache->nlink, inode->i_mapping->nrpages));
inode->i_ino, inode->i_mode, inode->i_nlink, f->inocache->nlink, inode->i_mapping->nrpages));
return 0;
fail:
make_bad_inode(inode);
iput(inode);
/***********************************************************************/
static int jffs2_unlink(struct inode *dir_i, struct dentry *dentry)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(dir_i->i_sb);
struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i);
struct jffs2_inode_info *dead_f = JFFS2_INODE_INFO(dentry->d_inode);
int ret;
uint32_t now = get_seconds();
ret = jffs2_do_unlink(c, dir_f, dentry->d_name.name,
dentry->d_name.len, dead_f, now);
if (dead_f->inocache)
dentry->d_inode->i_nlink = dead_f->inocache->nlink;
if (!ret)
dir_i->i_mtime = dir_i->i_ctime = ITIME(now);
return ret;
}
/***********************************************************************/
static int jffs2_link (struct dentry *old_dentry, struct inode *dir_i, struct dentry *dentry)
{
struct jffs2_sb_info *c = JFFS2_SB_INFO(old_dentry->d_inode->i_sb);
struct jffs2_inode_info *f = JFFS2_INODE_INFO(old_dentry->d_inode);
struct jffs2_inode_info *dir_f = JFFS2_INODE_INFO(dir_i);
int ret;
uint8_t type;
uint32_t now;
/* Don't let people make hard links to bad inodes. */
if (!f->inocache)
return -EIO;
if (S_ISDIR(old_dentry->d_inode->i_mode))
return -EPERM;
/* XXX: This is ugly */
type = (old_dentry->d_inode->i_mode & S_IFMT) >> 12;
if (!type) type = DT_REG;
now = get_seconds();
ret = jffs2_do_link(c, dir_f, f->inocache->ino, type, dentry->d_name.name, dentry->d_name.len, now);
if (!ret) {
down(&f->sem);
old_dentry->d_inode->i_nlink = ++f->inocache->nlink;
up(&f->sem);
d_instantiate(dentry, old_dentry->d_inode);
dir_i->i_mtime = dir_i->i_ctime = ITIME(now);
atomic_inc(&old_dentry->d_inode->i_count);
}
return ret;
}
/***********************************************************************/
static int jffs2_symlink (struct inode *dir_i, struct dentry *dentry, const char *target)
{
struct jffs2_inode_info *f, *dir_f;
struct jffs2_sb_info *c;
struct inode *inode;
struct jffs2_raw_inode *ri;
struct jffs2_raw_dirent *rd;
struct jffs2_full_dnode *fn;
struct jffs2_full_dirent *fd;
int namelen;
uint32_t alloclen;
struct jffs2_full_dirent *fd;
int namelen;
uint32_t alloclen;
int ret, targetlen = strlen(target);
/* FIXME: If you care. We'd need to use frags for the target
ri = jffs2_alloc_raw_inode();
if (!ri)
return -ENOMEM;
c = JFFS2_SB_INFO(dir_i->i_sb);
/* Try to reserve enough space for both node and dirent.
* Just the node will do for now, though
*/
namelen = dentry->d_name.len;
ret = jffs2_reserve_space(c, sizeof(*ri) + targetlen, &alloclen,
ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE);
if (ret) {
jffs2_free_raw_inode(ri);
return ret;
}
inode = jffs2_new_inode(dir_i, S_IFLNK | S_IRWXUGO, ri);
return ret;
}
inode = jffs2_new_inode(dir_i, S_IFLNK | S_IRWXUGO, ri);
if (IS_ERR(inode)) {
jffs2_free_raw_inode(ri);
inode->i_op = &jffs2_symlink_inode_operations;
f = JFFS2_INODE_INFO(inode);
inode->i_size = targetlen;
ri->isize = ri->dsize = ri->csize = cpu_to_je32(inode->i_size);
ri->totlen = cpu_to_je32(sizeof(*ri) + inode->i_size);
ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4));
ri->compr = JFFS2_COMPR_NONE;
ri->data_crc = cpu_to_je32(crc32(0, target, targetlen));
ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8));
fn = jffs2_write_dnode(c, f, ri, target, targetlen, ALLOC_NORMAL);
jffs2_free_raw_inode(ri);
if (IS_ERR(fn)) {
/* Eeek. Wave bye bye */
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return PTR_ERR(fn);
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return PTR_ERR(fn);
}
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return -ENOMEM;
}
up(&f->sem);
jffs2_complete_reservation(c);
jffs2_clear_inode(inode);
return -ENOMEM;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: static int jpc_pi_nextrpcl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
int compno;
jpc_picomp_t *picomp;
int xstep;
int ystep;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
uint_fast32_t trx0;
uint_fast32_t try0;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->xstep = 0;
pi->ystep = 0;
for (compno = 0, picomp = pi->picomps; compno < pi->numcomps;
++compno, ++picomp) {
for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <
picomp->numrlvls; ++rlvlno, ++pirlvl) {
xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn +
picomp->numrlvls - rlvlno - 1));
ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn +
picomp->numrlvls - rlvlno - 1));
pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep);
pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep);
}
}
pi->prgvolfirst = 0;
}
for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend &&
pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) {
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->compno = pchg->compnostart,
pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno <
pi->numcomps; ++pi->compno, ++pi->picomp) {
if (pi->rlvlno >= pi->picomp->numrlvls) {
continue;
}
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx)))
|| !(pi->x % (1 << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy)))
|| !(pi->y % (1 << 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 an integer overflow problem in the JPC codec that later resulted
in the use of uninitialized data.
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: AudioRendererHostTest()
: log_factory(base::MakeUnique<media::FakeAudioLogFactory>()),
audio_manager_(base::MakeUnique<FakeAudioManagerWithAssociations>(
base::ThreadTaskRunnerHandle::Get(),
log_factory.get())),
render_process_host_(&browser_context_, &auth_run_loop_) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
media_stream_manager_.reset(new MediaStreamManager(audio_manager_.get()));
host_ = new MockAudioRendererHost(
&auth_run_loop_, render_process_host_.GetID(), audio_manager_.get(),
&mirroring_manager_, media_stream_manager_.get(), kSalt);
host_->set_peer_process_for_testing(base::Process::Current());
}
Commit Message: Switching AudioOutputAuthorizationHandler from using AudioManager interface to AudioSystem one.
BUG=672468
CQ_INCLUDE_TRYBOTS=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
Review-Url: https://codereview.chromium.org/2692203003
Cr-Commit-Position: refs/heads/master@{#450939}
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: int ip_queue_xmit(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
struct inet_sock *inet = inet_sk(sk);
struct ip_options *opt = inet->opt;
struct rtable *rt;
struct iphdr *iph;
int res;
/* Skip all of this if the packet is already routed,
* f.e. by something like SCTP.
*/
rcu_read_lock();
rt = skb_rtable(skb);
if (rt != NULL)
goto packet_routed;
/* Make sure we can route this packet. */
rt = (struct rtable *)__sk_dst_check(sk, 0);
if (rt == NULL) {
__be32 daddr;
/* Use correct destination address if we have options. */
daddr = inet->inet_daddr;
if(opt && opt->srr)
daddr = opt->faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), sk,
daddr, inet->inet_saddr,
inet->inet_dport,
inet->inet_sport,
sk->sk_protocol,
RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
sk_setup_caps(sk, &rt->dst);
}
skb_dst_set_noref(skb, &rt->dst);
packet_routed:
if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway)
goto no_route;
/* OK, we know where to send it, allocate and build IP header. */
skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));
skb_reset_network_header(skb);
iph = ip_hdr(skb);
*((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (inet->tos & 0xff));
if (ip_dont_fragment(sk, &rt->dst) && !skb->local_df)
iph->frag_off = htons(IP_DF);
else
iph->frag_off = 0;
iph->ttl = ip_select_ttl(inet, &rt->dst);
iph->protocol = sk->sk_protocol;
iph->saddr = rt->rt_src;
iph->daddr = rt->rt_dst;
/* Transport layer set skb->h.foo itself. */
if (opt && opt->optlen) {
iph->ihl += opt->optlen >> 2;
ip_options_build(skb, opt, inet->inet_daddr, rt, 0);
}
ip_select_ident_more(iph, &rt->dst, sk,
(skb_shinfo(skb)->gso_segs ?: 1) - 1);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
res = ip_local_out(skb);
rcu_read_unlock();
return res;
no_route:
rcu_read_unlock();
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EHOSTUNREACH;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362
Target: 1
Example 2:
Code: static int bin_pe_init_sections(struct PE_(r_bin_pe_obj_t)* bin) {
bin->num_sections = bin->nt_headers->file_header.NumberOfSections;
int sections_size;
if (bin->num_sections < 1) {
return true;
}
sections_size = sizeof (PE_(image_section_header)) * bin->num_sections;
if (sections_size > bin->size) {
sections_size = bin->size;
bin->num_sections = bin->size / sizeof (PE_(image_section_header));
}
if (!(bin->section_header = malloc (sections_size))) {
r_sys_perror ("malloc (section header)");
goto out_error;
}
bin->section_header_offset = bin->dos_header->e_lfanew + 4 + sizeof (PE_(image_file_header)) +
bin->nt_headers->file_header.SizeOfOptionalHeader;
if (r_buf_read_at (bin->b, bin->section_header_offset,
(ut8*) bin->section_header, sections_size) == -1) {
bprintf ("Warning: read (sections)\n");
R_FREE (bin->section_header);
goto out_error;
}
#if 0
Each symbol table entry includes a name, storage class, type, value and section number.Short names (8 characters or fewer) are stored directly in the symbol table;
longer names are stored as an paddr into the string table at the end of the COFF object.
================================================================
COFF SYMBOL TABLE RECORDS (18 BYTES)
================================================================
record
paddr
struct symrec {
union {
char string[8]; // short name
struct {
ut32 seros;
ut32 stridx;
} stridx;
} name;
ut32 value;
ut16 secnum;
ut16 symtype;
ut8 symclass;
ut8 numaux;
}
------------------------------------------------------ -
0 | 8 - char symbol name |
| or 32 - bit zeroes followed by 32 - bit |
| index into string table |
------------------------------------------------------ -
8 | symbol value |
------------------------------------------------------ -
0Ch | section number | symbol type |
------------------------------------------------------ -
10h | sym class | num aux |
-------------------------- -
12h
#endif
return true;
out_error:
bin->num_sections = 0;
return false;
}
Commit Message: Fix crash in pe
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static int do_zfs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
char *filename = NULL;
int dev;
int part;
ulong addr = 0;
disk_partition_t info;
struct blk_desc *dev_desc;
char buf[12];
unsigned long count;
const char *addr_str;
struct zfs_file zfile;
struct device_s vdev;
if (argc < 3)
return CMD_RET_USAGE;
count = 0;
addr = simple_strtoul(argv[3], NULL, 16);
filename = env_get("bootfile");
switch (argc) {
case 3:
addr_str = env_get("loadaddr");
if (addr_str != NULL)
addr = simple_strtoul(addr_str, NULL, 16);
else
addr = CONFIG_SYS_LOAD_ADDR;
break;
case 4:
break;
case 5:
filename = argv[4];
break;
case 6:
filename = argv[4];
count = simple_strtoul(argv[5], NULL, 16);
break;
default:
return cmd_usage(cmdtp);
}
if (!filename) {
puts("** No boot file defined **\n");
return 1;
}
part = blk_get_device_part_str(argv[1], argv[2], &dev_desc, &info, 1);
if (part < 0)
return 1;
dev = dev_desc->devnum;
printf("Loading file \"%s\" from %s device %d%c%c\n",
filename, argv[1], dev,
part ? ':' : ' ', part ? part + '0' : ' ');
zfs_set_blk_dev(dev_desc, &info);
vdev.part_length = info.size;
memset(&zfile, 0, sizeof(zfile));
zfile.device = &vdev;
if (zfs_open(&zfile, filename)) {
printf("** File not found %s **\n", filename);
return 1;
}
if ((count < zfile.size) && (count != 0))
zfile.size = (uint64_t)count;
if (zfs_read(&zfile, (char *)addr, zfile.size) != zfile.size) {
printf("** Unable to read \"%s\" from %s %d:%d **\n",
filename, argv[1], dev, part);
zfs_close(&zfile);
return 1;
}
zfs_close(&zfile);
/* Loading ok, update default load address */
image_load_addr = addr;
printf("%llu bytes read\n", zfile.size);
env_set_hex("filesize", zfile.size);
return 0;
}
Commit Message: Merge branch '2020-01-22-master-imports'
- Re-add U8500 platform support
- Add bcm968360bg support
- Assorted Keymile fixes
- Other assorted bugfixes
CWE ID: CWE-787
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 NaClProcessHost::OnProcessLaunched() {
FilePath irt_path;
const char* irt_path_var = getenv("NACL_IRT_LIBRARY");
if (irt_path_var != NULL) {
FilePath::StringType string(irt_path_var,
irt_path_var + strlen(irt_path_var));
irt_path = FilePath(string);
} else {
FilePath plugin_dir;
if (!PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &plugin_dir)) {
LOG(ERROR) << "Failed to locate the plugins directory";
delete this;
return;
}
irt_path = plugin_dir.Append(GetIrtLibraryFilename());
}
base::FileUtilProxy::CreateOrOpenCallback* callback =
callback_factory_.NewCallback(&NaClProcessHost::OpenIrtFileDone);
if (!base::FileUtilProxy::CreateOrOpen(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
irt_path,
base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
callback)) {
delete callback;
delete this;
}
}
Commit Message: Fix a small leak in FileUtilProxy
BUG=none
TEST=green mem bots
Review URL: http://codereview.chromium.org/7669046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int kvm_vm_ioctl_set_msix_nr(struct kvm *kvm,
struct kvm_assigned_msix_nr *entry_nr)
{
int r = 0;
struct kvm_assigned_dev_kernel *adev;
mutex_lock(&kvm->lock);
adev = kvm_find_assigned_dev(&kvm->arch.assigned_dev_head,
entry_nr->assigned_dev_id);
if (!adev) {
r = -EINVAL;
goto msix_nr_out;
}
if (adev->entries_nr == 0) {
adev->entries_nr = entry_nr->entry_nr;
if (adev->entries_nr == 0 ||
adev->entries_nr > KVM_MAX_MSIX_PER_DEV) {
r = -EINVAL;
goto msix_nr_out;
}
adev->host_msix_entries = kzalloc(sizeof(struct msix_entry) *
entry_nr->entry_nr,
GFP_KERNEL);
if (!adev->host_msix_entries) {
r = -ENOMEM;
goto msix_nr_out;
}
adev->guest_msix_entries =
kzalloc(sizeof(struct msix_entry) * entry_nr->entry_nr,
GFP_KERNEL);
if (!adev->guest_msix_entries) {
kfree(adev->host_msix_entries);
r = -ENOMEM;
goto msix_nr_out;
}
} else /* Not allowed set MSI-X number twice */
r = -EINVAL;
msix_nr_out:
mutex_unlock(&kvm->lock);
return r;
}
Commit Message: KVM: Device assignment permission checks
(cherry picked from commit 3d27e23b17010c668db311140b17bbbb70c78fb9)
Only allow KVM device assignment to attach to devices which:
- Are not bridges
- Have BAR resources (assume others are special devices)
- The user has permissions to use
Assigning a bridge is a configuration error, it's not supported, and
typically doesn't result in the behavior the user is expecting anyway.
Devices without BAR resources are typically chipset components that
also don't have host drivers. We don't want users to hold such devices
captive or cause system problems by fencing them off into an iommu
domain. We determine "permission to use" by testing whether the user
has access to the PCI sysfs resource files. By default a normal user
will not have access to these files, so it provides a good indication
that an administration agent has granted the user access to the device.
[Yang Bai: add missing #include]
[avi: fix comment style]
Signed-off-by: Alex Williamson <[email protected]>
Signed-off-by: Yang Bai <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[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 CLASS ljpeg_start (struct jhead *jh, int info_only)
{
int c, tag, len;
uchar data[0x10000];
const uchar *dp;
memset (jh, 0, sizeof *jh);
jh->restart = INT_MAX;
fread (data, 2, 1, ifp);
if (data[1] != 0xd8) return 0;
do {
fread (data, 2, 2, ifp);
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00) return 0;
fread (data, 1, len, ifp);
switch (tag) {
case 0xffc3:
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc0:
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version) getc(ifp);
break;
case 0xffc4:
if (info_only) break;
for (dp = data; dp < data+len && (c = *dp++) < 4; )
jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
break;
case 0xffda:
jh->psv = data[1+data[0]*2];
jh->bits -= data[3+data[0]*2] & 15;
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (info_only) return 1;
FORC(5) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
if (jh->sraw) {
FORC(4) jh->huff[2+c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
}
jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
merror (jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
Commit Message: Avoid overflow in ljpeg_start().
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 int decode_frame_common(AVCodecContext *avctx, PNGDecContext *s,
AVFrame *p, AVPacket *avpkt)
{
AVDictionary *metadata = NULL;
uint32_t tag, length;
int decode_next_dat = 0;
int ret;
for (;;) {
length = bytestream2_get_bytes_left(&s->gb);
if (length <= 0) {
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && length == 0) {
if (!(s->state & PNG_IDAT))
return 0;
else
goto exit_loop;
}
av_log(avctx, AV_LOG_ERROR, "%d bytes left\n", length);
if ( s->state & PNG_ALLIMAGE
&& avctx->strict_std_compliance <= FF_COMPLIANCE_NORMAL)
goto exit_loop;
ret = AVERROR_INVALIDDATA;
goto fail;
}
length = bytestream2_get_be32(&s->gb);
if (length > 0x7fffffff || length > bytestream2_get_bytes_left(&s->gb)) {
av_log(avctx, AV_LOG_ERROR, "chunk too big\n");
ret = AVERROR_INVALIDDATA;
goto fail;
}
tag = bytestream2_get_le32(&s->gb);
if (avctx->debug & FF_DEBUG_STARTCODE)
av_log(avctx, AV_LOG_DEBUG, "png: tag=%c%c%c%c length=%u\n",
(tag & 0xff),
((tag >> 8) & 0xff),
((tag >> 16) & 0xff),
((tag >> 24) & 0xff), length);
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
switch(tag) {
case MKTAG('I', 'H', 'D', 'R'):
case MKTAG('p', 'H', 'Y', 's'):
case MKTAG('t', 'E', 'X', 't'):
case MKTAG('I', 'D', 'A', 'T'):
case MKTAG('t', 'R', 'N', 'S'):
break;
default:
goto skip_tag;
}
}
switch (tag) {
case MKTAG('I', 'H', 'D', 'R'):
if ((ret = decode_ihdr_chunk(avctx, s, length)) < 0)
goto fail;
break;
case MKTAG('p', 'H', 'Y', 's'):
if ((ret = decode_phys_chunk(avctx, s)) < 0)
goto fail;
break;
case MKTAG('f', 'c', 'T', 'L'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if ((ret = decode_fctl_chunk(avctx, s, length)) < 0)
goto fail;
decode_next_dat = 1;
break;
case MKTAG('f', 'd', 'A', 'T'):
if (!CONFIG_APNG_DECODER || avctx->codec_id != AV_CODEC_ID_APNG)
goto skip_tag;
if (!decode_next_dat) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_get_be32(&s->gb);
length -= 4;
/* fallthrough */
case MKTAG('I', 'D', 'A', 'T'):
if (CONFIG_APNG_DECODER && avctx->codec_id == AV_CODEC_ID_APNG && !decode_next_dat)
goto skip_tag;
if ((ret = decode_idat_chunk(avctx, s, length, p)) < 0)
goto fail;
break;
case MKTAG('P', 'L', 'T', 'E'):
if (decode_plte_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'R', 'N', 'S'):
if (decode_trns_chunk(avctx, s, length) < 0)
goto skip_tag;
break;
case MKTAG('t', 'E', 'X', 't'):
if (decode_text_chunk(s, length, 0, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken tEXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('z', 'T', 'X', 't'):
if (decode_text_chunk(s, length, 1, &metadata) < 0)
av_log(avctx, AV_LOG_WARNING, "Broken zTXt chunk\n");
bytestream2_skip(&s->gb, length + 4);
break;
case MKTAG('s', 'T', 'E', 'R'): {
int mode = bytestream2_get_byte(&s->gb);
AVStereo3D *stereo3d = av_stereo3d_create_side_data(p);
if (!stereo3d)
goto fail;
if (mode == 0 || mode == 1) {
stereo3d->type = AV_STEREO3D_SIDEBYSIDE;
stereo3d->flags = mode ? 0 : AV_STEREO3D_FLAG_INVERT;
} else {
av_log(avctx, AV_LOG_WARNING,
"Unknown value in sTER chunk (%d)\n", mode);
}
bytestream2_skip(&s->gb, 4); /* crc */
break;
}
case MKTAG('I', 'E', 'N', 'D'):
if (!(s->state & PNG_ALLIMAGE))
av_log(avctx, AV_LOG_ERROR, "IEND without all image\n");
if (!(s->state & (PNG_ALLIMAGE|PNG_IDAT))) {
ret = AVERROR_INVALIDDATA;
goto fail;
}
bytestream2_skip(&s->gb, 4); /* crc */
goto exit_loop;
default:
/* skip tag */
skip_tag:
bytestream2_skip(&s->gb, length + 4);
break;
}
}
exit_loop:
if (avctx->codec_id == AV_CODEC_ID_PNG &&
avctx->skip_frame == AVDISCARD_ALL) {
av_frame_set_metadata(p, metadata);
return 0;
}
if (s->bits_per_pixel <= 4)
handle_small_bpp(s, p);
/* apply transparency if needed */
if (s->has_trns && s->color_type != PNG_COLOR_TYPE_PALETTE) {
size_t byte_depth = s->bit_depth > 8 ? 2 : 1;
size_t raw_bpp = s->bpp - byte_depth;
unsigned x, y;
for (y = 0; y < s->height; ++y) {
uint8_t *row = &s->image_buf[s->image_linesize * y];
/* since we're updating in-place, we have to go from right to left */
for (x = s->width; x > 0; --x) {
uint8_t *pixel = &row[s->bpp * (x - 1)];
memmove(pixel, &row[raw_bpp * (x - 1)], raw_bpp);
if (!memcmp(pixel, s->transparent_color_be, raw_bpp)) {
memset(&pixel[raw_bpp], 0, byte_depth);
} else {
memset(&pixel[raw_bpp], 0xff, byte_depth);
}
}
}
}
/* handle P-frames only if a predecessor frame is available */
if (s->last_picture.f->data[0]) {
if ( !(avpkt->flags & AV_PKT_FLAG_KEY) && avctx->codec_tag != AV_RL32("MPNG")
&& s->last_picture.f->width == p->width
&& s->last_picture.f->height== p->height
&& s->last_picture.f->format== p->format
) {
if (CONFIG_PNG_DECODER && avctx->codec_id != AV_CODEC_ID_APNG)
handle_p_frame_png(s, p);
else if (CONFIG_APNG_DECODER &&
avctx->codec_id == AV_CODEC_ID_APNG &&
(ret = handle_p_frame_apng(avctx, s, p)) < 0)
goto fail;
}
}
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
av_frame_set_metadata(p, metadata);
metadata = NULL;
return 0;
fail:
av_dict_free(&metadata);
ff_thread_report_progress(&s->picture, INT_MAX, 0);
ff_thread_report_progress(&s->previous_picture, INT_MAX, 0);
return ret;
}
Commit Message: avcodec/pngdec: Check trns more completely
Fixes out of array access
Fixes: 546/clusterfuzz-testcase-4809433909559296
Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-787
Target: 1
Example 2:
Code: do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
type == NT_GNU_VERSION && descsz == 2) {
*flags |= FLAGS_DID_OS_NOTE;
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
return 1;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
memcpy(desc, &nbuf[doff], sizeof(desc));
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for GNU/") == -1)
return 1;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return 1;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return 1;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return 1;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return 1;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return 1;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return 1;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return 1;
return 1;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
if (type == NT_NETBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
do_note_netbsd_version(ms, swap, &nbuf[doff]);
return 1;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (type == NT_FREEBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
do_note_freebsd_version(ms, swap, &nbuf[doff]);
return 1;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
type == NT_OPENBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for OpenBSD") == -1)
return 1;
/* Content of note is always 0 */
return 1;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for DragonFly") == -1)
return 1;
memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return 1;
return 1;
}
return 0;
}
Commit Message: Avoid reading past the end of buffer (Rui Reis)
CWE ID: CWE-125
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: void PluginServiceImpl::AddExtraPluginDir(const FilePath& path) {
plugin_list_->AddExtraPluginDir(path);
}
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
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: irc_ctcp_dcc_filename_without_quotes (const char *filename)
{
int length;
length = strlen (filename);
if (length > 0)
{
if ((filename[0] == '\"') && (filename[length - 1] == '\"'))
return weechat_strndup (filename + 1, length - 2);
}
return strdup (filename);
}
Commit Message: irc: fix parsing of DCC filename
CWE ID: CWE-119
Target: 1
Example 2:
Code: void TestingAutomationProvider::ConnectToCellularNetwork(
DictionaryValue* args, IPC::Message* reply_message) {
std::string service_path;
if (!args->GetString("service_path", &service_path)) {
AutomationJSONReply(this, reply_message).SendError(
"Invalid or missing args.");
return;
}
NetworkLibrary* network_library = CrosLibrary::Get()->GetNetworkLibrary();
chromeos::CellularNetwork* cellular =
network_library->FindCellularNetworkByPath(service_path);
if (!cellular) {
AutomationJSONReply(this, reply_message).SendError(
"No network found with specified service path.");
return;
}
new ServicePathConnectObserver(this, reply_message, service_path);
network_library->ConnectToCellularNetwork(cellular);
network_library->RequestNetworkScan();
}
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: bool ExtensionTtsPlatformImplWin::Speak(
const std::string& src_utterance,
const std::string& language,
const std::string& gender,
double rate,
double pitch,
double volume) {
std::wstring utterance = UTF8ToUTF16(src_utterance);
if (!speech_synthesizer_)
return false;
if (rate >= 0.0) {
speech_synthesizer_->SetRate(static_cast<int32>(rate * 20 - 10));
}
if (pitch >= 0.0) {
std::wstring pitch_value =
base::IntToString16(static_cast<int>(pitch * 20 - 10));
utterance = L"<pitch absmiddle=\"" + pitch_value + L"\">" +
utterance + L"</pitch>";
}
if (volume >= 0.0) {
speech_synthesizer_->SetVolume(static_cast<uint16>(volume * 100));
}
if (paused_) {
speech_synthesizer_->Resume();
paused_ = false;
}
speech_synthesizer_->Speak(
utterance.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20
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: nfsd4_set_nfs4_acl(struct svc_rqst *rqstp, struct svc_fh *fhp,
struct nfs4_acl *acl)
{
__be32 error;
int host_error;
struct dentry *dentry;
struct inode *inode;
struct posix_acl *pacl = NULL, *dpacl = NULL;
unsigned int flags = 0;
/* Get inode */
error = fh_verify(rqstp, fhp, 0, NFSD_MAY_SATTR);
if (error)
return error;
dentry = fhp->fh_dentry;
inode = d_inode(dentry);
if (!inode->i_op->set_acl || !IS_POSIXACL(inode))
return nfserr_attrnotsupp;
if (S_ISDIR(inode->i_mode))
flags = NFS4_ACL_DIR;
host_error = nfs4_acl_nfsv4_to_posix(acl, &pacl, &dpacl, flags);
if (host_error == -EINVAL)
return nfserr_attrnotsupp;
if (host_error < 0)
goto out_nfserr;
host_error = inode->i_op->set_acl(inode, pacl, ACL_TYPE_ACCESS);
if (host_error < 0)
goto out_release;
if (S_ISDIR(inode->i_mode)) {
host_error = inode->i_op->set_acl(inode, dpacl,
ACL_TYPE_DEFAULT);
}
out_release:
posix_acl_release(pacl);
posix_acl_release(dpacl);
out_nfserr:
if (host_error == -EOPNOTSUPP)
return nfserr_attrnotsupp;
else
return nfserrno(host_error);
}
Commit Message: nfsd: check permissions when setting ACLs
Use set_posix_acl, which includes proper permission checks, instead of
calling ->set_acl directly. Without this anyone may be able to grant
themselves permissions to a file by setting the ACL.
Lock the inode to make the new checks atomic with respect to set_acl.
(Also, nfsd was the only caller of set_acl not locking the inode, so I
suspect this may fix other races.)
This also simplifies the code, and ensures our ACLs are checked by
posix_acl_valid.
The permission checks and the inode locking were lost with commit
4ac7249e, which changed nfsd to use the set_acl inode operation directly
instead of going through xattr handlers.
Reported-by: David Sinquin <[email protected]>
[[email protected]: use set_posix_acl]
Fixes: 4ac7249e
Cc: Christoph Hellwig <[email protected]>
Cc: Al Viro <[email protected]>
Cc: [email protected]
Signed-off-by: J. Bruce Fields <[email protected]>
CWE ID: CWE-284
Target: 1
Example 2:
Code: bool SyncManager::ReceivedExperimentalTypes(syncable::ModelTypeSet* to_add)
const {
ReadTransaction trans(FROM_HERE, GetUserShare());
ReadNode node(&trans);
if (!node.InitByTagLookup(kNigoriTag)) {
DVLOG(1) << "Couldn't find Nigori node.";
return false;
}
if (node.GetNigoriSpecifics().sync_tabs()) {
to_add->Put(syncable::SESSIONS);
return true;
}
return false;
}
Commit Message: sync: remove Chrome OS specific logic to deal with flimflam shutdown / sync race.
No longer necessary as the ProfileSyncService now aborts sync network traffic on shutdown.
BUG=chromium-os:20841
Review URL: http://codereview.chromium.org/9358007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120912 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: GlobalHistogramAllocator::ReleaseForTesting() {
GlobalHistogramAllocator* histogram_allocator = Get();
if (!histogram_allocator)
return nullptr;
PersistentMemoryAllocator* memory_allocator =
histogram_allocator->memory_allocator();
PersistentMemoryAllocator::Iterator iter(memory_allocator);
const PersistentHistogramData* data;
while ((data = iter.GetNextOfObject<PersistentHistogramData>()) != nullptr) {
StatisticsRecorder::ForgetHistogramForTesting(data->name);
DCHECK_NE(kResultHistogram, data->name);
}
subtle::Release_Store(&g_histogram_allocator, 0);
return WrapUnique(histogram_allocator);
};
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
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: parse_elements(netdissect_options *ndo,
struct mgmt_body_t *pbody, const u_char *p, int offset,
u_int length)
{
u_int elementlen;
struct ssid_t ssid;
struct challenge_t challenge;
struct rates_t rates;
struct ds_t ds;
struct cf_t cf;
struct tim_t tim;
/*
* We haven't seen any elements yet.
*/
pbody->challenge_present = 0;
pbody->ssid_present = 0;
pbody->rates_present = 0;
pbody->ds_present = 0;
pbody->cf_present = 0;
pbody->tim_present = 0;
while (length != 0) {
/* Make sure we at least have the element ID and length. */
if (!ND_TTEST2(*(p + offset), 2))
return 0;
if (length < 2)
return 0;
elementlen = *(p + offset + 1);
/* Make sure we have the entire element. */
if (!ND_TTEST2(*(p + offset + 2), elementlen))
return 0;
if (length < elementlen + 2)
return 0;
switch (*(p + offset)) {
case E_SSID:
memcpy(&ssid, p + offset, 2);
offset += 2;
length -= 2;
if (ssid.length != 0) {
if (ssid.length > sizeof(ssid.ssid) - 1)
return 0;
if (!ND_TTEST2(*(p + offset), ssid.length))
return 0;
if (length < ssid.length)
return 0;
memcpy(&ssid.ssid, p + offset, ssid.length);
offset += ssid.length;
length -= ssid.length;
}
ssid.ssid[ssid.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen an SSID IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ssid_present) {
pbody->ssid = ssid;
pbody->ssid_present = 1;
}
break;
case E_CHALLENGE:
memcpy(&challenge, p + offset, 2);
offset += 2;
length -= 2;
if (challenge.length != 0) {
if (challenge.length >
sizeof(challenge.text) - 1)
return 0;
if (!ND_TTEST2(*(p + offset), challenge.length))
return 0;
if (length < challenge.length)
return 0;
memcpy(&challenge.text, p + offset,
challenge.length);
offset += challenge.length;
length -= challenge.length;
}
challenge.text[challenge.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen a challenge IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->challenge_present) {
pbody->challenge = challenge;
pbody->challenge_present = 1;
}
break;
case E_RATES:
memcpy(&rates, p + offset, 2);
offset += 2;
length -= 2;
if (rates.length != 0) {
if (rates.length > sizeof rates.rate)
return 0;
if (!ND_TTEST2(*(p + offset), rates.length))
return 0;
if (length < rates.length)
return 0;
memcpy(&rates.rate, p + offset, rates.length);
offset += rates.length;
length -= rates.length;
}
/*
* Present and not truncated.
*
* If we haven't already seen a rates IE,
* copy this one if it's not zero-length,
* otherwise ignore this one, so we later
* report the first one we saw.
*
* We ignore zero-length rates IEs as some
* devices seem to put a zero-length rates
* IE, followed by an SSID IE, followed by
* a non-zero-length rates IE into frames,
* even though IEEE Std 802.11-2007 doesn't
* seem to indicate that a zero-length rates
* IE is valid.
*/
if (!pbody->rates_present && rates.length != 0) {
pbody->rates = rates;
pbody->rates_present = 1;
}
break;
case E_DS:
memcpy(&ds, p + offset, 2);
offset += 2;
length -= 2;
if (ds.length != 1) {
offset += ds.length;
length -= ds.length;
break;
}
ds.channel = *(p + offset);
offset += 1;
length -= 1;
/*
* Present and not truncated.
*
* If we haven't already seen a DS IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ds_present) {
pbody->ds = ds;
pbody->ds_present = 1;
}
break;
case E_CF:
memcpy(&cf, p + offset, 2);
offset += 2;
length -= 2;
if (cf.length != 6) {
offset += cf.length;
length -= cf.length;
break;
}
memcpy(&cf.count, p + offset, 6);
offset += 6;
length -= 6;
/*
* Present and not truncated.
*
* If we haven't already seen a CF IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->cf_present) {
pbody->cf = cf;
pbody->cf_present = 1;
}
break;
case E_TIM:
memcpy(&tim, p + offset, 2);
offset += 2;
length -= 2;
if (tim.length <= 3) {
offset += tim.length;
length -= tim.length;
break;
}
if (tim.length - 3 > (int)sizeof tim.bitmap)
return 0;
memcpy(&tim.count, p + offset, 3);
offset += 3;
length -= 3;
memcpy(tim.bitmap, p + offset + 3, tim.length - 3);
offset += tim.length - 3;
length -= tim.length - 3;
/*
* Present and not truncated.
*
* If we haven't already seen a TIM IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->tim_present) {
pbody->tim = tim;
pbody->tim_present = 1;
}
break;
default:
#if 0
ND_PRINT((ndo, "(1) unhandled element_id (%d) ",
*(p + offset)));
#endif
offset += 2 + elementlen;
length -= 2 + elementlen;
break;
}
}
/* No problems found. */
return 1;
}
Commit Message: CVE-2017-13008/IEEE 802.11: Fix TIM bitmap copy to copy from p + offset.
offset has already been advanced to point to the bitmap; we shouldn't
add the amount to advance again.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by the reporter(s).
While we're at it, remove some redundant tests - we've already checked,
before the case statement, whether we have captured the entire
information element and whether the entire information element is
present in the on-the-wire packet; in the cases for particular IEs, we
only need to make sure we don't go past the end of the IE.
CWE ID: CWE-125
Target: 1
Example 2:
Code: IHEVCD_ERROR_T ihevcd_parse_pps(codec_t *ps_codec)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 pps_id;
pps_t *ps_pps;
sps_t *ps_sps;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
if(0 == ps_codec->i4_sps_done)
return IHEVCD_INVALID_HEADER;
UEV_PARSE("pic_parameter_set_id", value, ps_bitstrm);
pps_id = value;
if((pps_id >= MAX_PPS_CNT) || (pps_id < 0))
{
if(ps_codec->i4_pps_done)
return IHEVCD_UNSUPPORTED_PPS_ID;
else
pps_id = 0;
}
ps_pps = (ps_codec->s_parse.ps_pps_base + MAX_PPS_CNT - 1);
ps_pps->i1_pps_id = pps_id;
UEV_PARSE("seq_parameter_set_id", value, ps_bitstrm);
ps_pps->i1_sps_id = value;
ps_pps->i1_sps_id = CLIP3(ps_pps->i1_sps_id, 0, MAX_SPS_CNT - 2);
ps_sps = (ps_codec->s_parse.ps_sps_base + ps_pps->i1_sps_id);
/* If the SPS that is being referred to has not been parsed,
* copy an existing SPS to the current location */
if(0 == ps_sps->i1_sps_valid)
{
return IHEVCD_INVALID_HEADER;
/*
sps_t *ps_sps_ref = ps_codec->ps_sps_base;
while(0 == ps_sps_ref->i1_sps_valid)
ps_sps_ref++;
ihevcd_copy_sps(ps_codec, ps_pps->i1_sps_id, ps_sps_ref->i1_sps_id);
*/
}
BITS_PARSE("dependent_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_dependent_slice_enabled_flag = value;
BITS_PARSE("output_flag_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_output_flag_present_flag = value;
BITS_PARSE("num_extra_slice_header_bits", value, ps_bitstrm, 3);
ps_pps->i1_num_extra_slice_header_bits = value;
BITS_PARSE("sign_data_hiding_flag", value, ps_bitstrm, 1);
ps_pps->i1_sign_data_hiding_flag = value;
BITS_PARSE("cabac_init_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_cabac_init_present_flag = value;
UEV_PARSE("num_ref_idx_l0_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l0_default_active = value + 1;
UEV_PARSE("num_ref_idx_l1_default_active_minus1", value, ps_bitstrm);
ps_pps->i1_num_ref_idx_l1_default_active = value + 1;
SEV_PARSE("pic_init_qp_minus26", value, ps_bitstrm);
ps_pps->i1_pic_init_qp = value + 26;
BITS_PARSE("constrained_intra_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_constrained_intra_pred_flag = value;
BITS_PARSE("transform_skip_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_transform_skip_enabled_flag = value;
BITS_PARSE("cu_qp_delta_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_cu_qp_delta_enabled_flag = value;
if(ps_pps->i1_cu_qp_delta_enabled_flag)
{
UEV_PARSE("diff_cu_qp_delta_depth", value, ps_bitstrm);
ps_pps->i1_diff_cu_qp_delta_depth = value;
}
else
{
ps_pps->i1_diff_cu_qp_delta_depth = 0;
}
ps_pps->i1_log2_min_cu_qp_delta_size = ps_sps->i1_log2_ctb_size - ps_pps->i1_diff_cu_qp_delta_depth;
/* Print different */
SEV_PARSE("cb_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cb_qp_offset = value;
/* Print different */
SEV_PARSE("cr_qp_offset", value, ps_bitstrm);
ps_pps->i1_pic_cr_qp_offset = value;
/* Print different */
BITS_PARSE("slicelevel_chroma_qp_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag = value;
BITS_PARSE("weighted_pred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_pred_flag = value;
BITS_PARSE("weighted_bipred_flag", value, ps_bitstrm, 1);
ps_pps->i1_weighted_bipred_flag = value;
BITS_PARSE("transquant_bypass_enable_flag", value, ps_bitstrm, 1);
ps_pps->i1_transquant_bypass_enable_flag = value;
BITS_PARSE("tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_tiles_enabled_flag = value;
/* When tiles are enabled and width or height is >= 4096,
* CTB Size should at least be 32. 16x16 CTBs can result
* in tile position greater than 255 for 4096,
* which decoder does not support.
*/
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_sps->i1_log2_ctb_size == 4) &&
((ps_sps->i2_pic_width_in_luma_samples >= 4096) ||
(ps_sps->i2_pic_height_in_luma_samples >= 4096)))
{
return IHEVCD_INVALID_HEADER;
}
BITS_PARSE("entropy_coding_sync_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_entropy_coding_sync_enabled_flag = value;
ps_pps->i1_loop_filter_across_tiles_enabled_flag = 0;
if(ps_pps->i1_tiles_enabled_flag)
{
WORD32 wd = ALIGN64(ps_codec->i4_wd);
WORD32 ht = ALIGN64(ps_codec->i4_ht);
WORD32 max_tile_cols = (wd + MIN_TILE_WD - 1) / MIN_TILE_WD;
WORD32 max_tile_rows = (ht + MIN_TILE_HT - 1) / MIN_TILE_HT;
UEV_PARSE("num_tile_columns_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_columns = value + 1;
UEV_PARSE("num_tile_rows_minus1", value, ps_bitstrm);
ps_pps->i1_num_tile_rows = value + 1;
if((ps_pps->i1_num_tile_columns < 1) ||
(ps_pps->i1_num_tile_columns > max_tile_cols) ||
(ps_pps->i1_num_tile_rows < 1) ||
(ps_pps->i1_num_tile_rows > max_tile_rows))
return IHEVCD_INVALID_HEADER;
BITS_PARSE("uniform_spacing_flag", value, ps_bitstrm, 1);
ps_pps->i1_uniform_spacing_flag = value;
{
WORD32 start;
WORD32 i, j;
start = 0;
for(i = 0; i < ps_pps->i1_num_tile_columns; i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_columns - 1))
{
UEV_PARSE("column_width_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_wd_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns -
(i * ps_sps->i2_pic_wd_in_ctb) / ps_pps->i1_num_tile_columns;
}
for(j = 0; j < ps_pps->i1_num_tile_rows; j++)
{
ps_tile = ps_pps->ps_tile + j * ps_pps->i1_num_tile_columns + i;
ps_tile->u1_pos_x = start;
ps_tile->u2_wd = value;
}
start += value;
if((start > ps_sps->i2_pic_wd_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
start = 0;
for(i = 0; i < (ps_pps->i1_num_tile_rows); i++)
{
tile_t *ps_tile;
if(!ps_pps->i1_uniform_spacing_flag)
{
if(i < (ps_pps->i1_num_tile_rows - 1))
{
UEV_PARSE("row_height_minus1[ i ]", value, ps_bitstrm);
value += 1;
}
else
{
value = ps_sps->i2_pic_ht_in_ctb - start;
}
}
else
{
value = ((i + 1) * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows -
(i * ps_sps->i2_pic_ht_in_ctb) / ps_pps->i1_num_tile_rows;
}
for(j = 0; j < ps_pps->i1_num_tile_columns; j++)
{
ps_tile = ps_pps->ps_tile + i * ps_pps->i1_num_tile_columns + j;
ps_tile->u1_pos_y = start;
ps_tile->u2_ht = value;
}
start += value;
if((start > ps_sps->i2_pic_ht_in_ctb) ||
(value <= 0))
return IHEVCD_INVALID_HEADER;
}
}
BITS_PARSE("loop_filter_across_tiles_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_tiles_enabled_flag = value;
}
else
{
/* If tiles are not present, set first tile in each PPS to have tile
width and height equal to picture width and height */
ps_pps->i1_num_tile_columns = 1;
ps_pps->i1_num_tile_rows = 1;
ps_pps->i1_uniform_spacing_flag = 1;
ps_pps->ps_tile->u1_pos_x = 0;
ps_pps->ps_tile->u1_pos_y = 0;
ps_pps->ps_tile->u2_wd = ps_sps->i2_pic_wd_in_ctb;
ps_pps->ps_tile->u2_ht = ps_sps->i2_pic_ht_in_ctb;
}
BITS_PARSE("loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_loop_filter_across_slices_enabled_flag = value;
BITS_PARSE("deblocking_filter_control_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_control_present_flag = value;
/* Default values */
ps_pps->i1_pic_disable_deblocking_filter_flag = 0;
ps_pps->i1_deblocking_filter_override_enabled_flag = 0;
ps_pps->i1_beta_offset_div2 = 0;
ps_pps->i1_tc_offset_div2 = 0;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
BITS_PARSE("deblocking_filter_override_enabled_flag", value, ps_bitstrm, 1);
ps_pps->i1_deblocking_filter_override_enabled_flag = value;
BITS_PARSE("pic_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_pps->i1_pic_disable_deblocking_filter_flag = value;
if(!ps_pps->i1_pic_disable_deblocking_filter_flag)
{
SEV_PARSE("pps_beta_offset_div2", value, ps_bitstrm);
ps_pps->i1_beta_offset_div2 = value;
SEV_PARSE("pps_tc_offset_div2", value, ps_bitstrm);
ps_pps->i1_tc_offset_div2 = value;
}
}
BITS_PARSE("pps_scaling_list_data_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_pps_scaling_list_data_present_flag = value;
if(ps_pps->i1_pps_scaling_list_data_present_flag)
{
COPY_DEFAULT_SCALING_LIST(ps_pps->pi2_scaling_mat);
ihevcd_scaling_list_data(ps_codec, ps_pps->pi2_scaling_mat);
}
BITS_PARSE("lists_modification_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_lists_modification_present_flag = value;
UEV_PARSE("log2_parallel_merge_level_minus2", value, ps_bitstrm);
ps_pps->i1_log2_parallel_merge_level = value + 2;
BITS_PARSE("slice_header_extension_present_flag", value, ps_bitstrm, 1);
ps_pps->i1_slice_header_extension_present_flag = value;
/* Not present in HM */
BITS_PARSE("pps_extension_flag", value, ps_bitstrm, 1);
if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max)
return IHEVCD_INVALID_PARAMETER;
ps_codec->i4_pps_done = 1;
return ret;
}
Commit Message: Fix overflow in sei user data parsing
Bug: 37968960
Bug: 65484460
Test: ran POC post-patch
Change-Id: I73e91b4b2976b954b5fd4f29182d6072abbc7f70
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 int set_bdev_super(struct super_block *s, void *data)
{
s->s_bdev = data;
s->s_dev = s->s_bdev->bd_dev;
/*
* We set the bdi here to the queue backing, file systems can
* overwrite this in ->fill_super()
*/
s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info;
return 0;
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17
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 avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
}
Commit Message: avcodec/ac3_parser: Check init_get_bits8() for failure
Fixes: null pointer dereference
Fixes: ffmpeg_crash_6.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Reviewed-by: Paul B Mahol <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-476
Target: 1
Example 2:
Code: void PrintDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
gtk_widget_hide(dialog_);
switch (response_id) {
case GTK_RESPONSE_OK: {
if (gtk_settings_)
g_object_unref(gtk_settings_);
gtk_settings_ = gtk_print_unix_dialog_get_settings(
GTK_PRINT_UNIX_DIALOG(dialog_));
if (printer_)
g_object_unref(printer_);
printer_ = gtk_print_unix_dialog_get_selected_printer(
GTK_PRINT_UNIX_DIALOG(dialog_));
g_object_ref(printer_);
if (page_setup_)
g_object_unref(page_setup_);
page_setup_ = gtk_print_unix_dialog_get_page_setup(
GTK_PRINT_UNIX_DIALOG(dialog_));
g_object_ref(page_setup_);
PageRanges ranges_vector;
gint num_ranges;
GtkPageRange* gtk_range =
gtk_print_settings_get_page_ranges(gtk_settings_, &num_ranges);
if (gtk_range) {
for (int i = 0; i < num_ranges; ++i) {
printing::PageRange range;
range.from = gtk_range[i].start;
range.to = gtk_range[i].end;
ranges_vector.push_back(range);
}
g_free(gtk_range);
}
PrintSettings settings;
printing::PrintSettingsInitializerGtk::InitPrintSettings(
gtk_settings_, page_setup_, ranges_vector, false, &settings);
context_->InitWithSettings(settings);
callback_->Run(PrintingContextCairo::OK);
callback_ = NULL;
return;
}
case GTK_RESPONSE_DELETE_EVENT: // Fall through.
case GTK_RESPONSE_CANCEL: {
callback_->Run(PrintingContextCairo::CANCEL);
callback_ = NULL;
return;
}
case GTK_RESPONSE_APPLY:
default: {
NOTREACHED();
}
}
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 0
Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation.
Code: static void __exit exit_ext2_fs(void)
{
unregister_filesystem(&ext2_fs_type);
destroy_inodecache();
exit_ext2_xattr();
}
Commit Message: ext2: convert to mbcache2
The conversion is generally straightforward. We convert filesystem from
a global cache to per-fs one. Similarly to ext4 the tricky part is that
xattr block corresponding to found mbcache entry can get freed before we
get buffer lock for that block. So we have to check whether the entry is
still valid after getting the buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19
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: struct timespec ns_to_timespec(const s64 nsec)
{
struct timespec ts;
if (!nsec)
return (struct timespec) {0, 0};
ts.tv_sec = div_long_long_rem_signed(nsec, NSEC_PER_SEC, &ts.tv_nsec);
if (unlikely(nsec < 0))
set_normalized_timespec(&ts, ts.tv_sec, ts.tv_nsec);
return ts;
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: static int rom_write(struct pci_dev *dev, int offset, u32 value, void *data)
{
struct pci_bar_info *bar = data;
if (unlikely(!bar)) {
pr_warn(DRV_NAME ": driver data not found for %s\n",
pci_name(dev));
return XEN_PCI_ERR_op_failed;
}
/* A write to obtain the length must happen as a 32-bit write.
* This does not (yet) support writing individual bytes
*/
if (value == ~PCI_ROM_ADDRESS_ENABLE)
bar->which = 1;
else {
u32 tmpval;
pci_read_config_dword(dev, offset, &tmpval);
if (tmpval != bar->val && value == bar->val) {
/* Allow restoration of bar value. */
pci_write_config_dword(dev, offset, bar->val);
}
bar->which = 0;
}
/* Do we need to support enabling/disabling the rom address here? */
return 0;
}
Commit Message: xen-pciback: limit guest control of command register
Otherwise the guest can abuse that control to cause e.g. PCIe
Unsupported Request responses by disabling memory and/or I/O decoding
and subsequently causing (CPU side) accesses to the respective address
ranges, which (depending on system configuration) may be fatal to the
host.
Note that to alter any of the bits collected together as
PCI_COMMAND_GUEST permissive mode is now required to be enabled
globally or on the specific device.
This is CVE-2015-2150 / XSA-120.
Signed-off-by: Jan Beulich <[email protected]>
Reviewed-by: Konrad Rzeszutek Wilk <[email protected]>
Cc: <[email protected]>
Signed-off-by: David Vrabel <[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: void DeviceTokenFetcher::StopAutoRetry() {
scheduler_->CancelDelayedWork();
backend_.reset();
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Output: | 1 |
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code.
Example 1:
Code: static struct mobj *alloc_ta_mem(size_t size)
{
#ifdef CFG_PAGED_USER_TA
return mobj_paged_alloc(size);
#else
struct mobj *mobj = mobj_mm_alloc(mobj_sec_ddr, size, &tee_mm_sec_ddr);
if (mobj)
memset(mobj_get_va(mobj, 0), 0, size);
return mobj;
#endif
}
Commit Message: core: clear the entire TA area
Previously we cleared (memset to zero) the size corresponding to code
and data segments, however the allocation for the TA is made on the
granularity of the memory pool, meaning that we did not clear all memory
and because of that we could potentially leak code and data of a
previous loaded TA.
Fixes: OP-TEE-2018-0006: "Potential disclosure of previously loaded TA
code and data"
Signed-off-by: Joakim Bech <[email protected]>
Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8)
Suggested-by: Jens Wiklander <[email protected]>
Reviewed-by: Jens Wiklander <[email protected]>
Reported-by: Riscure <[email protected]>
Reported-by: Alyssa Milburn <[email protected]>
Acked-by: Etienne Carriere <[email protected]>
CWE ID: CWE-189
Target: 1
Example 2:
Code: IW_IMPL(const struct iw_palette*) iw_get_output_palette(struct iw_context *ctx)
{
return ctx->optctx.palette;
}
Commit Message: Double-check that the input image's density is valid
Fixes a bug that could result in division by zero, at least for a JPEG
source image.
Fixes issues #19, #20
CWE ID: CWE-369
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: parse_intel_port_stats_rfc2819_property(const struct ofpbuf *payload,
struct ofputil_port_stats *ops)
{
const struct intel_port_stats_rfc2819 *rfc2819 = payload->data;
if (payload->size != sizeof *rfc2819) {
return OFPERR_OFPBPC_BAD_LEN;
}
ops->stats.rx_1_to_64_packets = ntohll(rfc2819->rx_1_to_64_packets);
ops->stats.rx_65_to_127_packets = ntohll(rfc2819->rx_65_to_127_packets);
ops->stats.rx_128_to_255_packets = ntohll(rfc2819->rx_128_to_255_packets);
ops->stats.rx_256_to_511_packets = ntohll(rfc2819->rx_256_to_511_packets);
ops->stats.rx_512_to_1023_packets =
ntohll(rfc2819->rx_512_to_1023_packets);
ops->stats.rx_1024_to_1522_packets =
ntohll(rfc2819->rx_1024_to_1522_packets);
ops->stats.rx_1523_to_max_packets =
ntohll(rfc2819->rx_1523_to_max_packets);
ops->stats.tx_1_to_64_packets = ntohll(rfc2819->tx_1_to_64_packets);
ops->stats.tx_65_to_127_packets = ntohll(rfc2819->tx_65_to_127_packets);
ops->stats.tx_128_to_255_packets = ntohll(rfc2819->tx_128_to_255_packets);
ops->stats.tx_256_to_511_packets = ntohll(rfc2819->tx_256_to_511_packets);
ops->stats.tx_512_to_1023_packets =
ntohll(rfc2819->tx_512_to_1023_packets);
ops->stats.tx_1024_to_1522_packets =
ntohll(rfc2819->tx_1024_to_1522_packets);
ops->stats.tx_1523_to_max_packets =
ntohll(rfc2819->tx_1523_to_max_packets);
ops->stats.tx_multicast_packets = ntohll(rfc2819->tx_multicast_packets);
ops->stats.rx_broadcast_packets = ntohll(rfc2819->rx_broadcast_packets);
ops->stats.tx_broadcast_packets = ntohll(rfc2819->tx_broadcast_packets);
ops->stats.rx_undersized_errors = ntohll(rfc2819->rx_undersized_errors);
ops->stats.rx_oversize_errors = ntohll(rfc2819->rx_oversize_errors);
ops->stats.rx_fragmented_errors = ntohll(rfc2819->rx_fragmented_errors);
ops->stats.rx_jabber_errors = ntohll(rfc2819->rx_jabber_errors);
return 0;
}
Commit Message: ofp-group: Don't assert-fail decoding bad OF1.5 group mod type or command.
When decoding a group mod, the current code validates the group type and
command after the whole group mod has been decoded. The OF1.5 decoder,
however, tries to use the type and command earlier, when it might still be
invalid. This caused an assertion failure (via OVS_NOT_REACHED). This
commit fixes the problem.
ovs-vswitchd does not enable support for OpenFlow 1.5 by default.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9249
Signed-off-by: Ben Pfaff <[email protected]>
Reviewed-by: Yifeng Sun <[email protected]>
CWE ID: CWE-617
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: zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
code = dict_find_string(op, "Implementation", &pImpl);
if (code != 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
Commit Message:
CWE ID: CWE-704
Target: 1
Example 2:
Code: int snd_compress_new(struct snd_card *card, int device,
int dirn, struct snd_compr *compr)
{
static struct snd_device_ops ops = {
.dev_free = NULL,
.dev_register = snd_compress_dev_register,
.dev_disconnect = snd_compress_dev_disconnect,
};
compr->card = card;
compr->device = device;
compr->direction = dirn;
return snd_device_new(card, SNDRV_DEV_COMPRESS, compr, &ops);
}
Commit Message: ALSA: compress: fix an integer overflow check
I previously added an integer overflow check here but looking at it now,
it's still buggy.
The bug happens in snd_compr_allocate_buffer(). We multiply
".fragments" and ".fragment_size" and that doesn't overflow but then we
save it in an unsigned int so it truncates the high bits away and we
allocate a smaller than expected size.
Fixes: b35cc8225845 ('ALSA: compress_core: integer overflow in snd_compr_allocate_buffer()')
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Takashi Iwai <[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 void bpf_prog_uncharge_memlock(struct bpf_prog *prog)
{
struct user_struct *user = prog->aux->user;
atomic_long_sub(prog->pages, &user->locked_vm);
free_uid(user);
}
Commit Message: bpf: fix refcnt overflow
On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK,
the malicious application may overflow 32-bit bpf program refcnt.
It's also possible to overflow map refcnt on 1Tb system.
Impose 32k hard limit which means that the same bpf program or
map cannot be shared by more than 32k processes.
Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs")
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Acked-by: Daniel Borkmann <[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: ssize_t utf16_to_utf8_length(const char16_t *src, size_t src_len)
{
if (src == NULL || src_len == 0) {
return -1;
}
size_t ret = 0;
const char16_t* const end = src + src_len;
while (src < end) {
if ((*src & 0xFC00) == 0xD800 && (src + 1) < end
&& (*++src & 0xFC00) == 0xDC00) {
ret += 4;
src++;
} else {
ret += utf32_codepoint_utf8_length((char32_t) *src++);
}
}
return ret;
}
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: set_num_733(unsigned char *p, uint32_t value)
{
archive_le32enc(p, value);
archive_be32enc(p+4, value);
}
Commit Message: Issue 711: Be more careful about verifying filename lengths when writing ISO9660 archives
* Don't cast size_t to int, since this can lead to overflow
on machines where sizeof(int) < sizeof(size_t)
* Check a + b > limit by writing it as
a > limit || b > limit || a + b > limit
to avoid problems when a + b wraps around.
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 inode_dio_wait(struct inode *inode)
{
if (atomic_read(&inode->i_dio_count))
__inode_dio_wait(inode);
}
Commit Message: fs,userns: Change inode_capable to capable_wrt_inode_uidgid
The kernel has no concept of capabilities with respect to inodes; inodes
exist independently of namespaces. For example, inode_capable(inode,
CAP_LINUX_IMMUTABLE) would be nonsense.
This patch changes inode_capable to check for uid and gid mappings and
renames it to capable_wrt_inode_uidgid, which should make it more
obvious what it does.
Fixes CVE-2014-4014.
Cc: Theodore Ts'o <[email protected]>
Cc: Serge Hallyn <[email protected]>
Cc: "Eric W. Biederman" <[email protected]>
Cc: Dave Chinner <[email protected]>
Cc: [email protected]
Signed-off-by: Andy Lutomirski <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264
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: vsock_stream_recvmsg(struct kiocb *kiocb,
struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk;
struct vsock_sock *vsk;
int err;
size_t target;
ssize_t copied;
long timeout;
struct vsock_transport_recv_notify_data recv_data;
DEFINE_WAIT(wait);
sk = sock->sk;
vsk = vsock_sk(sk);
err = 0;
lock_sock(sk);
if (sk->sk_state != SS_CONNECTED) {
/* Recvmsg is supposed to return 0 if a peer performs an
* orderly shutdown. Differentiate between that case and when a
* peer has not connected or a local shutdown occured with the
* SOCK_DONE flag.
*/
if (sock_flag(sk, SOCK_DONE))
err = 0;
else
err = -ENOTCONN;
goto out;
}
if (flags & MSG_OOB) {
err = -EOPNOTSUPP;
goto out;
}
/* We don't check peer_shutdown flag here since peer may actually shut
* down, but there can be data in the queue that a local socket can
* receive.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
err = 0;
goto out;
}
/* It is valid on Linux to pass in a zero-length receive buffer. This
* is not an error. We may as well bail out now.
*/
if (!len) {
err = 0;
goto out;
}
/* We must not copy less than target bytes into the user's buffer
* before returning successfully, so we wait for the consume queue to
* have that much data to consume before dequeueing. Note that this
* makes it impossible to handle cases where target is greater than the
* queue size.
*/
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
if (target >= transport->stream_rcvhiwat(vsk)) {
err = -ENOMEM;
goto out;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
copied = 0;
err = transport->notify_recv_init(vsk, target, &recv_data);
if (err < 0)
goto out;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
while (1) {
s64 ready = vsock_stream_has_data(vsk);
if (ready < 0) {
/* Invalid queue pair content. XXX This should be
* changed to a connection reset in a later change.
*/
err = -ENOMEM;
goto out_wait;
} else if (ready > 0) {
ssize_t read;
err = transport->notify_recv_pre_dequeue(
vsk, target, &recv_data);
if (err < 0)
break;
read = transport->stream_dequeue(
vsk, msg->msg_iov,
len - copied, flags);
if (read < 0) {
err = -ENOMEM;
break;
}
copied += read;
err = transport->notify_recv_post_dequeue(
vsk, target, read,
!(flags & MSG_PEEK), &recv_data);
if (err < 0)
goto out_wait;
if (read >= target || flags & MSG_PEEK)
break;
target -= read;
} else {
if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN)
|| (vsk->peer_shutdown & SEND_SHUTDOWN)) {
break;
}
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
break;
}
err = transport->notify_recv_pre_block(
vsk, target, &recv_data);
if (err < 0)
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
break;
} else if (timeout == 0) {
err = -EAGAIN;
break;
}
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
}
}
if (sk->sk_err)
err = -sk->sk_err;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
err = 0;
if (copied > 0) {
/* We only do these additional bookkeeping/notification steps
* if we actually copied something out of the queue pair
* instead of just peeking ahead.
*/
if (!(flags & MSG_PEEK)) {
/* If the other side has shutdown for sending and there
* is nothing more to read, then modify the socket
* state.
*/
if (vsk->peer_shutdown & SEND_SHUTDOWN) {
if (vsock_stream_has_data(vsk) <= 0) {
sk->sk_state = SS_UNCONNECTED;
sock_set_flag(sk, SOCK_DONE);
sk->sk_state_change(sk);
}
}
}
err = copied;
}
out_wait:
finish_wait(sk_sleep(sk), &wait);
out:
release_sock(sk);
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
Target: 1
Example 2:
Code: static void _S_AL_SanitiseVector( vec3_t v, int line )
{
if( Q_isnan( v[ 0 ] ) || Q_isnan( v[ 1 ] ) || Q_isnan( v[ 2 ] ) )
{
Com_DPrintf( S_COLOR_YELLOW "WARNING: vector with one or more NaN components "
"being passed to OpenAL at %s:%d -- zeroing\n", __FILE__, line );
VectorClear( v );
}
}
Commit Message: Don't open .pk3 files as OpenAL drivers.
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: raptor_libxml_resolveEntity(void* user_data,
const xmlChar *publicId, const xmlChar *systemId) {
raptor_sax2* sax2 = (raptor_sax2*)user_data;
return libxml2_resolveEntity(sax2->xc, publicId, systemId);
}
Commit Message: CVE-2012-0037
Enforce entity loading policy in raptor_libxml_resolveEntity
and raptor_libxml_getEntity by checking for file URIs and network URIs.
Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for
turning on loading of XML external entity loading, disabled by default.
This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and
aliases) and rdfa.
CWE ID: CWE-200
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 Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL ||
cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL ||
*replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL ||
*replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
if (pCmdData == NULL ||
cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (sizeof(effect_param_t) + sizeof(int32_t))){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *)pCmdData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
Commit Message: audio effects: fix heap overflow
Check consistency of effect command reply sizes before
copying to reply address.
Also add null pointer check on reply size.
Also remove unused parameter warning.
Bug: 21953516.
Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4
(cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844)
CWE ID: CWE-119
Target: 1
Example 2:
Code: JSRetainPtr<JSStringRef> AccessibilityUIElement::attributesOfLinkedUIElements()
{
return JSStringCreateWithCharacters(0, 0);
}
Commit Message: [GTK][WTR] Implement AccessibilityUIElement::stringValue
https://bugs.webkit.org/show_bug.cgi?id=102951
Reviewed by Martin Robinson.
Implement AccessibilityUIElement::stringValue in the ATK backend
in the same manner it is implemented in DumpRenderTree.
* WebKitTestRunner/InjectedBundle/atk/AccessibilityUIElementAtk.cpp:
(WTR::replaceCharactersForResults):
(WTR):
(WTR::AccessibilityUIElement::stringValue):
git-svn-id: svn://svn.chromium.org/blink/trunk@135485 bbb929c8-8fbe-4397-9dbb-9b2b20218538
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: int venc_dev::append_mbi_extradata(void *dst, struct msm_vidc_extradata_header* src)
{
OMX_QCOM_EXTRADATA_MBINFO *mbi = (OMX_QCOM_EXTRADATA_MBINFO *)dst;
if (!dst || !src)
return 0;
/* TODO: Once Venus 3XX target names are known, nFormat should 2 for those
* targets, since the payload format will be different */
mbi->nFormat = 1;
mbi->nDataSize = src->data_size;
memcpy(&mbi->data, &src->data, src->data_size);
return mbi->nDataSize + sizeof(*mbi);
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200
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 rpmPackageFilesInstall(rpmts ts, rpmte te, rpmfiles files,
rpmpsm psm, char ** failedFile)
{
FD_t payload = rpmtePayload(te);
rpmfi fi = rpmfiNewArchiveReader(payload, files, RPMFI_ITER_READ_ARCHIVE);
rpmfs fs = rpmteGetFileStates(te);
rpmPlugins plugins = rpmtsPlugins(ts);
struct stat sb;
int saveerrno = errno;
int rc = 0;
int nodigest = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOFILEDIGEST) ? 1 : 0;
int nofcaps = (rpmtsFlags(ts) & RPMTRANS_FLAG_NOCAPS) ? 1 : 0;
int firsthardlink = -1;
int skip;
rpmFileAction action;
char *tid = NULL;
const char *suffix;
char *fpath = NULL;
if (fi == NULL) {
rc = RPMERR_BAD_MAGIC;
goto exit;
}
/* transaction id used for temporary path suffix while installing */
rasprintf(&tid, ";%08x", (unsigned)rpmtsGetTid(ts));
/* Detect and create directories not explicitly in package. */
rc = fsmMkdirs(files, fs, plugins);
while (!rc) {
/* Read next payload header. */
rc = rpmfiNext(fi);
if (rc < 0) {
if (rc == RPMERR_ITER_END)
rc = 0;
break;
}
action = rpmfsGetAction(fs, rpmfiFX(fi));
skip = XFA_SKIPPING(action);
suffix = S_ISDIR(rpmfiFMode(fi)) ? NULL : tid;
if (action != FA_TOUCH) {
fpath = fsmFsPath(fi, suffix);
} else {
fpath = fsmFsPath(fi, "");
}
/* Remap file perms, owner, and group. */
rc = rpmfiStat(fi, 1, &sb);
fsmDebug(fpath, action, &sb);
/* Exit on error. */
if (rc)
break;
/* Run fsm file pre hook for all plugins */
rc = rpmpluginsCallFsmFilePre(plugins, fi, fpath,
sb.st_mode, action);
if (rc) {
skip = 1;
} else {
setFileState(fs, rpmfiFX(fi));
}
if (!skip) {
int setmeta = 1;
/* Directories replacing something need early backup */
if (!suffix) {
rc = fsmBackup(fi, action);
}
/* Assume file does't exist when tmp suffix is in use */
if (!suffix) {
rc = fsmVerify(fpath, fi);
} else {
rc = (action == FA_TOUCH) ? 0 : RPMERR_ENOENT;
}
if (S_ISREG(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmMkfile(fi, fpath, files, psm, nodigest,
&setmeta, &firsthardlink);
}
} else if (S_ISDIR(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
mode_t mode = sb.st_mode;
mode &= ~07777;
mode |= 00700;
rc = fsmMkdir(fpath, mode);
}
} else if (S_ISLNK(sb.st_mode)) {
if (rc == RPMERR_ENOENT) {
rc = fsmSymlink(rpmfiFLink(fi), fpath);
}
} else if (S_ISFIFO(sb.st_mode)) {
/* This mimics cpio S_ISSOCK() behavior but probably isn't right */
if (rc == RPMERR_ENOENT) {
rc = fsmMkfifo(fpath, 0000);
}
} else if (S_ISCHR(sb.st_mode) ||
S_ISBLK(sb.st_mode) ||
S_ISSOCK(sb.st_mode))
{
if (rc == RPMERR_ENOENT) {
rc = fsmMknod(fpath, sb.st_mode, sb.st_rdev);
}
} else {
/* XXX Special case /dev/log, which shouldn't be packaged anyways */
if (!IS_DEV_LOG(fpath))
rc = RPMERR_UNKNOWN_FILETYPE;
}
/* Set permissions, timestamps etc for non-hardlink entries */
if (!rc && setmeta) {
rc = fsmSetmeta(fpath, fi, plugins, action, &sb, nofcaps);
}
} else if (firsthardlink >= 0 && rpmfiArchiveHasContent(fi)) {
/* we skip the hard linked file containing the content */
/* write the content to the first used instead */
char *fn = rpmfilesFN(files, firsthardlink);
rc = expandRegular(fi, fn, psm, 0, nodigest, 0);
firsthardlink = -1;
free(fn);
}
if (rc) {
if (!skip) {
/* XXX only erase if temp fn w suffix is in use */
if (suffix && (action != FA_TOUCH)) {
(void) fsmRemove(fpath, sb.st_mode);
}
errno = saveerrno;
}
} else {
/* Notify on success. */
rpmpsmNotify(psm, RPMCALLBACK_INST_PROGRESS, rpmfiArchiveTell(fi));
if (!skip) {
/* Backup file if needed. Directories are handled earlier */
if (suffix)
rc = fsmBackup(fi, action);
if (!rc)
rc = fsmCommit(&fpath, fi, action, suffix);
}
}
if (rc)
*failedFile = xstrdup(fpath);
/* Run fsm file post hook for all plugins */
rpmpluginsCallFsmFilePost(plugins, fi, fpath,
sb.st_mode, action, rc);
fpath = _free(fpath);
}
rpmswAdd(rpmtsOp(ts, RPMTS_OP_UNCOMPRESS), fdOp(payload, FDSTAT_READ));
rpmswAdd(rpmtsOp(ts, RPMTS_OP_DIGEST), fdOp(payload, FDSTAT_DIGEST));
exit:
/* No need to bother with close errors on read */
rpmfiArchiveClose(fi);
rpmfiFree(fi);
Fclose(payload);
free(tid);
free(fpath);
return rc;
}
Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500)
Only follow directory symlinks owned by target directory owner or root.
This prevents privilege escalation from user-writable directories via
directory symlinks to privileged directories on package upgrade, while
still allowing admin to arrange disk usage with symlinks.
The rationale is that if you can create symlinks owned by user X you *are*
user X (or root), and if you also own directory Y you can do whatever with
it already, including change permissions. So when you create a symlink to
that directory, the link ownership acts as a simple stamp of authority that
you indeed want rpm to treat this symlink as it were the directory that
you own. Such a permission can only be given by you or root, which
is just the way we want it. Plus it's almost ridiculously simple as far
as rules go, compared to trying to calculate something from the
source vs destination directory permissions etc.
In the normal case, the user arranging diskspace with symlinks is indeed
root so nothing changes, the only real change here is to links created by
non-privileged users which should be few and far between in practise.
Unfortunately our test-suite runs as a regular user via fakechroot and
thus the testcase for this fails under the new rules. Adjust the testcase
to get the ownership straight and add a second case for the illegal
behavior, basically the same as the old one but with different expectations.
CWE ID: CWE-59
Target: 1
Example 2:
Code: static void t_stop(struct seq_file *m, void *p)
{
mutex_unlock(&ftrace_lock);
}
Commit Message: tracing: Fix possible NULL pointer dereferences
Currently set_ftrace_pid and set_graph_function files use seq_lseek
for their fops. However seq_open() is called only for FMODE_READ in
the fops->open() so that if an user tries to seek one of those file
when she open it for writing, it sees NULL seq_file and then panic.
It can be easily reproduced with following command:
$ cd /sys/kernel/debug/tracing
$ echo 1234 | sudo tee -a set_ftrace_pid
In this example, GNU coreutils' tee opens the file with fopen(, "a")
and then the fopen() internally calls lseek().
Link: http://lkml.kernel.org/r/[email protected]
Cc: Frederic Weisbecker <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Namhyung Kim <[email protected]>
Cc: [email protected]
Signed-off-by: Namhyung Kim <[email protected]>
Signed-off-by: Steven Rostedt <[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: PNG_FUNCTION(void, (PNGCBAPI error), (png_structp png_ptr, const char *message),
static PNG_NORETURN)
{
display *d = (display*)png_get_error_ptr(png_ptr);
fprintf(stderr, "%s(%s): libpng error: %s\n", d->file, d->test, message);
display_exit(d);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
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: InputMethodStatusConnection* ChromeOSMonitorInputMethodStatus(
void* language_library,
LanguageCurrentInputMethodMonitorFunction current_input_method_changed,
LanguageRegisterImePropertiesFunction register_ime_properties,
LanguageUpdateImePropertyFunction update_ime_property,
LanguageConnectionChangeMonitorFunction connection_changed) {
DLOG(INFO) << "MonitorInputMethodStatus";
return InputMethodStatusConnection::GetConnection(
language_library,
current_input_method_changed,
register_ime_properties,
update_ime_property,
connection_changed);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399
Target: 1
Example 2:
Code: static int select_cur_seq_no(HLSContext *c, struct playlist *pls)
{
int seq_no;
if (!pls->finished && !c->first_packet &&
av_gettime_relative() - pls->last_load_time >= default_reload_interval(pls))
/* reload the playlist since it was suspended */
parse_playlist(c, pls->url, pls, NULL);
/* If playback is already in progress (we are just selecting a new
* playlist) and this is a complete file, find the matching segment
* by counting durations. */
if (pls->finished && c->cur_timestamp != AV_NOPTS_VALUE) {
find_timestamp_in_playlist(c, pls, c->cur_timestamp, &seq_no);
return seq_no;
}
if (!pls->finished) {
if (!c->first_packet && /* we are doing a segment selection during playback */
c->cur_seq_no >= pls->start_seq_no &&
c->cur_seq_no < pls->start_seq_no + pls->n_segments)
/* While spec 3.4.3 says that we cannot assume anything about the
* content at the same sequence number on different playlists,
* in practice this seems to work and doing it otherwise would
* require us to download a segment to inspect its timestamps. */
return c->cur_seq_no;
/* If this is a live stream, start live_start_index segments from the
* start or end */
if (c->live_start_index < 0)
return pls->start_seq_no + FFMAX(pls->n_segments + c->live_start_index, 0);
else
return pls->start_seq_no + FFMIN(c->live_start_index, pls->n_segments - 1);
}
/* Otherwise just start on the first segment. */
return pls->start_seq_no;
}
Commit Message: avformat/hls: Fix DoS due to infinite loop
Fixes: loop.m3u
The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome
Found-by: Xiaohei and Wangchu from Alibaba Security Team
Previous version reviewed-by: Steven Liu <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
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 int ext3_drop_inode(struct inode *inode)
{
int drop = generic_drop_inode(inode);
trace_ext3_drop_inode(inode, drop);
return drop;
}
Commit Message: ext3: Fix format string issues
ext3_msg() takes the printk prefix as the second parameter and the
format string as the third parameter. Two callers of ext3_msg omit the
prefix and pass the format string as the second parameter and the first
parameter to the format string as the third parameter. In both cases
this string comes from an arbitrary source. Which means the string may
contain format string characters, which will
lead to undefined and potentially harmful behavior.
The issue was introduced in commit 4cf46b67eb("ext3: Unify log messages
in ext3") and is fixed by this patch.
CC: [email protected]
Signed-off-by: Lars-Peter Clausen <[email protected]>
Signed-off-by: Jan Kara <[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: int perf_config(config_fn_t fn, void *data)
{
int ret = 0, found = 0;
char *repo_config = NULL;
const char *home = NULL;
/* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
if (config_exclusive_filename)
return perf_config_from_file(fn, config_exclusive_filename, data);
if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) {
ret += perf_config_from_file(fn, perf_etc_perfconfig(),
data);
found += 1;
}
home = getenv("HOME");
if (perf_config_global() && home) {
char *user_config = strdup(mkpath("%s/.perfconfig", home));
if (!access(user_config, R_OK)) {
ret += perf_config_from_file(fn, user_config, data);
found += 1;
}
free(user_config);
}
repo_config = perf_pathdup("config");
if (!access(repo_config, R_OK)) {
ret += perf_config_from_file(fn, repo_config, data);
found += 1;
}
free(repo_config);
if (found == 0)
return -1;
return ret;
}
Commit Message: perf tools: do not look at ./config for configuration
In addition to /etc/perfconfig and $HOME/.perfconfig, perf looks for
configuration in the file ./config, imitating git which looks at
$GIT_DIR/config. If ./config is not a perf configuration file, it
fails, or worse, treats it as a configuration file and changes behavior
in some unexpected way.
"config" is not an unusual name for a file to be lying around and perf
does not have a private directory dedicated for its own use, so let's
just stop looking for configuration in the cwd. Callers needing
context-sensitive configuration can use the PERF_CONFIG environment
variable.
Requested-by: Christian Ohm <[email protected]>
Cc: [email protected]
Cc: Ben Hutchings <[email protected]>
Cc: Christian Ohm <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Paul Mackerras <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Jonathan Nieder <[email protected]>
Signed-off-by: Arnaldo Carvalho de Melo <[email protected]>
CWE ID:
Target: 1
Example 2:
Code: void HTMLMediaElement::remotePlaybackStarted() {
if (remotePlaybackClient())
remotePlaybackClient()->stateChanged(WebRemotePlaybackState::Connected);
}
Commit Message: [Blink>Media] Allow autoplay muted on Android by default
There was a mistake causing autoplay muted is shipped on Android
but it will be disabled if the chromium embedder doesn't specify
content setting for "AllowAutoplay" preference. This CL makes the
AllowAutoplay preference true by default so that it is allowed by
embedders (including AndroidWebView) unless they explicitly
disable it.
Intent to ship:
https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ
BUG=689018
Review-Url: https://codereview.chromium.org/2677173002
Cr-Commit-Position: refs/heads/master@{#448423}
CWE ID: CWE-119
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 ecryptfs_copy_mount_wide_sigs_to_inode_sigs(
struct ecryptfs_crypt_stat *crypt_stat,
struct ecryptfs_mount_crypt_stat *mount_crypt_stat)
{
struct ecryptfs_global_auth_tok *global_auth_tok;
int rc = 0;
mutex_lock(&crypt_stat->keysig_list_mutex);
mutex_lock(&mount_crypt_stat->global_auth_tok_list_mutex);
list_for_each_entry(global_auth_tok,
&mount_crypt_stat->global_auth_tok_list,
mount_crypt_stat_list) {
if (global_auth_tok->flags & ECRYPTFS_AUTH_TOK_FNEK)
continue;
rc = ecryptfs_add_keysig(crypt_stat, global_auth_tok->sig);
if (rc) {
printk(KERN_ERR "Error adding keysig; rc = [%d]\n", rc);
goto out;
}
}
out:
mutex_unlock(&mount_crypt_stat->global_auth_tok_list_mutex);
mutex_unlock(&crypt_stat->keysig_list_mutex);
return rc;
}
Commit Message: eCryptfs: Remove buggy and unnecessary write in file name decode routine
Dmitry Chernenkov used KASAN to discover that eCryptfs writes past the
end of the allocated buffer during encrypted filename decoding. This
fix corrects the issue by getting rid of the unnecessary 0 write when
the current bit offset is 2.
Signed-off-by: Michael Halcrow <[email protected]>
Reported-by: Dmitry Chernenkov <[email protected]>
Suggested-by: Kees Cook <[email protected]>
Cc: [email protected] # v2.6.29+: 51ca58d eCryptfs: Filename Encryption: Encoding and encryption functions
Signed-off-by: Tyler Hicks <[email protected]>
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: TaskService::TaskService()
: next_instance_id_(0), bound_instance_id_(kInvalidInstanceId) {}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20
Target: 1
Example 2:
Code: handle_t *__ext4_journal_start_sb(struct super_block *sb, unsigned int line,
int type, int blocks, int rsv_blocks)
{
journal_t *journal;
int err;
trace_ext4_journal_start(sb, blocks, rsv_blocks, _RET_IP_);
err = ext4_journal_check_start(sb);
if (err < 0)
return ERR_PTR(err);
journal = EXT4_SB(sb)->s_journal;
if (!journal)
return ext4_get_nojournal();
return jbd2__journal_start(journal, blocks, rsv_blocks, GFP_NOFS,
type, line);
}
Commit Message: ext4: fix potential use after free in __ext4_journal_stop
There is a use-after-free possibility in __ext4_journal_stop() in the
case that we free the handle in the first jbd2_journal_stop() because
we're referencing handle->h_err afterwards. This was introduced in
9705acd63b125dee8b15c705216d7186daea4625 and it is wrong. Fix it by
storing the handle->h_err value beforehand and avoid referencing
potentially freed handle.
Fixes: 9705acd63b125dee8b15c705216d7186daea4625
Signed-off-by: Lukas Czerner <[email protected]>
Reviewed-by: Andreas Dilger <[email protected]>
Cc: [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: void TaskService::RunTask(InstanceId instance_id,
RunnerId runner_id,
base::OnceClosure task) {
base::subtle::AutoReadLock task_lock(task_lock_);
{
base::AutoLock lock(lock_);
if (instance_id != bound_instance_id_)
return;
}
std::move(task).Run();
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
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: my_object_send_car (MyObject *obj, GValueArray *invals, GValueArray **outvals, GError **error)
{
if (invals->n_values != 3
|| G_VALUE_TYPE (g_value_array_get_nth (invals, 0)) != G_TYPE_STRING
|| G_VALUE_TYPE (g_value_array_get_nth (invals, 1)) != G_TYPE_UINT
|| G_VALUE_TYPE (g_value_array_get_nth (invals, 2)) != G_TYPE_VALUE)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"invalid incoming values");
return FALSE;
}
*outvals = g_value_array_new (2);
g_value_array_append (*outvals, NULL);
g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), G_TYPE_UINT);
g_value_set_uint (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1),
g_value_get_uint (g_value_array_get_nth (invals, 1)) + 1);
g_value_array_append (*outvals, NULL);
g_value_init (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1), DBUS_TYPE_G_OBJECT_PATH);
g_value_set_boxed (g_value_array_get_nth (*outvals, (*outvals)->n_values - 1),
g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2"));
return TRUE;
}
Commit Message:
CWE ID: CWE-264
Target: 1
Example 2:
Code: V0CustomElementMicrotaskRunQueue* Document::CustomElementMicrotaskRunQueue() {
if (!custom_element_microtask_run_queue_)
custom_element_microtask_run_queue_ =
V0CustomElementMicrotaskRunQueue::Create();
return custom_element_microtask_run_queue_.Get();
}
Commit Message: Cleanup and remove dead code in SetFocusedElement
This early-out was added in:
https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc
Back then, we applied fragment focus in LayoutUpdated() which could
cause this issue. This got cleaned up in:
https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2
so that focus is no longer applied after layout.
+Cleanup: Goto considered harmful
Bug: 795381
Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417
Commit-Queue: David Bokan <[email protected]>
Reviewed-by: Stefan Zager <[email protected]>
Cr-Commit-Position: refs/heads/master@{#641101}
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: setup_loginuid (gpointer data)
{
const char *id = data;
int fd;
fd = open ("/proc/self/loginuid", O_WRONLY);
write (fd, id, strlen (id));
close (fd);
}
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: long Cluster::GetFirst(const BlockEntry*& pFirst) const
{
if (m_entries_count <= 0)
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pFirst = NULL;
return status;
}
if (m_entries_count <= 0) //empty cluster
{
pFirst = NULL;
return 0;
}
}
assert(m_entries);
pFirst = m_entries[0];
assert(pFirst);
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: static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
bool check_only)
{
int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
int max_blocks = sbi->blocks_per_seg;
struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
unsigned long *discard_map = (unsigned long *)se->discard_map;
unsigned long *dmap = SIT_I(sbi)->tmp_map;
unsigned int start = 0, end = -1;
bool force = (cpc->reason & CP_DISCARD);
struct discard_entry *de = NULL;
struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
int i;
if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
return false;
if (!force) {
if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
SM_I(sbi)->dcc_info->nr_discards >=
SM_I(sbi)->dcc_info->max_discards)
return false;
}
/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
for (i = 0; i < entries; i++)
dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
while (force || SM_I(sbi)->dcc_info->nr_discards <=
SM_I(sbi)->dcc_info->max_discards) {
start = __find_rev_next_bit(dmap, max_blocks, end + 1);
if (start >= max_blocks)
break;
end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
if (force && start && end != max_blocks
&& (end - start) < cpc->trim_minlen)
continue;
if (check_only)
return true;
if (!de) {
de = f2fs_kmem_cache_alloc(discard_entry_slab,
GFP_F2FS_ZERO);
de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
list_add_tail(&de->list, head);
}
for (i = start; i < end; i++)
__set_bit_le(i, (void *)de->discard_map);
SM_I(sbi)->dcc_info->nr_discards += end - start;
}
return false;
}
Commit Message: f2fs: fix a panic caused by NULL flush_cmd_control
Mount fs with option noflush_merge, boot failed for illegal address
fcc in function f2fs_issue_flush:
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush); -> Here, fcc illegal
return ret;
}
Signed-off-by: Yunlei He <[email protected]>
Signed-off-by: Jaegeuk Kim <[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: static int tipc_nl_compat_node_dump(struct tipc_nl_compat_msg *msg,
struct nlattr **attrs)
{
struct tipc_node_info node_info;
struct nlattr *node[TIPC_NLA_NODE_MAX + 1];
int err;
if (!attrs[TIPC_NLA_NODE])
return -EINVAL;
err = nla_parse_nested(node, TIPC_NLA_NODE_MAX, attrs[TIPC_NLA_NODE],
NULL);
if (err)
return err;
node_info.addr = htonl(nla_get_u32(node[TIPC_NLA_NODE_ADDR]));
node_info.up = htonl(nla_get_flag(node[TIPC_NLA_NODE_UP]));
return tipc_add_tlv(msg->rep, TIPC_TLV_NODE_INFO, &node_info,
sizeof(node_info));
}
Commit Message: tipc: fix an infoleak in tipc_nl_compat_link_dump
link_info.str is a char array of size 60. Memory after the NULL
byte is not initialized. Sending the whole object out can cause
a leak.
Signed-off-by: Kangjie Lu <[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 int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr;
struct net *net = sock_net(sk);
__be32 v4addr = 0;
int addr_type;
int err;
if (!sock_flag(sk, SOCK_ZAPPED))
return -EINVAL;
if (addr->l2tp_family != AF_INET6)
return -EINVAL;
if (addr_len < sizeof(*addr))
return -EINVAL;
addr_type = ipv6_addr_type(&addr->l2tp_addr);
/* l2tp_ip6 sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
/* L2TP is point-point, not multicast */
if (addr_type & IPV6_ADDR_MULTICAST)
return -EADDRNOTAVAIL;
err = -EADDRINUSE;
read_lock_bh(&l2tp_ip6_lock);
if (__l2tp_ip6_bind_lookup(net, &addr->l2tp_addr,
sk->sk_bound_dev_if, addr->l2tp_conn_id))
goto out_in_use;
read_unlock_bh(&l2tp_ip6_lock);
lock_sock(sk);
err = -EINVAL;
if (sk->sk_state != TCP_CLOSE)
goto out_unlock;
/* Check if the address belongs to the host. */
rcu_read_lock();
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (addr_type & IPV6_ADDR_LINKLOCAL) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->l2tp_scope_id) {
/* Override any existing binding, if another
* one is supplied by user.
*/
sk->sk_bound_dev_if = addr->l2tp_scope_id;
}
/* Binding to link-local address requires an
interface */
if (!sk->sk_bound_dev_if)
goto out_unlock_rcu;
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk),
sk->sk_bound_dev_if);
if (!dev)
goto out_unlock_rcu;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0))
goto out_unlock_rcu;
}
rcu_read_unlock();
inet->inet_rcv_saddr = inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->l2tp_addr;
np->saddr = addr->l2tp_addr;
l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id;
write_lock_bh(&l2tp_ip6_lock);
sk_add_bind_node(sk, &l2tp_ip6_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip6_lock);
sock_reset_flag(sk, SOCK_ZAPPED);
release_sock(sk);
return 0;
out_unlock_rcu:
rcu_read_unlock();
out_unlock:
release_sock(sk);
return err;
out_in_use:
read_unlock_bh(&l2tp_ip6_lock);
return err;
}
Commit Message: l2tp: fix racy SOCK_ZAPPED flag check in l2tp_ip{,6}_bind()
Lock socket before checking the SOCK_ZAPPED flag in l2tp_ip6_bind().
Without lock, a concurrent call could modify the socket flags between
the sock_flag(sk, SOCK_ZAPPED) test and the lock_sock() call. This way,
a socket could be inserted twice in l2tp_ip6_bind_table. Releasing it
would then leave a stale pointer there, generating use-after-free
errors when walking through the list or modifying adjacent entries.
BUG: KASAN: use-after-free in l2tp_ip6_close+0x22e/0x290 at addr ffff8800081b0ed8
Write of size 8 by task syz-executor/10987
CPU: 0 PID: 10987 Comm: syz-executor Not tainted 4.8.0+ #39
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS rel-1.8.2-0-g33fbe13 by qemu-project.org 04/01/2014
ffff880031d97838 ffffffff829f835b ffff88001b5a1640 ffff8800081b0ec0
ffff8800081b15a0 ffff8800081b6d20 ffff880031d97860 ffffffff8174d3cc
ffff880031d978f0 ffff8800081b0e80 ffff88001b5a1640 ffff880031d978e0
Call Trace:
[<ffffffff829f835b>] dump_stack+0xb3/0x118 lib/dump_stack.c:15
[<ffffffff8174d3cc>] kasan_object_err+0x1c/0x70 mm/kasan/report.c:156
[< inline >] print_address_description mm/kasan/report.c:194
[<ffffffff8174d666>] kasan_report_error+0x1f6/0x4d0 mm/kasan/report.c:283
[< inline >] kasan_report mm/kasan/report.c:303
[<ffffffff8174db7e>] __asan_report_store8_noabort+0x3e/0x40 mm/kasan/report.c:329
[< inline >] __write_once_size ./include/linux/compiler.h:249
[< inline >] __hlist_del ./include/linux/list.h:622
[< inline >] hlist_del_init ./include/linux/list.h:637
[<ffffffff8579047e>] l2tp_ip6_close+0x22e/0x290 net/l2tp/l2tp_ip6.c:239
[<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415
[<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422
[<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570
[<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017
[<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208
[<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244
[<ffffffff813774f9>] task_work_run+0xf9/0x170
[<ffffffff81324aae>] do_exit+0x85e/0x2a00
[<ffffffff81326dc8>] do_group_exit+0x108/0x330
[<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307
[<ffffffff811b49af>] do_signal+0x7f/0x18f0
[<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156
[< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190
[<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259
[<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6
Object at ffff8800081b0ec0, in cache L2TP/IPv6 size: 1448
Allocated:
PID = 10987
[ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20
[ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0
[ 1116.897025] [<ffffffff8174c9ad>] kasan_kmalloc+0xad/0xe0
[ 1116.897025] [<ffffffff8174cee2>] kasan_slab_alloc+0x12/0x20
[ 1116.897025] [< inline >] slab_post_alloc_hook mm/slab.h:417
[ 1116.897025] [< inline >] slab_alloc_node mm/slub.c:2708
[ 1116.897025] [< inline >] slab_alloc mm/slub.c:2716
[ 1116.897025] [<ffffffff817476a8>] kmem_cache_alloc+0xc8/0x2b0 mm/slub.c:2721
[ 1116.897025] [<ffffffff84c4f6a9>] sk_prot_alloc+0x69/0x2b0 net/core/sock.c:1326
[ 1116.897025] [<ffffffff84c58ac8>] sk_alloc+0x38/0xae0 net/core/sock.c:1388
[ 1116.897025] [<ffffffff851ddf67>] inet6_create+0x2d7/0x1000 net/ipv6/af_inet6.c:182
[ 1116.897025] [<ffffffff84c4af7b>] __sock_create+0x37b/0x640 net/socket.c:1153
[ 1116.897025] [< inline >] sock_create net/socket.c:1193
[ 1116.897025] [< inline >] SYSC_socket net/socket.c:1223
[ 1116.897025] [<ffffffff84c4b46f>] SyS_socket+0xef/0x1b0 net/socket.c:1203
[ 1116.897025] [<ffffffff85e4d685>] entry_SYSCALL_64_fastpath+0x23/0xc6
Freed:
PID = 10987
[ 1116.897025] [<ffffffff811ddcb6>] save_stack_trace+0x16/0x20
[ 1116.897025] [<ffffffff8174c736>] save_stack+0x46/0xd0
[ 1116.897025] [<ffffffff8174cf61>] kasan_slab_free+0x71/0xb0
[ 1116.897025] [< inline >] slab_free_hook mm/slub.c:1352
[ 1116.897025] [< inline >] slab_free_freelist_hook mm/slub.c:1374
[ 1116.897025] [< inline >] slab_free mm/slub.c:2951
[ 1116.897025] [<ffffffff81748b28>] kmem_cache_free+0xc8/0x330 mm/slub.c:2973
[ 1116.897025] [< inline >] sk_prot_free net/core/sock.c:1369
[ 1116.897025] [<ffffffff84c541eb>] __sk_destruct+0x32b/0x4f0 net/core/sock.c:1444
[ 1116.897025] [<ffffffff84c5aca4>] sk_destruct+0x44/0x80 net/core/sock.c:1452
[ 1116.897025] [<ffffffff84c5ad33>] __sk_free+0x53/0x220 net/core/sock.c:1460
[ 1116.897025] [<ffffffff84c5af23>] sk_free+0x23/0x30 net/core/sock.c:1471
[ 1116.897025] [<ffffffff84c5cb6c>] sk_common_release+0x28c/0x3e0 ./include/net/sock.h:1589
[ 1116.897025] [<ffffffff8579044e>] l2tp_ip6_close+0x1fe/0x290 net/l2tp/l2tp_ip6.c:243
[ 1116.897025] [<ffffffff850b2dfd>] inet_release+0xed/0x1c0 net/ipv4/af_inet.c:415
[ 1116.897025] [<ffffffff851dc5a0>] inet6_release+0x50/0x70 net/ipv6/af_inet6.c:422
[ 1116.897025] [<ffffffff84c4581d>] sock_release+0x8d/0x1d0 net/socket.c:570
[ 1116.897025] [<ffffffff84c45976>] sock_close+0x16/0x20 net/socket.c:1017
[ 1116.897025] [<ffffffff817a108c>] __fput+0x28c/0x780 fs/file_table.c:208
[ 1116.897025] [<ffffffff817a1605>] ____fput+0x15/0x20 fs/file_table.c:244
[ 1116.897025] [<ffffffff813774f9>] task_work_run+0xf9/0x170
[ 1116.897025] [<ffffffff81324aae>] do_exit+0x85e/0x2a00
[ 1116.897025] [<ffffffff81326dc8>] do_group_exit+0x108/0x330
[ 1116.897025] [<ffffffff81348cf7>] get_signal+0x617/0x17a0 kernel/signal.c:2307
[ 1116.897025] [<ffffffff811b49af>] do_signal+0x7f/0x18f0
[ 1116.897025] [<ffffffff810039bf>] exit_to_usermode_loop+0xbf/0x150 arch/x86/entry/common.c:156
[ 1116.897025] [< inline >] prepare_exit_to_usermode arch/x86/entry/common.c:190
[ 1116.897025] [<ffffffff81006060>] syscall_return_slowpath+0x1a0/0x1e0 arch/x86/entry/common.c:259
[ 1116.897025] [<ffffffff85e4d726>] entry_SYSCALL_64_fastpath+0xc4/0xc6
Memory state around the buggy address:
ffff8800081b0d80: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
ffff8800081b0e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
>ffff8800081b0e80: fc fc fc fc fc fc fc fc fb fb fb fb fb fb fb fb
^
ffff8800081b0f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
ffff8800081b0f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
==================================================================
The same issue exists with l2tp_ip_bind() and l2tp_ip_bind_table.
Fixes: c51ce49735c1 ("l2tp: fix oops in L2TP IP sockets for connect() AF_UNSPEC case")
Reported-by: Baozeng Ding <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Baozeng Ding <[email protected]>
Signed-off-by: Guillaume Nault <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416
Target: 1
Example 2:
Code: static int cms_kari_set1_pkey(CMS_ContentInfo *cms, CMS_RecipientInfo *ri,
EVP_PKEY *pk, X509 *cert)
{
int i;
STACK_OF(CMS_RecipientEncryptedKey) *reks;
CMS_RecipientEncryptedKey *rek;
reks = CMS_RecipientInfo_kari_get0_reks(ri);
if (!cert)
return 0;
for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++)
{
int rv;
rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
if (CMS_RecipientEncryptedKey_cert_cmp(rek, cert))
continue;
CMS_RecipientInfo_kari_set0_pkey(ri, pk);
rv = CMS_RecipientInfo_kari_decrypt(cms, ri, rek);
CMS_RecipientInfo_kari_set0_pkey(ri, NULL);
if (rv > 0)
return 1;
return -1;
}
return 0;
}
Commit Message: Canonicalise input in CMS_verify.
If content is detached and not binary mode translate the input to
CRLF format. Before this change the input was verified verbatim
which lead to a discrepancy between sign and verify.
CWE ID: CWE-399
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 SampleTable::setTimeToSampleParams(
off64_t data_offset, size_t data_size) {
if (mTimeToSample != NULL || data_size < 8) {
return ERROR_MALFORMED;
}
uint8_t header[8];
if (mDataSource->readAt(
data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) {
return ERROR_IO;
}
if (U32_AT(header) != 0) {
return ERROR_MALFORMED;
}
mTimeToSampleCount = U32_AT(&header[4]);
uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t);
if (allocSize > SIZE_MAX) {
return ERROR_OUT_OF_RANGE;
}
mTimeToSample = new uint32_t[mTimeToSampleCount * 2];
size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2;
if (mDataSource->readAt(
data_offset + 8, mTimeToSample, size) < (ssize_t)size) {
return ERROR_IO;
}
for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) {
mTimeToSample[i] = ntohl(mTimeToSample[i]);
}
return OK;
}
Commit Message: Fix several ineffective integer overflow checks
Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added
several integer overflow checks. Unfortunately, those checks fail to take into
account integer promotion rules and are thus themselves subject to an integer
overflow. Cast the sizeof() operator to a uint64_t to force promotion while
multiplying.
Bug: 20139950
(cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32)
Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b
CWE ID: CWE-189
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: __u32 secure_tcpv6_sequence_number(__be32 *saddr, __be32 *daddr,
__be16 sport, __be16 dport)
{
__u32 seq;
__u32 hash[12];
struct keydata *keyptr = get_keyptr();
/* The procedure is the same as for IPv4, but addresses are longer.
* Thus we must use twothirdsMD4Transform.
*/
memcpy(hash, saddr, 16);
hash[4] = ((__force u16)sport << 16) + (__force u16)dport;
memcpy(&hash[5], keyptr->secret, sizeof(__u32) * 7);
seq = twothirdsMD4Transform((const __u32 *)daddr, hash) & HASH_MASK;
seq += keyptr->count;
seq += ktime_to_ns(ktime_get_real());
return seq;
}
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: 1
Example 2:
Code: static void jpg_finish_output(j_decompress_ptr cinfo, jpg_dest_t *dinfo)
{
JAS_DBGLOG(10, ("jpg_finish_output(%p, %p)\n", cinfo, dinfo));
/* Avoid compiler warnings about unused parameters. */
cinfo = 0;
dinfo = 0;
}
Commit Message: The generation of the configuration file jas_config.h has been completely
reworked in order to avoid pollution of the global namespace.
Some problematic types like uchar, ulong, and friends have been replaced
with names with a jas_ prefix.
An option max_samples has been added to the BMP and JPEG decoders to
restrict the maximum size of image that they can decode. This change
was made as a (possibly temporary) fix to address security concerns.
A max_samples command-line option has also been added to imginfo.
Whether an image component (for jas_image_t) is stored in memory or on
disk is now based on the component size (rather than the image size).
Some debug log message were added.
Some new integer overflow checks were added.
Some new safe integer add/multiply functions were added.
More pre-C99 cruft was removed. JasPer has numerous "hacks" to
handle pre-C99 compilers. JasPer now assumes C99 support. So, this
pre-C99 cruft is unnecessary and can be removed.
The regression jasper-doublefree-mem_close.jpg has been re-enabled.
Theoretically, it should work more predictably now.
CWE ID: CWE-190
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 CNBL::RegisterMappedNB(CNB *NB)
{
if (m_MappedBuffers.PushBack(NB) == m_BuffersNumber)
{
m_ParentTXPath->NBLMappingDone(this);
}
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[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: void* sspi_SecureHandleGetUpperPointer(SecHandle* handle)
{
void* pointer;
if (!handle)
return NULL;
pointer = (void*) ~((size_t) handle->dwUpper);
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: struct sta_info *sta_info_get(struct ieee80211_sub_if_data *sdata,
const u8 *addr)
{
struct ieee80211_local *local = sdata->local;
struct sta_info *sta;
sta = rcu_dereference_check(local->sta_hash[STA_HASH(addr)],
lockdep_is_held(&local->sta_mtx));
while (sta) {
if (sta->sdata == sdata &&
ether_addr_equal(sta->sta.addr, addr))
break;
sta = rcu_dereference_check(sta->hnext,
lockdep_is_held(&local->sta_mtx));
}
return sta;
}
Commit Message: mac80211: fix AP powersave TX vs. wakeup race
There is a race between the TX path and the STA wakeup: while
a station is sleeping, mac80211 buffers frames until it wakes
up, then the frames are transmitted. However, the RX and TX
path are concurrent, so the packet indicating wakeup can be
processed while a packet is being transmitted.
This can lead to a situation where the buffered frames list
is emptied on the one side, while a frame is being added on
the other side, as the station is still seen as sleeping in
the TX path.
As a result, the newly added frame will not be send anytime
soon. It might be sent much later (and out of order) when the
station goes to sleep and wakes up the next time.
Additionally, it can lead to the crash below.
Fix all this by synchronising both paths with a new lock.
Both path are not fastpath since they handle PS situations.
In a later patch we'll remove the extra skb queue locks to
reduce locking overhead.
BUG: unable to handle kernel
NULL pointer dereference at 000000b0
IP: [<ff6f1791>] ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
*pde = 00000000
Oops: 0000 [#1] SMP DEBUG_PAGEALLOC
EIP: 0060:[<ff6f1791>] EFLAGS: 00210282 CPU: 1
EIP is at ieee80211_report_used_skb+0x11/0x3e0 [mac80211]
EAX: e5900da0 EBX: 00000000 ECX: 00000001 EDX: 00000000
ESI: e41d00c0 EDI: e5900da0 EBP: ebe458e4 ESP: ebe458b0
DS: 007b ES: 007b FS: 00d8 GS: 00e0 SS: 0068
CR0: 8005003b CR2: 000000b0 CR3: 25a78000 CR4: 000407d0
DR0: 00000000 DR1: 00000000 DR2: 00000000 DR3: 00000000
DR6: ffff0ff0 DR7: 00000400
Process iperf (pid: 3934, ti=ebe44000 task=e757c0b0 task.ti=ebe44000)
iwlwifi 0000:02:00.0: I iwl_pcie_enqueue_hcmd Sending command LQ_CMD (#4e), seq: 0x0903, 92 bytes at 3[3]:9
Stack:
e403b32c ebe458c4 00200002 00200286 e403b338 ebe458cc c10960bb e5900da0
ff76a6ec ebe458d8 00000000 e41d00c0 e5900da0 ebe458f0 ff6f1b75 e403b210
ebe4598c ff723dc1 00000000 ff76a6ec e597c978 e403b758 00000002 00000002
Call Trace:
[<ff6f1b75>] ieee80211_free_txskb+0x15/0x20 [mac80211]
[<ff723dc1>] invoke_tx_handlers+0x1661/0x1780 [mac80211]
[<ff7248a5>] ieee80211_tx+0x75/0x100 [mac80211]
[<ff7249bf>] ieee80211_xmit+0x8f/0xc0 [mac80211]
[<ff72550e>] ieee80211_subif_start_xmit+0x4fe/0xe20 [mac80211]
[<c149ef70>] dev_hard_start_xmit+0x450/0x950
[<c14b9aa9>] sch_direct_xmit+0xa9/0x250
[<c14b9c9b>] __qdisc_run+0x4b/0x150
[<c149f732>] dev_queue_xmit+0x2c2/0xca0
Cc: [email protected]
Reported-by: Yaara Rozenblum <[email protected]>
Signed-off-by: Emmanuel Grumbach <[email protected]>
Reviewed-by: Stanislaw Gruszka <[email protected]>
[reword commit log, use a separate lock]
Signed-off-by: Johannes Berg <[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: filter_rsvd_memory (unsigned long start, unsigned long end, void *arg)
{
unsigned long range_start, range_end, prev_start;
void (*func)(unsigned long, unsigned long, int);
int i;
#if IGNORE_PFN0
if (start == PAGE_OFFSET) {
printk(KERN_WARNING "warning: skipping physical page 0\n");
start += PAGE_SIZE;
if (start >= end) return 0;
}
#endif
/*
* lowest possible address(walker uses virtual)
*/
prev_start = PAGE_OFFSET;
func = arg;
for (i = 0; i < num_rsvd_regions; ++i) {
range_start = max(start, prev_start);
range_end = min(end, rsvd_region[i].start);
if (range_start < range_end)
call_pernode_memory(__pa(range_start), range_end - range_start, func);
/* nothing more available in this segment */
if (range_end == end) return 0;
prev_start = rsvd_region[i].end;
}
/* end of memory marker allows full processing inside loop body */
return 0;
}
Commit Message: [IA64] Workaround for RSE issue
Problem: An application violating the architectural rules regarding
operation dependencies and having specific Register Stack Engine (RSE)
state at the time of the violation, may result in an illegal operation
fault and invalid RSE state. Such faults may initiate a cascade of
repeated illegal operation faults within OS interruption handlers.
The specific behavior is OS dependent.
Implication: An application causing an illegal operation fault with
specific RSE state may result in a series of illegal operation faults
and an eventual OS stack overflow condition.
Workaround: OS interruption handlers that switch to kernel backing
store implement a check for invalid RSE state to avoid the series
of illegal operation faults.
The core of the workaround is the RSE_WORKAROUND code sequence
inserted into each invocation of the SAVE_MIN_WITH_COVER and
SAVE_MIN_WITH_COVER_R19 macros. This sequence includes hard-coded
constants that depend on the number of stacked physical registers
being 96. The rest of this patch consists of code to disable this
workaround should this not be the case (with the presumption that
if a future Itanium processor increases the number of registers, it
would also remove the need for this patch).
Move the start of the RBS up to a mod32 boundary to avoid some
corner cases.
The dispatch_illegal_op_fault code outgrew the spot it was
squatting in when built with this patch and CONFIG_VIRT_CPU_ACCOUNTING=y
Move it out to the end of the ivt.
Signed-off-by: Tony Luck <[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 RList *relocs(RBinFile *arch) {
struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj;
RList *list = r_list_newf ((RListFree)free);
int i, len, n_got, amount;
if (!list || !obj) {
r_list_free (list);
return NULL;
}
if (obj->hdr->flags & FLAT_FLAG_GOTPIC) {
n_got = get_ngot_entries (obj);
if (n_got) {
amount = n_got * sizeof (ut32);
if (amount < n_got || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *got_table = calloc (1, n_got * sizeof (ut32));
if (got_table) {
ut32 offset = 0;
for (i = 0; i < n_got ; offset += 4, i++) {
ut32 got_entry;
if (obj->hdr->data_start + offset + 4 > obj->size ||
obj->hdr->data_start + offset + 4 < offset) {
break;
}
len = r_buf_read_at (obj->b, obj->hdr->data_start + offset,
(ut8 *)&got_entry, sizeof (ut32));
if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) {
break;
}
got_table[i].addr_to_patch = got_entry;
got_table[i].data_offset = got_entry + BFLT_HDR_SIZE;
}
obj->n_got = n_got;
obj->got_table = got_table;
}
}
}
if (obj->hdr->reloc_count > 0) {
int n_reloc = obj->hdr->reloc_count;
amount = n_reloc * sizeof (struct reloc_struct_t);
if (amount < n_reloc || amount > UT32_MAX) {
goto out_error;
}
struct reloc_struct_t *reloc_table = calloc (1, amount + 1);
if (!reloc_table) {
goto out_error;
}
amount = n_reloc * sizeof (ut32);
if (amount < n_reloc || amount > UT32_MAX) {
free (reloc_table);
goto out_error;
}
ut32 *reloc_pointer_table = calloc (1, amount + 1);
if (!reloc_pointer_table) {
free (reloc_table);
goto out_error;
}
if (obj->hdr->reloc_start + amount > obj->size ||
obj->hdr->reloc_start + amount < amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, obj->hdr->reloc_start,
(ut8 *)reloc_pointer_table, amount);
if (len != amount) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
for (i = 0; i < obj->hdr->reloc_count; i++) {
ut32 reloc_offset =
r_swap_ut32 (reloc_pointer_table[i]) +
BFLT_HDR_SIZE;
if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) {
ut32 reloc_fixed, reloc_data_offset;
if (reloc_offset + sizeof (ut32) > obj->size ||
reloc_offset + sizeof (ut32) < reloc_offset) {
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
len = r_buf_read_at (obj->b, reloc_offset,
(ut8 *)&reloc_fixed,
sizeof (ut32));
if (len != sizeof (ut32)) {
eprintf ("problem while reading relocation entries\n");
free (reloc_table);
free (reloc_pointer_table);
goto out_error;
}
reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE;
reloc_table[i].addr_to_patch = reloc_offset;
reloc_table[i].data_offset = reloc_data_offset;
RBinReloc *reloc = R_NEW0 (RBinReloc);
if (reloc) {
reloc->type = R_BIN_RELOC_32;
reloc->paddr = reloc_table[i].addr_to_patch;
reloc->vaddr = reloc->paddr;
r_list_append (list, reloc);
}
}
}
free (reloc_pointer_table);
obj->reloc_table = reloc_table;
}
return list;
out_error:
r_list_free (list);
return NULL;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119
Target: 1
Example 2:
Code: void show_stack(struct task_struct *tsk, unsigned long *sp)
{
unsigned long stack;
if (!tsk)
tsk = current;
if (tsk == current)
sp = (unsigned long *)current_stack_pointer;
else
sp = (unsigned long *)tsk->thread.sp;
stack = (unsigned long)sp;
dump_mem("Stack: ", stack, THREAD_SIZE +
(unsigned long)task_stack_page(tsk));
show_trace(tsk, sp, NULL);
}
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: scoped_refptr<TestUrlData> last_url_data() {
EXPECT_TRUE(last_url_data_);
return last_url_data_;
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732
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 MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
SkipRGBMipmaps(image, dds_info, 3);
return MagickTrue;
}
Commit Message: Added extra EOF check and some minor refactoring.
CWE ID: CWE-20
Target: 1
Example 2:
Code: authentic_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
struct sc_context *ctx = card->ctx;
struct authentic_private_data *prv_data = (struct authentic_private_data *) card->drv_data;
int rv;
LOG_FUNC_CALLED(ctx);
if (!card->serialnr.len) {
rv = authentic_get_cplc(card);
LOG_TEST_RET(ctx, rv, "get CPLC data error");
card->serialnr.len = 4;
memcpy(card->serialnr.value, prv_data->cplc.value + 15, 4);
sc_log(ctx, "serial %02X%02X%02X%02X",
card->serialnr.value[0], card->serialnr.value[1],
card->serialnr.value[2], card->serialnr.value[3]);
}
if (serial)
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds reads
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting and suggesting security fixes.
CWE ID: CWE-125
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 RenderWidgetHostImpl::RendererIsUnresponsive() {
NotificationService::current()->Notify(
NOTIFICATION_RENDER_WIDGET_HOST_HANG,
Source<RenderWidgetHost>(this),
NotificationService::NoDetails());
is_unresponsive_ = true;
if (delegate_)
delegate_->RendererUnresponsive(this);
}
Commit Message: Check that RWHI isn't deleted manually while owned by a scoped_ptr in RVHI
BUG=590284
Review URL: https://codereview.chromium.org/1747183002
Cr-Commit-Position: refs/heads/master@{#378844}
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: png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size,
png_bytep output, png_size_t output_size)
{
png_size_t count = 0;
png_ptr->zstream.next_in = (png_bytep)data; /* const_cast: VALID */
png_ptr->zstream.avail_in = size;
while (1)
{
int ret, avail;
/* Reset the output buffer each time round - we empty it
* after every inflate call.
*/
png_ptr->zstream.next_out = png_ptr->zbuf;
png_ptr->zstream.avail_out = png_ptr->zbuf_size;
ret = inflate(&png_ptr->zstream, Z_NO_FLUSH);
avail = png_ptr->zbuf_size - png_ptr->zstream.avail_out;
/* First copy/count any new output - but only if we didn't
* get an error code.
*/
if ((ret == Z_OK || ret == Z_STREAM_END) && avail > 0)
{
if (output != 0 && output_size > count)
{
int copy = output_size - count;
if (avail < copy) copy = avail;
png_memcpy(output + count, png_ptr->zbuf, copy);
}
count += avail;
}
if (ret == Z_OK)
continue;
/* Termination conditions - always reset the zstream, it
* must be left in inflateInit state.
*/
png_ptr->zstream.avail_in = 0;
inflateReset(&png_ptr->zstream);
if (ret == Z_STREAM_END)
return count; /* NOTE: may be zero. */
/* Now handle the error codes - the API always returns 0
* and the error message is dumped into the uncompressed
* buffer if available.
*/
{
PNG_CONST char *msg;
if (png_ptr->zstream.msg != 0)
msg = png_ptr->zstream.msg;
else
{
#if defined(PNG_STDIO_SUPPORTED) && !defined(_WIN32_WCE)
char umsg[52];
switch (ret)
{
case Z_BUF_ERROR:
msg = "Buffer error in compressed datastream in %s chunk";
break;
case Z_DATA_ERROR:
msg = "Data error in compressed datastream in %s chunk";
break;
default:
msg = "Incomplete compressed datastream in %s chunk";
break;
}
png_snprintf(umsg, sizeof umsg, msg, png_ptr->chunk_name);
msg = umsg;
#else
msg = "Damaged compressed datastream in chunk other than IDAT";
#endif
}
png_warning(png_ptr, msg);
}
/* 0 means an error - notice that this code simple ignores
* zero length compressed chunks as a result.
*/
return 0;
}
}
Commit Message: Pull follow-up tweak from upstream.
BUG=116162
Review URL: http://codereview.chromium.org/9546033
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@125311 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189
Target: 1
Example 2:
Code: void RenderProcessHostImpl::OnChannelError() {
ProcessDied(true /* already_dead */);
}
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: 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: ReadUserLogState::EventNum( const ReadUserLog::FileState &state ) const
{
const ReadUserLogFileState::FileState *istate;
if ( ( !convertState(state, istate) ) || ( !istate->m_version ) ) {
return -1;
}
return (filesize_t) istate->m_event_num.asint;
}
Commit Message:
CWE ID: CWE-134
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 GpuProcessHostUIShim::OnAcceleratedSurfaceNew(
const GpuHostMsg_AcceleratedSurfaceNew_Params& params) {
RenderWidgetHostViewPort* view = GetRenderWidgetHostViewFromSurfaceID(
params.surface_id);
if (!view)
return;
view->AcceleratedSurfaceNew(
params.width, params.height, params.surface_handle);
}
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: static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb,
struct tcp_sacktag_state *state,
u32 start_seq, u32 end_seq,
int dup_sack)
{
struct tcp_sock *tp = tcp_sk(sk);
struct sk_buff *prev;
int mss;
int pcount = 0;
int len;
int in_sack;
if (!sk_can_gso(sk))
goto fallback;
/* Normally R but no L won't result in plain S */
if (!dup_sack &&
(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS)
goto fallback;
if (!skb_can_shift(skb))
goto fallback;
/* This frame is about to be dropped (was ACKed). */
if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una))
goto fallback;
/* Can only happen with delayed DSACK + discard craziness */
if (unlikely(skb == tcp_write_queue_head(sk)))
goto fallback;
prev = tcp_write_queue_prev(sk, skb);
if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED)
goto fallback;
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) &&
!before(end_seq, TCP_SKB_CB(skb)->end_seq);
if (in_sack) {
len = skb->len;
pcount = tcp_skb_pcount(skb);
mss = tcp_skb_seglen(skb);
/* TODO: Fix DSACKs to not fragment already SACKed and we can
* drop this restriction as unnecessary
*/
if (mss != tcp_skb_seglen(prev))
goto fallback;
} else {
if (!after(TCP_SKB_CB(skb)->end_seq, start_seq))
goto noop;
/* CHECKME: This is non-MSS split case only?, this will
* cause skipped skbs due to advancing loop btw, original
* has that feature too
*/
if (tcp_skb_pcount(skb) <= 1)
goto noop;
in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq);
if (!in_sack) {
/* TODO: head merge to next could be attempted here
* if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)),
* though it might not be worth of the additional hassle
*
* ...we can probably just fallback to what was done
* previously. We could try merging non-SACKed ones
* as well but it probably isn't going to buy off
* because later SACKs might again split them, and
* it would make skb timestamp tracking considerably
* harder problem.
*/
goto fallback;
}
len = end_seq - TCP_SKB_CB(skb)->seq;
BUG_ON(len < 0);
BUG_ON(len > skb->len);
/* MSS boundaries should be honoured or else pcount will
* severely break even though it makes things bit trickier.
* Optimize common case to avoid most of the divides
*/
mss = tcp_skb_mss(skb);
/* TODO: Fix DSACKs to not fragment already SACKed and we can
* drop this restriction as unnecessary
*/
if (mss != tcp_skb_seglen(prev))
goto fallback;
if (len == mss) {
pcount = 1;
} else if (len < mss) {
goto noop;
} else {
pcount = len / mss;
len = pcount * mss;
}
}
if (!skb_shift(prev, skb, len))
goto fallback;
if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack))
goto out;
/* Hole filled allows collapsing with the next as well, this is very
* useful when hole on every nth skb pattern happens
*/
if (prev == tcp_write_queue_tail(sk))
goto out;
skb = tcp_write_queue_next(sk, prev);
if (!skb_can_shift(skb) ||
(skb == tcp_send_head(sk)) ||
((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) ||
(mss != tcp_skb_seglen(skb)))
goto out;
len = skb->len;
if (skb_shift(prev, skb, len)) {
pcount += tcp_skb_pcount(skb);
tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0);
}
out:
state->fack_count += pcount;
return prev;
noop:
return skb;
fallback:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK);
return NULL;
}
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: LogoServiceFactory::LogoServiceFactory()
: BrowserContextKeyedServiceFactory(
"LogoService",
BrowserContextDependencyManager::GetInstance()) {
DependsOn(TemplateURLServiceFactory::GetInstance());
}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119
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 RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
RenderStyle* newStyle = style();
if (!isAnonymousBlock()) {
for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
RenderBoxModelObject* nextCont = currCont->continuation();
currCont->setContinuation(0);
currCont->setStyle(newStyle);
currCont->setContinuation(nextCont);
}
}
if (FastTextAutosizer* textAutosizer = document().fastTextAutosizer())
textAutosizer->record(this);
propagateStyleToAnonymousChildren(true);
invalidateLineHeight();
m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
Vector<ImageResource*> images;
appendImagesFromStyle(images, *newStyle);
if (images.isEmpty())
ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
else
ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
}
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: 1
Example 2:
Code: LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb) const
{
LayoutUnit logicalTopPosition = logicalTop();
LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false) - childMarginStart - childMarginEnd;
if (childMarginStart > 0) {
LayoutUnit startContentSide = cb->startOffsetForContent();
LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false);
if (startOffset > startContentSideWithMargin)
result += childMarginStart;
else
result += startOffset - startContentSide;
}
if (childMarginEnd > 0) {
LayoutUnit endContentSide = cb->endOffsetForContent();
LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false);
if (endOffset > endContentSideWithMargin)
result += childMarginEnd;
else
result += endOffset - endContentSide;
}
return result;
}
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: ecryptfs_write_metadata_to_contents(struct inode *ecryptfs_inode,
char *virt, size_t virt_len)
{
int rc;
rc = ecryptfs_write_lower(ecryptfs_inode, virt,
0, virt_len);
if (rc < 0)
printk(KERN_ERR "%s: Error attempting to write header "
"information to lower file; rc = [%d]\n", __func__, rc);
else
rc = 0;
return rc;
}
Commit Message: eCryptfs: Remove buggy and unnecessary write in file name decode routine
Dmitry Chernenkov used KASAN to discover that eCryptfs writes past the
end of the allocated buffer during encrypted filename decoding. This
fix corrects the issue by getting rid of the unnecessary 0 write when
the current bit offset is 2.
Signed-off-by: Michael Halcrow <[email protected]>
Reported-by: Dmitry Chernenkov <[email protected]>
Suggested-by: Kees Cook <[email protected]>
Cc: [email protected] # v2.6.29+: 51ca58d eCryptfs: Filename Encryption: Encoding and encryption functions
Signed-off-by: Tyler Hicks <[email protected]>
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: static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
unlink(src);
}
Commit Message: security fix
CWE ID: CWE-269
Target: 1
Example 2:
Code: error::Error GLES2DecoderPassthroughImpl::DoSetDisjointValueSyncCHROMIUM(
DisjointValueSync* sync) {
NOTIMPLEMENTED();
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 RELOC_PTRS_WITH(device_forward_reloc_ptrs, gx_device_forward *fdev)
{
fdev->target = gx_device_reloc_ptr(fdev->target, gcst);
}
Commit Message:
CWE ID: CWE-78
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) {
FILE *infile = NULL;
vpx_codec_ctx_t codec;
vpx_codec_enc_cfg_t cfg;
int frame_count = 0;
vpx_image_t raw;
vpx_codec_err_t res;
VpxVideoInfo info = {0};
VpxVideoWriter *writer = NULL;
const VpxInterface *encoder = NULL;
const int fps = 30; // TODO(dkovalev) add command line argument
const int bitrate = 200; // kbit/s TODO(dkovalev) add command line argument
int keyframe_interval = 0;
const char *codec_arg = NULL;
const char *width_arg = NULL;
const char *height_arg = NULL;
const char *infile_arg = NULL;
const char *outfile_arg = NULL;
const char *keyframe_interval_arg = NULL;
exec_name = argv[0];
if (argc < 7)
die("Invalid number of arguments");
codec_arg = argv[1];
width_arg = argv[2];
height_arg = argv[3];
infile_arg = argv[4];
outfile_arg = argv[5];
keyframe_interval_arg = argv[6];
encoder = get_vpx_encoder_by_name(codec_arg);
if (!encoder)
die("Unsupported codec.");
info.codec_fourcc = encoder->fourcc;
info.frame_width = strtol(width_arg, NULL, 0);
info.frame_height = strtol(height_arg, NULL, 0);
info.time_base.numerator = 1;
info.time_base.denominator = fps;
if (info.frame_width <= 0 ||
info.frame_height <= 0 ||
(info.frame_width % 2) != 0 ||
(info.frame_height % 2) != 0) {
die("Invalid frame size: %dx%d", info.frame_width, info.frame_height);
}
if (!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, info.frame_width,
info.frame_height, 1)) {
die("Failed to allocate image.");
}
keyframe_interval = strtol(keyframe_interval_arg, NULL, 0);
if (keyframe_interval < 0)
die("Invalid keyframe interval value.");
printf("Using %s\n", vpx_codec_iface_name(encoder->interface()));
res = vpx_codec_enc_config_default(encoder->interface(), &cfg, 0);
if (res)
die_codec(&codec, "Failed to get default codec config.");
cfg.g_w = info.frame_width;
cfg.g_h = info.frame_height;
cfg.g_timebase.num = info.time_base.numerator;
cfg.g_timebase.den = info.time_base.denominator;
cfg.rc_target_bitrate = bitrate;
cfg.g_error_resilient = argc > 7 ? strtol(argv[7], NULL, 0) : 0;
writer = vpx_video_writer_open(outfile_arg, kContainerIVF, &info);
if (!writer)
die("Failed to open %s for writing.", outfile_arg);
if (!(infile = fopen(infile_arg, "rb")))
die("Failed to open %s for reading.", infile_arg);
if (vpx_codec_enc_init(&codec, encoder->interface(), &cfg, 0))
die_codec(&codec, "Failed to initialize encoder");
while (vpx_img_read(&raw, infile)) {
int flags = 0;
if (keyframe_interval > 0 && frame_count % keyframe_interval == 0)
flags |= VPX_EFLAG_FORCE_KF;
encode_frame(&codec, &raw, frame_count++, flags, writer);
}
encode_frame(&codec, NULL, -1, 0, writer); // flush the encoder
printf("\n");
fclose(infile);
printf("Processed %d frames.\n", frame_count);
vpx_img_free(&raw);
if (vpx_codec_destroy(&codec))
die_codec(&codec, "Failed to destroy codec.");
vpx_video_writer_close(writer);
return EXIT_SUCCESS;
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void ccid3_hc_rx_exit(struct sock *sk)
{
struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk);
tfrc_rx_hist_purge(&hc->rx_hist);
tfrc_lh_cleanup(&hc->rx_li_hist);
}
Commit Message: dccp: fix info leak via getsockopt(DCCP_SOCKOPT_CCID_TX_INFO)
The CCID3 code fails to initialize the trailing padding bytes of struct
tfrc_tx_info added for alignment on 64 bit architectures. It that for
potentially leaks four bytes kernel stack via the getsockopt() syscall.
Add an explicit memset(0) before filling the structure to avoid the
info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Gerrit Renker <[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: u32 _ilog_(u32 v)
{
u32 ret=0;
while(v) {
ret++;
v>>=1;
}
return(ret);
}
Commit Message: fix some exploitable overflows (#994, #997)
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 DownloadRequestLimiter::TabDownloadState::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
if (status_ == ALLOW_ONE_DOWNLOAD ||
(status_ == PROMPT_BEFORE_DOWNLOAD &&
!navigation_handle->IsRendererInitiated())) {
NotifyCallbacks(false);
host_->Remove(this, web_contents());
}
}
Commit Message: Don't reset TabDownloadState on history back/forward
Currently performing forward/backward on a tab will reset the TabDownloadState.
Which allows javascript code to do trigger multiple downloads.
This CL disables that behavior by not resetting the TabDownloadState on
forward/back.
It is still possible to reset the TabDownloadState through user gesture
or using browser initiated download.
BUG=848535
Change-Id: I7f9bf6e8fb759b4dcddf5ac0c214e8c6c9f48863
Reviewed-on: https://chromium-review.googlesource.com/1108959
Commit-Queue: Min Qin <[email protected]>
Reviewed-by: Xing Liu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#574437}
CWE ID:
Target: 1
Example 2:
Code: static int ptrace_signal(int signr, siginfo_t *info,
struct pt_regs *regs, void *cookie)
{
if (!task_ptrace(current))
return signr;
ptrace_signal_deliver(regs, cookie);
/* Let the debugger run. */
ptrace_stop(signr, 0, info);
/* We're back. Did the debugger cancel the sig? */
signr = current->exit_code;
if (signr == 0)
return signr;
current->exit_code = 0;
/* Update the siginfo structure if the signal has
changed. If the debugger wanted something
specific in the siginfo structure then it should
have updated *info via PTRACE_SETSIGINFO. */
if (signr != info->si_signo) {
info->si_signo = signr;
info->si_errno = 0;
info->si_code = SI_USER;
info->si_pid = task_pid_vnr(current->parent);
info->si_uid = task_uid(current->parent);
}
/* If the (new) signal is now blocked, requeue it. */
if (sigismember(¤t->blocked, signr)) {
specific_send_sig_info(signr, info, current);
signr = 0;
}
return signr;
}
Commit Message: Prevent rt_sigqueueinfo and rt_tgsigqueueinfo from spoofing the signal code
Userland should be able to trust the pid and uid of the sender of a
signal if the si_code is SI_TKILL.
Unfortunately, the kernel has historically allowed sigqueueinfo() to
send any si_code at all (as long as it was negative - to distinguish it
from kernel-generated signals like SIGILL etc), so it could spoof a
SI_TKILL with incorrect siginfo values.
Happily, it looks like glibc has always set si_code to the appropriate
SI_QUEUE, so there are probably no actual user code that ever uses
anything but the appropriate SI_QUEUE flag.
So just tighten the check for si_code (we used to allow any negative
value), and add a (one-time) warning in case there are binaries out
there that might depend on using other si_code values.
Signed-off-by: Julien Tinnes <[email protected]>
Acked-by: Oleg Nesterov <[email protected]>
Signed-off-by: Linus Torvalds <[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: nvmet_fc_find_target_queue(struct nvmet_fc_tgtport *tgtport,
u64 connection_id)
{
struct nvmet_fc_tgt_assoc *assoc;
struct nvmet_fc_tgt_queue *queue;
u64 association_id = nvmet_fc_getassociationid(connection_id);
u16 qid = nvmet_fc_getqueueid(connection_id);
unsigned long flags;
spin_lock_irqsave(&tgtport->lock, flags);
list_for_each_entry(assoc, &tgtport->assoc_list, a_list) {
if (association_id == assoc->association_id) {
queue = assoc->queues[qid];
if (queue &&
(!atomic_read(&queue->connected) ||
!nvmet_fc_tgt_q_get(queue)))
queue = NULL;
spin_unlock_irqrestore(&tgtport->lock, flags);
return queue;
}
}
spin_unlock_irqrestore(&tgtport->lock, flags);
return NULL;
}
Commit Message: nvmet-fc: ensure target queue id within range.
When searching for queue id's ensure they are within the expected range.
Signed-off-by: James Smart <[email protected]>
Signed-off-by: Christoph Hellwig <[email protected]>
Signed-off-by: Jens Axboe <[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: xps_parse_path(xps_document *doc, const fz_matrix *ctm, char *base_uri, xps_resource *dict, fz_xml *root)
{
fz_xml *node;
char *fill_uri;
char *stroke_uri;
char *opacity_mask_uri;
char *transform_att;
char *clip_att;
char *data_att;
char *fill_att;
char *stroke_att;
char *opacity_att;
char *opacity_mask_att;
fz_xml *transform_tag = NULL;
fz_xml *clip_tag = NULL;
fz_xml *data_tag = NULL;
fz_xml *fill_tag = NULL;
fz_xml *stroke_tag = NULL;
fz_xml *opacity_mask_tag = NULL;
char *fill_opacity_att = NULL;
char *stroke_opacity_att = NULL;
char *stroke_dash_array_att;
char *stroke_dash_cap_att;
char *stroke_dash_offset_att;
char *stroke_end_line_cap_att;
char *stroke_start_line_cap_att;
char *stroke_line_join_att;
char *stroke_miter_limit_att;
char *stroke_thickness_att;
char *navigate_uri_att;
fz_stroke_state *stroke = NULL;
fz_matrix transform;
float samples[32];
fz_colorspace *colorspace;
fz_path *path = NULL;
fz_path *stroke_path = NULL;
fz_rect area;
int fill_rule;
int dash_len = 0;
fz_matrix local_ctm;
/*
* Extract attributes and extended attributes.
*/
transform_att = fz_xml_att(root, "RenderTransform");
clip_att = fz_xml_att(root, "Clip");
data_att = fz_xml_att(root, "Data");
fill_att = fz_xml_att(root, "Fill");
stroke_att = fz_xml_att(root, "Stroke");
opacity_att = fz_xml_att(root, "Opacity");
opacity_mask_att = fz_xml_att(root, "OpacityMask");
stroke_dash_array_att = fz_xml_att(root, "StrokeDashArray");
stroke_dash_cap_att = fz_xml_att(root, "StrokeDashCap");
stroke_dash_offset_att = fz_xml_att(root, "StrokeDashOffset");
stroke_end_line_cap_att = fz_xml_att(root, "StrokeEndLineCap");
stroke_start_line_cap_att = fz_xml_att(root, "StrokeStartLineCap");
stroke_line_join_att = fz_xml_att(root, "StrokeLineJoin");
stroke_miter_limit_att = fz_xml_att(root, "StrokeMiterLimit");
stroke_thickness_att = fz_xml_att(root, "StrokeThickness");
navigate_uri_att = fz_xml_att(root, "FixedPage.NavigateUri");
for (node = fz_xml_down(root); node; node = fz_xml_next(node))
{
if (!strcmp(fz_xml_tag(node), "Path.RenderTransform"))
transform_tag = fz_xml_down(node);
if (!strcmp(fz_xml_tag(node), "Path.OpacityMask"))
opacity_mask_tag = fz_xml_down(node);
if (!strcmp(fz_xml_tag(node), "Path.Clip"))
clip_tag = fz_xml_down(node);
if (!strcmp(fz_xml_tag(node), "Path.Fill"))
fill_tag = fz_xml_down(node);
if (!strcmp(fz_xml_tag(node), "Path.Stroke"))
stroke_tag = fz_xml_down(node);
if (!strcmp(fz_xml_tag(node), "Path.Data"))
data_tag = fz_xml_down(node);
}
fill_uri = base_uri;
stroke_uri = base_uri;
opacity_mask_uri = base_uri;
xps_resolve_resource_reference(doc, dict, &data_att, &data_tag, NULL);
xps_resolve_resource_reference(doc, dict, &clip_att, &clip_tag, NULL);
xps_resolve_resource_reference(doc, dict, &transform_att, &transform_tag, NULL);
xps_resolve_resource_reference(doc, dict, &fill_att, &fill_tag, &fill_uri);
xps_resolve_resource_reference(doc, dict, &stroke_att, &stroke_tag, &stroke_uri);
xps_resolve_resource_reference(doc, dict, &opacity_mask_att, &opacity_mask_tag, &opacity_mask_uri);
/*
* Act on the information we have gathered:
*/
if (!data_att && !data_tag)
return;
if (fill_tag && !strcmp(fz_xml_tag(fill_tag), "SolidColorBrush"))
{
fill_opacity_att = fz_xml_att(fill_tag, "Opacity");
fill_att = fz_xml_att(fill_tag, "Color");
fill_tag = NULL;
}
if (stroke_tag && !strcmp(fz_xml_tag(stroke_tag), "SolidColorBrush"))
{
stroke_opacity_att = fz_xml_att(stroke_tag, "Opacity");
stroke_att = fz_xml_att(stroke_tag, "Color");
stroke_tag = NULL;
}
if (stroke_att || stroke_tag)
{
if (stroke_dash_array_att)
{
char *s = stroke_dash_array_att;
while (*s)
{
while (*s == ' ')
s++;
if (*s) /* needed in case of a space before the last quote */
dash_len++;
while (*s && *s != ' ')
s++;
}
}
stroke = fz_new_stroke_state_with_dash_len(doc->ctx, dash_len);
stroke->start_cap = xps_parse_line_cap(stroke_start_line_cap_att);
stroke->dash_cap = xps_parse_line_cap(stroke_dash_cap_att);
stroke->end_cap = xps_parse_line_cap(stroke_end_line_cap_att);
stroke->linejoin = FZ_LINEJOIN_MITER_XPS;
if (stroke_line_join_att)
{
if (!strcmp(stroke_line_join_att, "Miter")) stroke->linejoin = FZ_LINEJOIN_MITER_XPS;
if (!strcmp(stroke_line_join_att, "Round")) stroke->linejoin = FZ_LINEJOIN_ROUND;
if (!strcmp(stroke_line_join_att, "Bevel")) stroke->linejoin = FZ_LINEJOIN_BEVEL;
}
stroke->miterlimit = 10;
if (stroke_miter_limit_att)
stroke->miterlimit = fz_atof(stroke_miter_limit_att);
stroke->linewidth = 1;
if (stroke_thickness_att)
stroke->linewidth = fz_atof(stroke_thickness_att);
stroke->dash_phase = 0;
stroke->dash_len = 0;
if (stroke_dash_array_att)
{
char *s = stroke_dash_array_att;
if (stroke_dash_offset_att)
stroke->dash_phase = fz_atof(stroke_dash_offset_att) * stroke->linewidth;
while (*s)
{
while (*s == ' ')
s++;
if (*s) /* needed in case of a space before the last quote */
stroke->dash_list[stroke->dash_len++] = fz_atof(s) * stroke->linewidth;
while (*s && *s != ' ')
s++;
}
stroke->dash_len = dash_len;
}
}
transform = fz_identity;
if (transform_att)
xps_parse_render_transform(doc, transform_att, &transform);
if (transform_tag)
xps_parse_matrix_transform(doc, transform_tag, &transform);
fz_concat(&local_ctm, &transform, ctm);
if (clip_att || clip_tag)
xps_clip(doc, &local_ctm, dict, clip_att, clip_tag);
fill_rule = 0;
if (data_att)
path = xps_parse_abbreviated_geometry(doc, data_att, &fill_rule);
else if (data_tag)
{
path = xps_parse_path_geometry(doc, dict, data_tag, 0, &fill_rule);
if (stroke_att || stroke_tag)
stroke_path = xps_parse_path_geometry(doc, dict, data_tag, 1, &fill_rule);
}
if (!stroke_path)
stroke_path = path;
if (stroke_att || stroke_tag)
{
fz_bound_path(doc->ctx, stroke_path, stroke, &local_ctm, &area);
if (stroke_path != path && (fill_att || fill_tag)) {
fz_rect bounds;
fz_bound_path(doc->ctx, path, NULL, &local_ctm, &bounds);
fz_union_rect(&area, &bounds);
}
}
else
fz_bound_path(doc->ctx, path, NULL, &local_ctm, &area);
if (navigate_uri_att)
xps_add_link(doc, &area, base_uri, navigate_uri_att);
xps_begin_opacity(doc, &local_ctm, &area, opacity_mask_uri, dict, opacity_att, opacity_mask_tag);
if (fill_att)
{
xps_parse_color(doc, base_uri, fill_att, &colorspace, samples);
if (fill_opacity_att)
samples[0] *= fz_atof(fill_opacity_att);
xps_set_color(doc, colorspace, samples);
fz_fill_path(doc->dev, path, fill_rule == 0, &local_ctm,
doc->colorspace, doc->color, doc->alpha);
}
if (fill_tag)
{
fz_clip_path(doc->dev, path, &area, fill_rule == 0, &local_ctm);
xps_parse_brush(doc, &local_ctm, &area, fill_uri, dict, fill_tag);
fz_pop_clip(doc->dev);
}
if (stroke_att)
{
xps_parse_color(doc, base_uri, stroke_att, &colorspace, samples);
if (stroke_opacity_att)
samples[0] *= fz_atof(stroke_opacity_att);
xps_set_color(doc, colorspace, samples);
fz_stroke_path(doc->dev, stroke_path, stroke, &local_ctm,
doc->colorspace, doc->color, doc->alpha);
}
if (stroke_tag)
{
fz_clip_stroke_path(doc->dev, stroke_path, &area, stroke, &local_ctm);
xps_parse_brush(doc, &local_ctm, &area, stroke_uri, dict, stroke_tag);
fz_pop_clip(doc->dev);
}
xps_end_opacity(doc, opacity_mask_uri, dict, opacity_att, opacity_mask_tag);
if (stroke_path != path)
fz_free_path(doc->ctx, stroke_path);
fz_free_path(doc->ctx, path);
path = NULL;
fz_drop_stroke_state(doc->ctx, stroke);
if (clip_att || clip_tag)
fz_pop_clip(doc->dev);
}
Commit Message:
CWE ID: CWE-119
Target: 1
Example 2:
Code: v8::Handle<v8::Value> V8WebGLRenderingContext::uniform2fvCallback(const v8::Arguments& args)
{
INC_STATS("DOM.WebGLRenderingContext.uniform2fv()");
return vertexAttribAndUniformHelperf(args, kUniform2v);
}
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: 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 __always_inline void slab_unlock(struct page *page)
{
__bit_spin_unlock(PG_locked, &page->flags);
}
Commit Message: remove div_long_long_rem
x86 is the only arch right now, which provides an optimized for
div_long_long_rem and it has the downside that one has to be very careful that
the divide doesn't overflow.
The API is a little akward, as the arguments for the unsigned divide are
signed. The signed version also doesn't handle a negative divisor and
produces worse code on 64bit archs.
There is little incentive to keep this API alive, so this converts the few
users to the new API.
Signed-off-by: Roman Zippel <[email protected]>
Cc: Ralf Baechle <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Cc: john stultz <[email protected]>
Cc: Christoph Lameter <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-189
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 parser(void)
{
char *arg;
#ifndef MINIMAL
char *sitearg;
#endif
#ifdef WITH_RFC2640
char *narg = NULL;
#endif
size_t n;
#ifdef IMPLICIT_TLS
(void) tls_init_new_session();
data_protection_level = CPL_PRIVATE;
#endif
for (;;) {
xferfd = -1;
if (state_needs_update != 0) {
state_needs_update = 0;
setprocessname("pure-ftpd (IDLE)");
#ifdef FTPWHO
if (shm_data_cur != NULL) {
ftpwho_lock();
shm_data_cur->state = FTPWHO_STATE_IDLE;
*shm_data_cur->filename = 0;
ftpwho_unlock();
}
#endif
}
doreply();
alarm(idletime * 2);
switch (sfgets()) {
case -1:
#ifdef BORING_MODE
die(421, LOG_INFO, MSG_TIMEOUT);
#else
die(421, LOG_INFO, MSG_TIMEOUT_PARSER);
#endif
case -2:
return;
}
#ifdef DEBUG
if (debug != 0) {
addreply(0, "%s", cmd);
}
#endif
n = (size_t) 0U;
while ((isalpha((unsigned char) cmd[n]) || cmd[n] == '@') &&
n < cmdsize) {
cmd[n] = (char) tolower((unsigned char) cmd[n]);
n++;
}
if (n >= cmdsize) { /* overparanoid, it should never happen */
die(421, LOG_WARNING, MSG_LINE_TOO_LONG);
}
if (n == (size_t) 0U) {
nop:
addreply_noformat(500, "?");
continue;
}
#ifdef SKIP_COMMAND_TRAILING_SPACES
while (isspace((unsigned char) cmd[n]) && n < cmdsize) {
cmd[n++] = 0;
}
arg = cmd + n;
while (cmd[n] != 0 && n < cmdsize) {
n++;
}
n--;
while (isspace((unsigned char) cmd[n])) {
cmd[n--] = 0;
}
#else
if (cmd[n] == 0) {
arg = cmd + n;
} else if (isspace((unsigned char) cmd[n])) {
cmd[n] = 0;
arg = cmd + n + 1;
} else {
goto nop;
}
#endif
if (logging != 0) {
#ifdef DEBUG
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, arg);
#else
logfile(LOG_DEBUG, MSG_DEBUG_COMMAND " [%s] [%s]",
cmd, strcmp(cmd, "pass") ? arg : "<*>");
#endif
}
#ifdef WITH_RFC2640
narg = charset_client2fs(arg);
arg = narg;
#endif
/*
* antiidle() is called with dummy commands, usually used by clients
* who are wanting extra idle time. We give them some, but not too much.
* When we jump to wayout, the idle timer is not zeroed. It means that
* we didn't issue an 'active' command like RETR.
*/
#ifndef MINIMAL
if (!strcmp(cmd, "noop")) {
antiidle();
donoop();
goto wayout;
}
#endif
if (!strcmp(cmd, "user")) {
#ifdef WITH_TLS
if (enforce_tls_auth > 1 && tls_cnx == NULL) {
die(421, LOG_WARNING, MSG_TLS_NEEDED);
}
#endif
douser(arg);
} else if (!strcmp(cmd, "acct")) {
addreply(202, MSG_WHOAREYOU);
} else if (!strcmp(cmd, "pass")) {
if (guest == 0) {
randomdelay();
}
dopass(arg);
} else if (!strcmp(cmd, "quit")) {
addreply(221, MSG_GOODBYE,
(unsigned long long) ((uploaded + 1023ULL) / 1024ULL),
(unsigned long long) ((downloaded + 1023ULL) / 1024ULL));
return;
} else if (!strcmp(cmd, "syst")) {
antiidle();
addreply_noformat(215, "UNIX Type: L8");
goto wayout;
#ifdef WITH_TLS
} else if (enforce_tls_auth > 0 &&
!strcmp(cmd, "auth") && !strcasecmp(arg, "tls")) {
addreply_noformat(234, "AUTH TLS OK.");
doreply();
if (tls_cnx == NULL) {
(void) tls_init_new_session();
}
goto wayout;
} else if (!strcmp(cmd, "pbsz")) {
addreply_noformat(tls_cnx == NULL ? 503 : 200, "PBSZ=0");
} else if (!strcmp(cmd, "prot")) {
if (tls_cnx == NULL) {
addreply_noformat(503, MSG_PROT_BEFORE_PBSZ);
goto wayout;
}
switch (*arg) {
case 0:
addreply_noformat(503, MSG_MISSING_ARG);
data_protection_level = CPL_NONE;
break;
case 'C':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "clear");
data_protection_level = CPL_CLEAR;
break;
}
case 'S':
case 'E':
if (arg[1] == 0) {
addreply(200, MSG_PROT_UNKNOWN_LEVEL, arg, "private");
data_protection_level = CPL_PRIVATE;
break;
}
case 'P':
if (arg[1] == 0) {
addreply(200, MSG_PROT_OK, "private");
data_protection_level = CPL_PRIVATE;
break;
}
default:
addreply_noformat(534, "Fallback to [C]");
data_protection_level = CPL_CLEAR;
break;
}
#endif
} else if (!strcmp(cmd, "auth") || !strcmp(cmd, "adat")) {
addreply_noformat(500, MSG_AUTH_UNIMPLEMENTED);
} else if (!strcmp(cmd, "type")) {
antiidle();
dotype(arg);
goto wayout;
} else if (!strcmp(cmd, "mode")) {
antiidle();
domode(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "feat")) {
dofeat();
goto wayout;
} else if (!strcmp(cmd, "opts")) {
doopts(arg);
goto wayout;
#endif
} else if (!strcmp(cmd, "stru")) {
dostru(arg);
goto wayout;
#ifndef MINIMAL
} else if (!strcmp(cmd, "help")) {
goto help_site;
#endif
#ifdef DEBUG
} else if (!strcmp(cmd, "xdbg")) {
debug++;
addreply(200, MSG_XDBG_OK, debug);
goto wayout;
#endif
} else if (loggedin == 0) {
/* from this point, all commands need authentication */
addreply_noformat(530, MSG_NOT_LOGGED_IN);
goto wayout;
} else {
if (!strcmp(cmd, "cwd") || !strcmp(cmd, "xcwd")) {
antiidle();
docwd(arg);
goto wayout;
} else if (!strcmp(cmd, "port")) {
doport(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "eprt")) {
doeprt(arg);
} else if (!strcmp(cmd, "esta") &&
disallow_passive == 0 &&
STORAGE_FAMILY(force_passive_ip) == 0) {
doesta();
} else if (!strcmp(cmd, "estp")) {
doestp();
#endif
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "pasv") || !strcmp(cmd, "p@sw"))) {
dopasv(0);
} else if (disallow_passive == 0 &&
(!strcmp(cmd, "epsv") &&
(broken_client_compat == 0 ||
STORAGE_FAMILY(ctrlconn) == AF_INET6))) {
if (!strcasecmp(arg, "all")) {
epsv_all = 1;
addreply_noformat(220, MSG_ACTIVE_DISABLED);
} else if (!strcmp(arg, "2") && !v6ready) {
addreply_noformat(522, MSG_ONLY_IPV4);
} else {
dopasv(1);
}
#ifndef MINIMAL
} else if (disallow_passive == 0 && !strcmp(cmd, "spsv")) {
dopasv(2);
} else if (!strcmp(cmd, "allo")) {
if (*arg == 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
const off_t size = (off_t) strtoull(arg, NULL, 10);
if (size < (off_t) 0) {
addreply_noformat(501, MSG_STAT_FAILURE);
} else {
doallo(size);
}
}
#endif
} else if (!strcmp(cmd, "pwd") || !strcmp(cmd, "xpwd")) {
#ifdef WITH_RFC2640
char *nwd;
#endif
antiidle();
#ifdef WITH_RFC2640
nwd = charset_fs2client(wd);
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, nwd);
free(nwd);
#else
addreply(257, "\"%s\" " MSG_IS_YOUR_CURRENT_LOCATION, wd);
#endif
goto wayout;
} else if (!strcmp(cmd, "cdup") || !strcmp(cmd, "xcup")) {
docwd("..");
} else if (!strcmp(cmd, "retr")) {
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
}
else
#endif
{
doretr(arg);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rest")) {
antiidle();
if (*arg != 0) {
dorest(arg);
} else {
addreply_noformat(501, MSG_NO_RESTART_POINT);
restartat = (off_t) 0;
}
goto wayout;
} else if (!strcmp(cmd, "dele")) {
if (*arg != 0) {
dodele(arg);
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "stor")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 0, autorename);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "appe")) {
arg = revealextraspc(arg);
if (*arg != 0) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostor(arg, 1, 0);
}
} else {
addreply_noformat(501, MSG_NO_FILE_NAME);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "stou")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
dostou();
}
#endif
#ifndef DISABLE_MKD_RMD
} else if (!strcmp(cmd, "mkd") || !strcmp(cmd, "xmkd")) {
arg = revealextraspc(arg);
if (*arg != 0) {
domkd(arg);
} else {
addreply_noformat(501, MSG_NO_DIRECTORY_NAME);
}
} else if (!strcmp(cmd, "rmd") || !strcmp(cmd, "xrmd")) {
if (*arg != 0) {
dormd(arg);
} else {
addreply_noformat(550, MSG_NO_DIRECTORY_NAME);
}
#endif
#ifndef MINIMAL
} else if (!strcmp(cmd, "stat")) {
if (*arg != 0) {
modern_listings = 0;
donlist(arg, 1, 1, 1, 1);
} else {
addreply_noformat(211, "http://www.pureftpd.org/");
}
#endif
} else if (!strcmp(cmd, "list")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 0, 1);
}
} else if (!strcmp(cmd, "nlst")) {
#ifndef MINIMAL
modern_listings = 0;
#endif
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 0, 0, broken_client_compat);
}
#ifndef MINIMAL
} else if (!strcmp(cmd, "mlst")) {
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
domlst(*arg != 0 ? arg : ".");
}
} else if (!strcmp(cmd, "mlsd")) {
modern_listings = 1;
#ifdef WITH_TLS
if (enforce_tls_auth == 3 &&
data_protection_level != CPL_PRIVATE) {
addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED);
} else
#endif
{
donlist(arg, 0, 1, 1, 0);
}
#endif
} else if (!strcmp(cmd, "abor")) {
addreply_noformat(226, MSG_ABOR_SUCCESS);
#ifndef MINIMAL
} else if (!strcmp(cmd, "site")) {
if ((sitearg = arg) != NULL) {
while (*sitearg != 0 && !isspace((unsigned char) *sitearg)) {
sitearg++;
}
if (*sitearg != 0) {
*sitearg++ = 0;
}
}
if (!strcasecmp(arg, "idle")) {
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, "SITE IDLE: " MSG_MISSING_ARG);
} else {
unsigned long int i = 0;
i = strtoul(sitearg, &sitearg, 10);
if (sitearg && *sitearg)
addreply(501, MSG_GARBAGE_FOUND " : %s", sitearg);
else if (i > MAX_SITE_IDLE)
addreply_noformat(501, MSG_VALUE_TOO_LARGE);
else {
idletime = i;
addreply(200, MSG_IDLE_TIME, idletime);
idletime_noop = (double) idletime * 2.0;
}
}
} else if (!strcasecmp(arg, "time")) {
dositetime();
} else if (!strcasecmp(arg, "help")) {
help_site:
addreply_noformat(214, MSG_SITE_HELP CRLF
# ifdef WITH_DIRALIASES
" ALIAS" CRLF
# endif
" CHMOD" CRLF " IDLE" CRLF " UTIME");
addreply_noformat(214, "Pure-FTPd - http://pureftpd.org/");
} else if (!strcasecmp(arg, "chmod")) {
char *sitearg2;
mode_t mode;
parsechmod:
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_MISSING_ARG);
goto chmod_wayout;
}
sitearg2 = sitearg;
while (*sitearg2 != 0 && !isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
while (*sitearg2 != 0 && isspace((unsigned char) *sitearg2)) {
sitearg2++;
}
if (*sitearg2 == 0) {
addreply_noformat(550, MSG_NO_FILE_NAME);
goto chmod_wayout;
}
mode = (mode_t) strtoul(sitearg, NULL, 8);
if (mode > (mode_t) 07777) {
addreply_noformat(501, MSG_BAD_CHMOD);
goto chmod_wayout;
}
dochmod(sitearg2, mode);
chmod_wayout:
(void) 0;
} else if (!strcasecmp(arg, "utime")) {
char *sitearg2;
if (sitearg == NULL || *sitearg == 0) {
addreply_noformat(501, MSG_NO_FILE_NAME);
goto utime_wayout;
}
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
if (strcasecmp(sitearg2, " UTC") != 0) {
addreply_noformat(500, "UTC Only");
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
utime_no_arg:
addreply_noformat(501, MSG_MISSING_ARG);
goto utime_wayout;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2-- = 0;
if ((sitearg2 = strrchr(sitearg, ' ')) == NULL ||
sitearg2 == sitearg) {
goto utime_no_arg;
}
*sitearg2++ = 0;
if (*sitearg2 == 0) {
goto utime_no_arg;
}
doutime(sitearg, sitearg2);
utime_wayout:
(void) 0;
# ifdef WITH_DIRALIASES
} else if (!strcasecmp(arg, "alias")) {
if (sitearg == NULL || *sitearg == 0) {
print_aliases();
} else {
const char *alias;
if ((alias = lookup_alias(sitearg)) != NULL) {
addreply(214, MSG_ALIASES_ALIAS, sitearg, alias);
} else {
addreply(502, MSG_ALIASES_UNKNOWN, sitearg);
}
}
# endif
} else if (*arg != 0) {
addreply(500, "SITE %s " MSG_UNKNOWN_EXTENSION, arg);
} else {
addreply_noformat(500, "SITE: " MSG_MISSING_ARG);
}
#endif
} else if (!strcmp(cmd, "mdtm")) {
domdtm(arg);
} else if (!strcmp(cmd, "size")) {
dosize(arg);
#ifndef MINIMAL
} else if (!strcmp(cmd, "chmod")) {
sitearg = arg;
goto parsechmod;
#endif
} else if (!strcmp(cmd, "rnfr")) {
if (*arg != 0) {
dornfr(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else if (!strcmp(cmd, "rnto")) {
arg = revealextraspc(arg);
if (*arg != 0) {
dornto(arg);
} else {
addreply_noformat(550, MSG_NO_FILE_NAME);
}
} else {
addreply_noformat(500, MSG_UNKNOWN_COMMAND);
}
}
noopidle = (time_t) -1;
wayout:
#ifdef WITH_RFC2640
free(narg);
narg = NULL;
#endif
#ifdef THROTTLING
if (throttling_delay != 0UL) {
usleep2(throttling_delay);
}
#else
(void) 0;
#endif
}
}
Commit Message: Flush the command buffer after switching to TLS.
Fixes a flaw similar to CVE-2011-0411.
CWE ID: CWE-399
Target: 1
Example 2:
Code: void WebMediaPlayerImpl::SetTickClockForTest(
const base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
buffered_data_source_host_.SetTickClockForTest(tick_clock);
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732
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_t xdr_krb5_tl_data(XDR *xdrs, krb5_tl_data **tl_data_head)
{
krb5_tl_data *tl, *tl2;
bool_t more;
unsigned int len;
switch (xdrs->x_op) {
case XDR_FREE:
tl = tl2 = *tl_data_head;
while (tl) {
tl2 = tl->tl_data_next;
free(tl->tl_data_contents);
free(tl);
tl = tl2;
}
break;
case XDR_ENCODE:
tl = *tl_data_head;
while (1) {
more = (tl != NULL);
if (!xdr_bool(xdrs, &more))
return FALSE;
if (tl == NULL)
break;
if (!xdr_krb5_int16(xdrs, &tl->tl_data_type))
return FALSE;
len = tl->tl_data_length;
if (!xdr_bytes(xdrs, (char **) &tl->tl_data_contents, &len, ~0))
return FALSE;
tl = tl->tl_data_next;
}
break;
case XDR_DECODE:
tl = NULL;
while (1) {
if (!xdr_bool(xdrs, &more))
return FALSE;
if (more == FALSE)
break;
tl2 = (krb5_tl_data *) malloc(sizeof(krb5_tl_data));
if (tl2 == NULL)
return FALSE;
memset(tl2, 0, sizeof(krb5_tl_data));
if (!xdr_krb5_int16(xdrs, &tl2->tl_data_type))
return FALSE;
if (!xdr_bytes(xdrs, (char **)&tl2->tl_data_contents, &len, ~0))
return FALSE;
tl2->tl_data_length = len;
tl2->tl_data_next = tl;
tl = tl2;
}
*tl_data_head = tl;
break;
}
return TRUE;
}
Commit Message: Fix kadm5/gssrpc XDR double free [CVE-2014-9421]
[MITKRB5-SA-2015-001] In auth_gssapi_unwrap_data(), do not free
partial deserialization results upon failure to deserialize. This
responsibility belongs to the callers, svctcp_getargs() and
svcudp_getargs(); doing it in the unwrap function results in freeing
the results twice.
In xdr_krb5_tl_data() and xdr_krb5_principal(), null out the pointers
we are freeing, as other XDR functions such as xdr_bytes() and
xdr_string().
ticket: 8056 (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 int netlink_dump(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_callback *cb;
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
int len, err = -ENOBUFS;
int alloc_min_size;
int alloc_size;
mutex_lock(nlk->cb_mutex);
if (!nlk->cb_running) {
err = -EINVAL;
goto errout_skb;
}
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto errout_skb;
/* NLMSG_GOODSIZE is small to avoid high order allocations being
* required, but it makes sense to _attempt_ a 16K bytes allocation
* to reduce number of system calls on dump operations, if user
* ever provided a big enough buffer.
*/
cb = &nlk->cb;
alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
if (alloc_min_size < nlk->max_recvmsg_len) {
alloc_size = nlk->max_recvmsg_len;
skb = alloc_skb(alloc_size, GFP_KERNEL |
__GFP_NOWARN | __GFP_NORETRY);
}
if (!skb) {
alloc_size = alloc_min_size;
skb = alloc_skb(alloc_size, GFP_KERNEL);
}
if (!skb)
goto errout_skb;
/* Trim skb to allocated size. User is expected to provide buffer as
* large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at
* netlink_recvmsg())). dump will pack as many smaller messages as
* could fit within the allocated skb. skb is typically allocated
* with larger space than required (could be as much as near 2x the
* requested size with align to next power of 2 approach). Allowing
* dump to use the excess space makes it difficult for a user to have a
* reasonable static buffer based on the expected largest dump of a
* single netdev. The outcome is MSG_TRUNC error.
*/
skb_reserve(skb, skb_tailroom(skb) - alloc_size);
netlink_skb_set_owner_r(skb, sk);
len = cb->dump(skb, cb);
if (len > 0) {
mutex_unlock(nlk->cb_mutex);
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
return 0;
}
nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
if (!nlh)
goto errout_skb;
nl_dump_check_consistent(cb, nlh);
memcpy(nlmsg_data(nlh), &len, sizeof(len));
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
if (cb->done)
cb->done(cb);
nlk->cb_running = false;
mutex_unlock(nlk->cb_mutex);
module_put(cb->module);
consume_skb(cb->skb);
return 0;
errout_skb:
mutex_unlock(nlk->cb_mutex);
kfree_skb(skb);
return err;
}
Commit Message: netlink: Fix dump skb leak/double free
When we free cb->skb after a dump, we do it after releasing the
lock. This means that a new dump could have started in the time
being and we'll end up freeing their skb instead of ours.
This patch saves the skb and module before we unlock so we free
the right memory.
Fixes: 16b304f3404f ("netlink: Eliminate kmalloc in netlink dump operation.")
Reported-by: Baozeng Ding <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
Acked-by: Cong Wang <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-415
Target: 1
Example 2:
Code: void RenderProcessHostImpl::OnDumpHandlesDone() {
Cleanup();
}
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: 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 inline u8 btrfs_inode_type(struct inode *inode)
{
return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
}
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 void sig_server_connect_copy(SERVER_CONNECT_REC **dest,
IRC_SERVER_CONNECT_REC *src)
{
IRC_SERVER_CONNECT_REC *rec;
g_return_if_fail(dest != NULL);
if (!IS_IRC_SERVER_CONNECT(src))
return;
rec = g_new0(IRC_SERVER_CONNECT_REC, 1);
rec->chat_type = IRC_PROTOCOL;
rec->max_cmds_at_once = src->max_cmds_at_once;
rec->cmd_queue_speed = src->cmd_queue_speed;
rec->max_query_chans = src->max_query_chans;
rec->max_kicks = src->max_kicks;
rec->max_modes = src->max_modes;
rec->max_msgs = src->max_msgs;
rec->max_whois = src->max_whois;
rec->usermode = g_strdup(src->usermode);
rec->alternate_nick = g_strdup(src->alternate_nick);
rec->sasl_mechanism = src->sasl_mechanism;
rec->sasl_username = src->sasl_username;
rec->sasl_password = src->sasl_password;
*dest = (SERVER_CONNECT_REC *) rec;
}
Commit Message: Merge pull request #1058 from ailin-nemui/sasl-reconnect
copy sasl username and password values
CWE ID: CWE-416
Target: 1
Example 2:
Code: ofpacts_verify(const struct ofpact ofpacts[], size_t ofpacts_len,
uint32_t allowed_ovsinsts, enum ofpact_type outer_action)
{
const struct ofpact *a;
enum ovs_instruction_type inst;
inst = OVSINST_OFPIT13_METER;
OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
enum ovs_instruction_type next;
enum ofperr error;
if (a->type == OFPACT_CONJUNCTION) {
OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
if (a->type != OFPACT_CONJUNCTION && a->type != OFPACT_NOTE) {
VLOG_WARN("\"conjunction\" actions may be used along with "
"\"note\" but not any other kind of action "
"(such as the \"%s\" action used here)",
ofpact_name(a->type));
return OFPERR_NXBAC_BAD_CONJUNCTION;
}
}
return 0;
}
error = ofpacts_verify_nested(a, outer_action);
if (error) {
return error;
}
next = ovs_instruction_type_from_ofpact_type(a->type);
if (a > ofpacts
&& (inst == OVSINST_OFPIT11_APPLY_ACTIONS
? next < inst
: next <= inst)) {
const char *name = ovs_instruction_name_from_type(inst);
const char *next_name = ovs_instruction_name_from_type(next);
if (next == inst) {
VLOG_WARN("duplicate %s instruction not allowed, for OpenFlow "
"1.1+ compatibility", name);
} else {
VLOG_WARN("invalid instruction ordering: %s must appear "
"before %s, for OpenFlow 1.1+ compatibility",
next_name, name);
}
return OFPERR_OFPBAC_UNSUPPORTED_ORDER;
}
if (!((1u << next) & allowed_ovsinsts)) {
const char *name = ovs_instruction_name_from_type(next);
VLOG_WARN("%s instruction not allowed here", name);
return OFPERR_OFPBIC_UNSUP_INST;
}
inst = next;
}
return 0;
}
Commit Message: ofp-actions: Avoid buffer overread in BUNDLE action decoding.
Reported-at: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=9052
Signed-off-by: Ben Pfaff <[email protected]>
Acked-by: Justin Pettit <[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: bool Document::execCommand(const String& commandName, bool, const String& value, ExceptionState& exceptionState)
{
if (!isHTMLDocument() && !isXHTMLDocument()) {
exceptionState.throwDOMException(InvalidStateError, "execCommand is only supported on HTML documents.");
return false;
}
if (focusedElement() && isHTMLTextFormControlElement(*focusedElement()))
UseCounter::count(*this, UseCounter::ExecCommandOnInputOrTextarea);
if (m_isRunningExecCommand) {
String message = "We don't execute document.execCommand() this time, because it is called recursively.";
addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, message));
return false;
}
TemporaryChange<bool> executeScope(m_isRunningExecCommand, true);
EventQueueScope eventQueueScope;
Editor::tidyUpHTMLStructure(*this);
Editor::Command editorCommand = command(this, commandName);
DEFINE_STATIC_LOCAL(SparseHistogram, editorCommandHistogram, ("WebCore.Document.execCommand"));
editorCommandHistogram.sample(editorCommand.idForHistogram());
return editorCommand.execute(value);
}
Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone.
BUG=556724,577105
Review URL: https://codereview.chromium.org/1667573002
Cr-Commit-Position: refs/heads/master@{#373642}
CWE ID: CWE-264
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(imagecrop)
{
zval *IM;
gdImagePtr im;
gdImagePtr im_crop;
gdRect rect;
zval *z_rect;
zval **tmp;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra", &IM, &z_rect) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.x = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) {
rect.y = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) {
rect.width = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width");
RETURN_FALSE;
}
if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) {
rect.height = Z_LVAL_PP(tmp);
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height");
RETURN_FALSE;
}
im_crop = gdImageCrop(im, &rect);
if (im_crop == NULL) {
RETURN_FALSE;
} else {
ZEND_REGISTER_RESOURCE(return_value, im_crop, le_gd);
}
}
Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop())
And also fixed the bug: arguments are altered after some calls
CWE ID: CWE-189
Target: 1
Example 2:
Code: const SSL_CIPHER *ssl3_get_cipher(unsigned int u)
{
if (u < SSL3_NUM_CIPHERS)
return(&(ssl3_ciphers[SSL3_NUM_CIPHERS-1-u]));
else
return(NULL);
}
Commit Message:
CWE ID: CWE-310
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 nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
{
const struct nft_set *set;
struct nft_set_dump_args args;
struct nft_ctx ctx;
struct nlattr *nla[NFTA_SET_ELEM_LIST_MAX + 1];
struct nfgenmsg *nfmsg;
struct nlmsghdr *nlh;
struct nlattr *nest;
u32 portid, seq;
int event, err;
err = nlmsg_parse(cb->nlh, sizeof(struct nfgenmsg), nla,
NFTA_SET_ELEM_LIST_MAX, nft_set_elem_list_policy);
if (err < 0)
return err;
err = nft_ctx_init_from_elemattr(&ctx, cb->skb, cb->nlh, (void *)nla,
false);
if (err < 0)
return err;
set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
if (IS_ERR(set))
return PTR_ERR(set);
if (set->flags & NFT_SET_INACTIVE)
return -ENOENT;
event = NFT_MSG_NEWSETELEM;
event |= NFNL_SUBSYS_NFTABLES << 8;
portid = NETLINK_CB(cb->skb).portid;
seq = cb->nlh->nlmsg_seq;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
NLM_F_MULTI);
if (nlh == NULL)
goto nla_put_failure;
nfmsg = nlmsg_data(nlh);
nfmsg->nfgen_family = ctx.afi->family;
nfmsg->version = NFNETLINK_V0;
nfmsg->res_id = htons(ctx.net->nft.base_seq & 0xffff);
if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, ctx.table->name))
goto nla_put_failure;
if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
goto nla_put_failure;
nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
if (nest == NULL)
goto nla_put_failure;
args.cb = cb;
args.skb = skb;
args.iter.skip = cb->args[0];
args.iter.count = 0;
args.iter.err = 0;
args.iter.fn = nf_tables_dump_setelem;
set->ops->walk(&ctx, set, &args.iter);
nla_nest_end(skb, nest);
nlmsg_end(skb, nlh);
if (args.iter.err && args.iter.err != -EMSGSIZE)
return args.iter.err;
if (args.iter.count == cb->args[0])
return 0;
cb->args[0] = args.iter.count;
return skb->len;
nla_put_failure:
return -ENOSPC;
}
Commit Message: netfilter: nf_tables: fix flush ruleset chain dependencies
Jumping between chains doesn't mix well with flush ruleset. Rules
from a different chain and set elements may still refer to us.
[ 353.373791] ------------[ cut here ]------------
[ 353.373845] kernel BUG at net/netfilter/nf_tables_api.c:1159!
[ 353.373896] invalid opcode: 0000 [#1] SMP
[ 353.373942] Modules linked in: intel_powerclamp uas iwldvm iwlwifi
[ 353.374017] CPU: 0 PID: 6445 Comm: 31c3.nft Not tainted 3.18.0 #98
[ 353.374069] Hardware name: LENOVO 5129CTO/5129CTO, BIOS 6QET47WW (1.17 ) 07/14/2010
[...]
[ 353.375018] Call Trace:
[ 353.375046] [<ffffffff81964c31>] ? nf_tables_commit+0x381/0x540
[ 353.375101] [<ffffffff81949118>] nfnetlink_rcv+0x3d8/0x4b0
[ 353.375150] [<ffffffff81943fc5>] netlink_unicast+0x105/0x1a0
[ 353.375200] [<ffffffff8194438e>] netlink_sendmsg+0x32e/0x790
[ 353.375253] [<ffffffff818f398e>] sock_sendmsg+0x8e/0xc0
[ 353.375300] [<ffffffff818f36b9>] ? move_addr_to_kernel.part.20+0x19/0x70
[ 353.375357] [<ffffffff818f44f9>] ? move_addr_to_kernel+0x19/0x30
[ 353.375410] [<ffffffff819016d2>] ? verify_iovec+0x42/0xd0
[ 353.375459] [<ffffffff818f3e10>] ___sys_sendmsg+0x3f0/0x400
[ 353.375510] [<ffffffff810615fa>] ? native_sched_clock+0x2a/0x90
[ 353.375563] [<ffffffff81176697>] ? acct_account_cputime+0x17/0x20
[ 353.375616] [<ffffffff8110dc78>] ? account_user_time+0x88/0xa0
[ 353.375667] [<ffffffff818f4bbd>] __sys_sendmsg+0x3d/0x80
[ 353.375719] [<ffffffff81b184f4>] ? int_check_syscall_exit_work+0x34/0x3d
[ 353.375776] [<ffffffff818f4c0d>] SyS_sendmsg+0xd/0x20
[ 353.375823] [<ffffffff81b1826d>] system_call_fastpath+0x16/0x1b
Release objects in this order: rules -> sets -> chains -> tables, to
make sure no references to chains are held anymore.
Reported-by: Asbjoern Sloth Toennesen <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-19
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 LoadingStatsCollector::RecordPreconnectStats(
std::unique_ptr<PreconnectStats> stats) {
const GURL& main_frame_url = stats->url;
auto it = preconnect_stats_.find(main_frame_url);
if (it != preconnect_stats_.end()) {
ReportPreconnectAccuracy(*it->second,
std::map<GURL, OriginRequestSummary>());
preconnect_stats_.erase(it);
}
preconnect_stats_.emplace(main_frame_url, std::move(stats));
}
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: 1
Example 2:
Code: ShowModalDialogTest() {}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 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 g2m_init_buffers(G2MContext *c)
{
int aligned_height;
if (!c->framebuf || c->old_width < c->width || c->old_height < c->height) {
c->framebuf_stride = FFALIGN(c->width * 3, 16);
aligned_height = FFALIGN(c->height, 16);
av_free(c->framebuf);
c->framebuf = av_mallocz(c->framebuf_stride * aligned_height);
if (!c->framebuf)
return AVERROR(ENOMEM);
}
if (!c->synth_tile || !c->jpeg_tile ||
c->old_tile_w < c->tile_width ||
c->old_tile_h < c->tile_height) {
c->tile_stride = FFALIGN(c->tile_width * 3, 16);
aligned_height = FFALIGN(c->tile_height, 16);
av_free(c->synth_tile);
av_free(c->jpeg_tile);
av_free(c->kempf_buf);
av_free(c->kempf_flags);
c->synth_tile = av_mallocz(c->tile_stride * aligned_height);
c->jpeg_tile = av_mallocz(c->tile_stride * aligned_height);
c->kempf_buf = av_mallocz((c->tile_width + 1) * aligned_height
+ FF_INPUT_BUFFER_PADDING_SIZE);
c->kempf_flags = av_mallocz( c->tile_width * aligned_height);
if (!c->synth_tile || !c->jpeg_tile ||
!c->kempf_buf || !c->kempf_flags)
return AVERROR(ENOMEM);
}
return 0;
}
Commit Message: avcodec/g2meet: Fix order of align and pixel size multiplication.
Fixes out of array accesses
Fixes Ticket2922
Found-by: ami_stuff
Signed-off-by: Michael Niedermayer <[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: 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 (!asoc->temp) {
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: sctp: Fix sk_ack_backlog wrap-around problem
Consider the scenario:
For a TCP-style socket, while processing the COOKIE_ECHO chunk in
sctp_sf_do_5_1D_ce(), after it has passed a series of sanity check,
a new association would be created in sctp_unpack_cookie(), but afterwards,
some processing maybe failed, and sctp_association_free() will be called to
free the previously allocated association, in sctp_association_free(),
sk_ack_backlog value is decremented for this socket, since the initial
value for sk_ack_backlog is 0, after the decrement, it will be 65535,
a wrap-around problem happens, and if we want to establish new associations
afterward in the same socket, ABORT would be triggered since sctp deem the
accept queue as full.
Fix this issue by only decrementing sk_ack_backlog for associations in
the endpoint's list.
Fix-suggested-by: Neil Horman <[email protected]>
Signed-off-by: Xufeng Zhang <[email protected]>
Acked-by: Daniel Borkmann <[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: vips_foreign_is_a_buffer( const char *loader, const void *data, size_t size )
{
const VipsObjectClass *class;
VipsForeignLoadClass *load_class;
if( !(class = vips_class_find( "VipsForeignLoad", loader )) )
return( FALSE );
load_class = VIPS_FOREIGN_LOAD_CLASS( class );
if( load_class->is_a_buffer &&
load_class->is_a_buffer( data, size ) )
return( TRUE );
return( FALSE );
}
Commit Message: fix a crash with delayed load
If a delayed load failed, it could leave the pipeline only half-set up.
Sebsequent threads could then segv.
Set a load-has-failed flag and test before generate.
See https://github.com/jcupitt/libvips/issues/893
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 AppCacheHost::DoPendingGetStatus() {
DCHECK_EQ(false, pending_get_status_callback_.is_null());
pending_get_status_callback_.Run(GetStatus(), pending_callback_param_);
pending_get_status_callback_.Reset();
pending_callback_param_ = NULL;
}
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:
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: Session* SessionManager::GetSession(const std::string& id) const {
std::map<std::string, Session*>::const_iterator it;
base::AutoLock lock(map_lock_);
it = map_.find(id);
if (it == map_.end()) {
VLOG(1) << "No such session with ID " << id;
return NULL;
}
return it->second;
}
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: bool GLES2DecoderImpl::ValidateCopyTextureCHROMIUMTextures(
const char* function_name,
GLenum dest_target,
TextureRef* source_texture_ref,
TextureRef* dest_texture_ref) {
if (!source_texture_ref || !dest_texture_ref) {
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name, "unknown texture id");
return false;
}
Texture* source_texture = source_texture_ref->texture();
Texture* dest_texture = dest_texture_ref->texture();
if (source_texture == dest_texture) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, function_name,
"source and destination textures are the same");
return false;
}
if (dest_texture->target() !=
GLES2Util::GLFaceTargetToTextureTarget(dest_target)) {
LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, function_name,
"target should be aligned with dest target");
return false;
}
switch (dest_texture->target()) {
case GL_TEXTURE_2D:
case GL_TEXTURE_CUBE_MAP:
case GL_TEXTURE_RECTANGLE_ARB:
break;
default:
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name,
"invalid dest texture target binding");
return false;
}
switch (source_texture->target()) {
case GL_TEXTURE_2D:
case GL_TEXTURE_RECTANGLE_ARB:
case GL_TEXTURE_EXTERNAL_OES:
break;
default:
LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, function_name,
"invalid source texture target binding");
return false;
}
return true;
}
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: input_userauth_success(int type, u_int32_t seq, void *ctxt)
{
Authctxt *authctxt = ctxt;
if (authctxt == NULL)
fatal("input_userauth_success: no authentication context");
free(authctxt->authlist);
authctxt->authlist = NULL;
if (authctxt->method != NULL && authctxt->method->cleanup != NULL)
authctxt->method->cleanup(authctxt);
free(authctxt->methoddata);
authctxt->methoddata = NULL;
authctxt->success = 1; /* break out */
return 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
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: vhost_scsi_send_evt(struct vhost_scsi *vs,
struct vhost_scsi_tpg *tpg,
struct se_lun *lun,
u32 event,
u32 reason)
{
struct vhost_scsi_evt *evt;
evt = vhost_scsi_allocate_evt(vs, event, reason);
if (!evt)
return;
if (tpg && lun) {
/* TODO: share lun setup code with virtio-scsi.ko */
/*
* Note: evt->event is zeroed when we allocate it and
* lun[4-7] need to be zero according to virtio-scsi spec.
*/
evt->event.lun[0] = 0x01;
evt->event.lun[1] = tpg->tport_tpgt & 0xFF;
if (lun->unpacked_lun >= 256)
evt->event.lun[2] = lun->unpacked_lun >> 8 | 0x40 ;
evt->event.lun[3] = lun->unpacked_lun & 0xFF;
}
llist_add(&evt->list, &vs->vs_event_list);
vhost_work_queue(&vs->dev, &vs->vs_event_work);
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas Bellinger <[email protected]>
CWE ID: CWE-119
Target: 1
Example 2:
Code: static int ati_remote2_setup(struct ati_remote2 *ar2, unsigned int ch_mask)
{
int r, i, channel;
/*
* Configure receiver to only accept input from remote "channel"
* channel == 0 -> Accept input from any remote channel
* channel == 1 -> Only accept input from remote channel 1
* channel == 2 -> Only accept input from remote channel 2
* ...
* channel == 16 -> Only accept input from remote channel 16
*/
channel = 0;
for (i = 0; i < 16; i++) {
if ((1 << i) & ch_mask) {
if (!(~(1 << i) & ch_mask))
channel = i + 1;
break;
}
}
r = usb_control_msg(ar2->udev, usb_sndctrlpipe(ar2->udev, 0),
0x20,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
channel, 0x0, NULL, 0, USB_CTRL_SET_TIMEOUT);
if (r) {
dev_err(&ar2->udev->dev, "%s - failed to set channel due to error: %d\n",
__func__, r);
return r;
}
return 0;
}
Commit Message: Input: ati_remote2 - fix crashes on detecting device with invalid descriptor
The ati_remote2 driver expects at least two interfaces with one
endpoint each. If given malicious descriptor that specify one
interface or no endpoints, it will crash in the probe function.
Ensure there is at least two interfaces and one endpoint for each
interface before using it.
The full disclosure: http://seclists.org/bugtraq/2016/Mar/90
Reported-by: Ralf Spenneberg <[email protected]>
Signed-off-by: Vladis Dronov <[email protected]>
Cc: [email protected]
Signed-off-by: Dmitry Torokhov <[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: vhost_scsi_make_tpg(struct se_wwn *wwn,
struct config_group *group,
const char *name)
{
struct vhost_scsi_tport *tport = container_of(wwn,
struct vhost_scsi_tport, tport_wwn);
struct vhost_scsi_tpg *tpg;
unsigned long tpgt;
int ret;
if (strstr(name, "tpgt_") != name)
return ERR_PTR(-EINVAL);
if (kstrtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)
return ERR_PTR(-EINVAL);
tpg = kzalloc(sizeof(struct vhost_scsi_tpg), GFP_KERNEL);
if (!tpg) {
pr_err("Unable to allocate struct vhost_scsi_tpg");
return ERR_PTR(-ENOMEM);
}
mutex_init(&tpg->tv_tpg_mutex);
INIT_LIST_HEAD(&tpg->tv_tpg_list);
tpg->tport = tport;
tpg->tport_tpgt = tpgt;
ret = core_tpg_register(&vhost_scsi_fabric_configfs->tf_ops, wwn,
&tpg->se_tpg, tpg, TRANSPORT_TPG_TYPE_NORMAL);
if (ret < 0) {
kfree(tpg);
return NULL;
}
mutex_lock(&vhost_scsi_mutex);
list_add_tail(&tpg->tv_tpg_list, &vhost_scsi_list);
mutex_unlock(&vhost_scsi_mutex);
return &tpg->se_tpg;
}
Commit Message: vhost/scsi: potential memory corruption
This code in vhost_scsi_make_tpg() is confusing because we limit "tpgt"
to UINT_MAX but the data type of "tpg->tport_tpgt" and that is a u16.
I looked at the context and it turns out that in
vhost_scsi_set_endpoint(), "tpg->tport_tpgt" is used as an offset into
the vs_tpg[] array which has VHOST_SCSI_MAX_TARGET (256) elements so
anything higher than 255 then it is invalid. I have made that the limit
now.
In vhost_scsi_send_evt() we mask away values higher than 255, but now
that the limit has changed, we don't need the mask.
Signed-off-by: Dan Carpenter <[email protected]>
Signed-off-by: Nicholas 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: void svc_rdma_put_req_map(struct svcxprt_rdma *xprt,
struct svc_rdma_req_map *map)
{
spin_lock(&xprt->sc_map_lock);
list_add(&map->free, &xprt->sc_maps);
spin_unlock(&xprt->sc_map_lock);
}
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: static void dns_reset_resolution(struct dns_resolution *resolution)
{
/* update resolution status */
resolution->step = RSLV_STEP_NONE;
resolution->try = 0;
resolution->last_resolution = now_ms;
resolution->nb_queries = 0;
resolution->nb_responses = 0;
resolution->query_type = resolution->prefered_query_type;
/* clean up query id */
eb32_delete(&resolution->qid);
resolution->query_id = 0;
resolution->qid.key = 0;
}
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: dissect_rpcap_filter (tvbuff_t *tvb, packet_info *pinfo,
proto_tree *parent_tree, gint offset)
{
proto_tree *tree;
proto_item *ti;
guint32 nitems, i;
ti = proto_tree_add_item (parent_tree, hf_filter, tvb, offset, -1, ENC_NA);
tree = proto_item_add_subtree (ti, ett_filter);
proto_tree_add_item (tree, hf_filtertype, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item (tree, hf_dummy, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
nitems = tvb_get_ntohl (tvb, offset);
proto_tree_add_item (tree, hf_nitems, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
for (i = 0; i < nitems; i++) {
offset = dissect_rpcap_filterbpf_insn (tvb, pinfo, tree, offset);
if (tvb_reported_length_remaining (tvb, offset) < 0) {
/* No more data in packet */
expert_add_info(pinfo, ti, &ei_no_more_data);
break;
}
}
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <[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: void Verify_MakeGroupObsolete() {
EXPECT_TRUE(delegate()->obsoleted_success_);
EXPECT_EQ(group_.get(), delegate()->obsoleted_group_.get());
EXPECT_TRUE(group_->is_obsolete());
EXPECT_TRUE(storage()->usage_map_.empty());
AppCacheDatabase::GroupRecord group_record;
AppCacheDatabase::CacheRecord cache_record;
EXPECT_FALSE(database()->FindGroup(1, &group_record));
EXPECT_FALSE(database()->FindCache(1, &cache_record));
std::vector<AppCacheDatabase::EntryRecord> entry_records;
database()->FindEntriesForCache(1, &entry_records);
EXPECT_TRUE(entry_records.empty());
std::vector<AppCacheDatabase::NamespaceRecord> intercept_records;
std::vector<AppCacheDatabase::NamespaceRecord> fallback_records;
database()->FindNamespacesForCache(1, &intercept_records,
&fallback_records);
EXPECT_TRUE(fallback_records.empty());
std::vector<AppCacheDatabase::OnlineWhiteListRecord> whitelist_records;
database()->FindOnlineWhiteListForCache(1, &whitelist_records);
EXPECT_TRUE(whitelist_records.empty());
EXPECT_TRUE(storage()->usage_map_.empty());
EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_);
EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_);
EXPECT_EQ(-kDefaultEntrySize, mock_quota_manager_proxy_->last_delta_);
TestFinished();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200
Target: 1
Example 2:
Code: void HTMLMediaElement::InvokeResourceSelectionAlgorithm() {
BLINK_MEDIA_LOG << "invokeResourceSelectionAlgorithm(" << (void*)this << ")";
SetNetworkState(kNetworkNoSource);
played_time_ranges_ = TimeRanges::Create();
last_seek_time_ = 0;
duration_ = std::numeric_limits<double>::quiet_NaN();
SetShouldDelayLoadEvent(true);
if (GetMediaControls())
GetMediaControls()->Reset();
ScheduleNextSourceChild();
}
Commit Message: defeat cors attacks on audio/video tags
Neutralize error messages and fire no progress events
until media metadata has been loaded for media loaded
from cross-origin locations.
Bug: 828265, 826187
Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6
Reviewed-on: https://chromium-review.googlesource.com/1015794
Reviewed-by: Mounir Lamouri <[email protected]>
Reviewed-by: Dale Curtis <[email protected]>
Commit-Queue: Fredrik Hubinette <[email protected]>
Cr-Commit-Position: refs/heads/master@{#557312}
CWE ID: CWE-200
Target: 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: INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
Commit Message: Fix #9943 - Invalid free on RAnal.avr
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: long Cluster::CreateSimpleBlock(
long long st,
long long sz)
{
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count >= 0);
assert(m_entries_count < m_entries_size);
const long idx = m_entries_count;
BlockEntry** const ppEntry = m_entries + idx;
BlockEntry*& pEntry = *ppEntry;
pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz);
if (pEntry == NULL)
return -1; //generic error
SimpleBlock* const p = static_cast<SimpleBlock*>(pEntry);
const long status = p->Parse();
if (status == 0)
{
++m_entries_count;
return 0;
}
delete pEntry;
pEntry = 0;
return status;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119
Target: 1
Example 2:
Code: static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
{
ssh_pkt_adddata(pkt, &value, 1);
}
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 inline void ipgre_ecn_decapsulate(struct iphdr *iph, struct sk_buff *skb)
{
if (INET_ECN_is_ce(iph->tos)) {
if (skb->protocol == htons(ETH_P_IP)) {
IP_ECN_set_ce(ip_hdr(skb));
} else if (skb->protocol == htons(ETH_P_IPV6)) {
IP6_ECN_set_ce(ipv6_hdr(skb));
}
}
}
Commit Message: gre: fix netns vs proto registration ordering
GRE protocol receive hook can be called right after protocol addition is done.
If netns stuff is not yet initialized, we're going to oops in
net_generic().
This is remotely oopsable if ip_gre is compiled as module and packet
comes at unfortunate moment of module loading.
Signed-off-by: Alexey Dobriyan <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID:
Output: | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.