prompt
stringlengths
1.19k
236k
output
int64
0
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm) { return &crypto_rng_tfm(tfm)->__crt_alg->cra_rng; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: static int tipc_wait_for_connect(struct socket *sock, long *timeo_p) { struct sock *sk = sock->sk; DEFINE_WAIT(wait); int done; do { int err = sock_error(sk); if (err) return err; if (!*timeo_p) return -ETIMEDOUT; if (signal_pending(current)) return sock_intr_errno(*timeo_p); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); done = sk_wait_event(sk, timeo_p, sock->state != SS_CONNECTING); finish_wait(sk_sleep(sk), &wait); } while (!done); return 0; } Commit Message: tipc: check nl sock before parsing nested attributes Make sure the socket for which the user is listing publication exists before parsing the socket netlink attributes. Prior to this patch a call without any socket caused a NULL pointer dereference in tipc_nl_publ_dump(). Tested-and-reported-by: Baozeng Ding <[email protected]> Signed-off-by: Richard Alpe <[email protected]> Acked-by: Jon Maloy <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: lookup_pi_state(u32 uval, struct futex_hash_bucket *hb, union futex_key *key, struct futex_pi_state **ps) { struct futex_pi_state *pi_state = NULL; struct futex_q *this, *next; struct plist_head *head; struct task_struct *p; pid_t pid = uval & FUTEX_TID_MASK; head = &hb->chain; plist_for_each_entry_safe(this, next, head, list) { if (match_futex(&this->key, key)) { /* * Another waiter already exists - bump up * the refcount and return its pi_state: */ pi_state = this->pi_state; /* * Userspace might have messed up non-PI and PI futexes */ if (unlikely(!pi_state)) return -EINVAL; WARN_ON(!atomic_read(&pi_state->refcount)); /* * When pi_state->owner is NULL then the owner died * and another waiter is on the fly. pi_state->owner * is fixed up by the task which acquires * pi_state->rt_mutex. * * We do not check for pid == 0 which can happen when * the owner died and robust_list_exit() cleared the * TID. */ if (pid && pi_state->owner) { /* * Bail out if user space manipulated the * futex value. */ if (pid != task_pid_vnr(pi_state->owner)) return -EINVAL; } atomic_inc(&pi_state->refcount); *ps = pi_state; return 0; } } /* * We are the first waiter - try to look up the real owner and attach * the new pi_state to it, but bail out when TID = 0 */ if (!pid) return -ESRCH; p = futex_find_get_task(pid); if (!p) return -ESRCH; /* * We need to look at the task state flags to figure out, * whether the task is exiting. To protect against the do_exit * change of the task flags, we do this protected by * p->pi_lock: */ raw_spin_lock_irq(&p->pi_lock); if (unlikely(p->flags & PF_EXITING)) { /* * The task is on the way out. When PF_EXITPIDONE is * set, we know that the task has finished the * cleanup: */ int ret = (p->flags & PF_EXITPIDONE) ? -ESRCH : -EAGAIN; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); return ret; } pi_state = alloc_pi_state(); /* * Initialize the pi_mutex in locked state and make 'p' * the owner of it: */ rt_mutex_init_proxy_locked(&pi_state->pi_mutex, p); /* Store the key for possible exit cleanups: */ pi_state->key = *key; WARN_ON(!list_empty(&pi_state->list)); list_add(&pi_state->list, &p->pi_state_list); pi_state->owner = p; raw_spin_unlock_irq(&p->pi_lock); put_task_struct(p); *ps = pi_state; return 0; } Commit Message: futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi() If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, as the trinity test suite manages to do, we miss early wakeups as q.key is equal to key2 (because they are the same uaddr). We will then attempt to dereference the pi_mutex (which would exist had the futex_q been properly requeued to a pi futex) and trigger a NULL pointer dereference. Signed-off-by: Darren Hart <[email protected]> Cc: Dave Jones <[email protected]> Cc: [email protected] Link: http://lkml.kernel.org/r/ad82bfe7f7d130247fbe2b5b4275654807774227.1342809673.git.dvhart@linux.intel.com Signed-off-by: Thomas Gleixner <[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: int32_t DownmixLib_Create(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle) { int ret; int i; downmix_module_t *module; const effect_descriptor_t *desc; ALOGV("DownmixLib_Create()"); #ifdef DOWNMIX_TEST_CHANNEL_INDEX ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_QUAD_SIDE | CHANNEL_MASK_QUAD_BACK); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_SIDE | AUDIO_CHANNEL_OUT_BACK_CENTER); Downmix_testIndexComputation(CHANNEL_MASK_5POINT1_BACK | AUDIO_CHANNEL_OUT_BACK_CENTER); ALOGI("DOWNMIX_TEST_CHANNEL_INDEX: should NOT work:"); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_BACK_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_FRONT_RIGHT | AUDIO_CHANNEL_OUT_LOW_FREQUENCY | AUDIO_CHANNEL_OUT_SIDE_LEFT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_BACK_LEFT | AUDIO_CHANNEL_OUT_BACK_RIGHT); Downmix_testIndexComputation(AUDIO_CHANNEL_OUT_FRONT_LEFT | AUDIO_CHANNEL_OUT_SIDE_LEFT | AUDIO_CHANNEL_OUT_SIDE_RIGHT); #endif if (pHandle == NULL || uuid == NULL) { return -EINVAL; } for (i = 0 ; i < kNbEffects ; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { break; } } if (i == kNbEffects) { return -ENOENT; } module = malloc(sizeof(downmix_module_t)); module->itfe = &gDownmixInterface; module->context.state = DOWNMIX_STATE_UNINITIALIZED; ret = Downmix_Init(module); if (ret < 0) { ALOGW("DownmixLib_Create() init failed"); free(module); return ret; } *pHandle = (effect_handle_t) module; ALOGV("DownmixLib_Create() %p , size %zu", module, sizeof(downmix_module_t)); return 0; } 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: static char *get_default_chdir(pool *p, xaset_t *conf) { config_rec *c; char *dir = NULL; int ret; c = find_config(conf, CONF_PARAM, "DefaultChdir", FALSE); while (c) { /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } ret = pr_expr_eval_group_and(((char **) c->argv)+1); if (ret) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultChdir", FALSE); } /* If the directory is relative, concatenate w/ session.cwd. */ if (dir && *dir != '/' && *dir != '~') dir = pdircat(p, session.cwd, dir, NULL); /* Check for any expandable variables. */ if (dir) dir = path_subst_uservar(p, &dir); return dir; } Commit Message: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks is off, to 1.3.5 branch. CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ServiceManagerConnectionImpl::ServiceManagerConnectionImpl( service_manager::mojom::ServiceRequest request, scoped_refptr<base::SequencedTaskRunner> io_task_runner) : weak_factory_(this) { service_manager::mojom::ConnectorRequest connector_request; connector_ = service_manager::Connector::Create(&connector_request); std::unique_ptr<service_manager::Connector> io_thread_connector = connector_->Clone(); context_ = new IOThreadContext( std::move(request), io_task_runner, std::move(io_thread_connector), std::move(connector_request)); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119 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 validation_gamma(int argc, char **argv) { double gamma[9] = { 2.2, 1.8, 1.52, 1.45, 1., 1/1.45, 1/1.52, 1/1.8, 1/2.2 }; double maxerr; int i, silent=0, onlygamma=0; /* Silence the output with -s, just test the gamma functions with -g: */ while (--argc > 0) if (strcmp(*++argv, "-s") == 0) silent = 1; else if (strcmp(*argv, "-g") == 0) onlygamma = 1; else { fprintf(stderr, "unknown argument %s\n", *argv); return 1; } if (!onlygamma) { /* First validate the log functions: */ maxerr = 0; for (i=0; i<256; ++i) { double correct = -log(i/255.)/log(2.)*65536; double error = png_log8bit(i) - correct; if (i != 0 && fabs(error) > maxerr) maxerr = fabs(error); if (i == 0 && png_log8bit(i) != 0xffffffff || i != 0 && png_log8bit(i) != floor(correct+.5)) { fprintf(stderr, "8 bit log error: %d: got %u, expected %f\n", i, png_log8bit(i), correct); } } if (!silent) printf("maximum 8 bit log error = %f\n", maxerr); maxerr = 0; for (i=0; i<65536; ++i) { double correct = -log(i/65535.)/log(2.)*65536; double error = png_log16bit(i) - correct; if (i != 0 && fabs(error) > maxerr) maxerr = fabs(error); if (i == 0 && png_log16bit(i) != 0xffffffff || i != 0 && png_log16bit(i) != floor(correct+.5)) { if (error > .68) /* By experiment error is less than .68 */ { fprintf(stderr, "16 bit log error: %d: got %u, expected %f" " error: %f\n", i, png_log16bit(i), correct, error); } } } if (!silent) printf("maximum 16 bit log error = %f\n", maxerr); /* Now exponentiations. */ maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * (65536. * 65536); double error = png_exp(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > 1883) /* By experiment. */ { fprintf(stderr, "32 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp(i), correct, error); } } if (!silent) printf("maximum 32 bit exp error = %f\n", maxerr); maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * 255; double error = png_exp8bit(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > .50002) /* By experiment */ { fprintf(stderr, "8 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp8bit(i), correct, error); } } if (!silent) printf("maximum 8 bit exp error = %f\n", maxerr); maxerr = 0; for (i=0; i<=0xfffff; ++i) { double correct = exp(-i/65536. * log(2.)) * 65535; double error = png_exp16bit(i) - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > .524) /* By experiment */ { fprintf(stderr, "16 bit exp error: %d: got %u, expected %f" " error: %f\n", i, png_exp16bit(i), correct, error); } } if (!silent) printf("maximum 16 bit exp error = %f\n", maxerr); } /* !onlygamma */ /* Test the overall gamma correction. */ for (i=0; i<9; ++i) { unsigned j; double g = gamma[i]; png_fixed_point gfp = floor(g * PNG_FP_1 + .5); if (!silent) printf("Test gamma %f\n", g); maxerr = 0; for (j=0; j<256; ++j) { double correct = pow(j/255., g) * 255; png_byte out = png_gamma_8bit_correct(j, gfp); double error = out - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (out != floor(correct+.5)) { fprintf(stderr, "8bit %d ^ %f: got %d expected %f error %f\n", j, g, out, correct, error); } } if (!silent) printf("gamma %f: maximum 8 bit error %f\n", g, maxerr); maxerr = 0; for (j=0; j<65536; ++j) { double correct = pow(j/65535., g) * 65535; png_uint_16 out = png_gamma_16bit_correct(j, gfp); double error = out - correct; if (fabs(error) > maxerr) maxerr = fabs(error); if (fabs(error) > 1.62) { fprintf(stderr, "16bit %d ^ %f: got %d expected %f error %f\n", j, g, out, correct, error); } } if (!silent) printf("gamma %f: maximum 16 bit error %f\n", g, maxerr); } return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Target: 1 Example 2: Code: void iput(struct inode *inode) { if (!inode) return; BUG_ON(inode->i_state & I_CLEAR); retry: if (atomic_dec_and_lock(&inode->i_count, &inode->i_lock)) { if (inode->i_nlink && (inode->i_state & I_DIRTY_TIME)) { atomic_inc(&inode->i_count); spin_unlock(&inode->i_lock); trace_writeback_lazytime_iput(inode); mark_inode_dirty_sync(inode); goto retry; } iput_final(inode); } } Commit Message: Fix up non-directory creation in SGID directories sgid directories have special semantics, making newly created files in the directory belong to the group of the directory, and newly created subdirectories will also become sgid. This is historically used for group-shared directories. But group directories writable by non-group members should not imply that such non-group members can magically join the group, so make sure to clear the sgid bit on non-directories for non-members (but remember that sgid without group execute means "mandatory locking", just to confuse things even more). Reported-by: Jann Horn <[email protected]> Cc: Andy Lutomirski <[email protected]> Cc: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> 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: static void lsi_queue_command(LSIState *s) { lsi_request *p = s->current; trace_lsi_queue_command(p->tag); assert(s->current != NULL); assert(s->current->dma_len == 0); QTAILQ_INSERT_TAIL(&s->queue, s->current, next); s->current = NULL; p->pending = 0; p->out = (s->sstat1 & PHASE_MASK) == PHASE_DO; } Commit Message: CWE ID: CWE-835 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 needs_empty_write(sector_t block, struct inode *inode) { int error; struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; bh_map.b_size = 1 << inode->i_blkbits; error = gfs2_block_map(inode, block, &bh_map, 0); if (unlikely(error)) return error; return !buffer_mapped(&bh_map); } Commit Message: GFS2: rewrite fallocate code to write blocks directly GFS2's fallocate code currently goes through the page cache. Since it's only writing to the end of the file or to holes in it, it doesn't need to, and it was causing issues on low memory environments. This patch pulls in some of Steve's block allocation work, and uses it to simply allocate the blocks for the file, and zero them out at allocation time. It provides a slight performance increase, and it dramatically simplifies the code. Signed-off-by: Benjamin Marzinski <[email protected]> Signed-off-by: Steven Whitehouse <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static inline int check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (!(dir->i_mode & S_ISVTX)) return 0; if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable_wrt_inode_uidgid(inode, CAP_FOWNER); } Commit Message: fs: umount on symlink leaks mnt count Currently umount on symlink blocks following umount: /vz is separate mount # ls /vz/ -al | grep test drwxr-xr-x. 2 root root 4096 Jul 19 01:14 testdir lrwxrwxrwx. 1 root root 11 Jul 19 01:16 testlink -> /vz/testdir # umount -l /vz/testlink umount: /vz/testlink: not mounted (expected) # lsof /vz # umount /vz umount: /vz: device is busy. (unexpected) In this case mountpoint_last() gets an extra refcount on path->mnt Signed-off-by: Vasily Averin <[email protected]> Acked-by: Ian Kent <[email protected]> Acked-by: Jeff Layton <[email protected]> Cc: [email protected] Signed-off-by: Christoph Hellwig <[email protected]> CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { 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) { 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 = 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_cache(); 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. */ 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: Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks is off, to 1.3.5 branch. 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 void timer_config_save(UNUSED_ATTR void *data) { assert(config != NULL); assert(alarm_timer != NULL); static const size_t CACHE_MAX = 256; const char *keys[CACHE_MAX]; size_t num_keys = 0; size_t total_candidates = 0; pthread_mutex_lock(&lock); for (const config_section_node_t *snode = config_section_begin(config); snode != config_section_end(config); snode = config_section_next(snode)) { const char *section = config_section_name(snode); if (!string_is_bdaddr(section)) continue; if (config_has_key(config, section, "LinkKey") || config_has_key(config, section, "LE_KEY_PENC") || config_has_key(config, section, "LE_KEY_PID") || config_has_key(config, section, "LE_KEY_PCSRK") || config_has_key(config, section, "LE_KEY_LENC") || config_has_key(config, section, "LE_KEY_LCSRK")) continue; if (num_keys < CACHE_MAX) keys[num_keys++] = section; ++total_candidates; } if (total_candidates > CACHE_MAX * 2) while (num_keys > 0) config_remove_section(config, keys[--num_keys]); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119 Target: 1 Example 2: Code: GraphicsSurfaceToken GraphicsContext3DPrivate::graphicsSurfaceToken() const { return m_graphicsSurface->exportToken(); } Commit Message: [Qt] Remove an unnecessary masking from swapBgrToRgb() https://bugs.webkit.org/show_bug.cgi?id=103630 Reviewed by Zoltan Herczeg. Get rid of a masking command in swapBgrToRgb() to speed up a little bit. * platform/graphics/qt/GraphicsContext3DQt.cpp: (WebCore::swapBgrToRgb): git-svn-id: svn://svn.chromium.org/blink/trunk@136375 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 TryCreateDuplicateRequestIds(Shell* shell, bool block_loaders) { NavigateToURL(shell, GURL("http://foo.com/simple_page.html")); RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>( shell->web_contents()->GetMainFrame()); if (block_loaders) { rfh->BlockRequestsForFrame(); } const char* blocking_url = net::URLRequestSlowDownloadJob::kUnknownSizeUrl; network::ResourceRequest request(CreateXHRRequest(blocking_url)); RenderProcessHostKillWaiter kill_waiter(rfh->GetProcess()); network::mojom::URLLoaderPtr loader1, loader2; network::TestURLLoaderClient client1, client2; CreateLoaderAndStart(rfh, mojo::MakeRequest(&loader1), rfh->GetRoutingID(), kRequestIdNotPreviouslyUsed, request, client1.CreateInterfacePtr().PassInterface()); CreateLoaderAndStart(rfh, mojo::MakeRequest(&loader2), rfh->GetRoutingID(), kRequestIdNotPreviouslyUsed, request, client2.CreateInterfacePtr().PassInterface()); EXPECT_EQ(bad_message::RDH_INVALID_REQUEST_ID, kill_waiter.Wait()); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} 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: void WT_InterpolateNoLoop (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_PCM *pOutputBuffer; EAS_I32 phaseInc; EAS_I32 phaseFrac; EAS_I32 acc0; const EAS_SAMPLE *pSamples; EAS_I32 samp1; EAS_I32 samp2; EAS_I32 numSamples; /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pOutputBuffer = pWTIntFrame->pAudioBuffer; phaseInc = pWTIntFrame->frame.phaseIncrement; pSamples = (const EAS_SAMPLE*) pWTVoice->phaseAccum; phaseFrac = (EAS_I32)pWTVoice->phaseFrac; /* fetch adjacent samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif while (numSamples--) { /* linear interpolation */ acc0 = samp2 - samp1; acc0 = acc0 * phaseFrac; /*lint -e{704} <avoid divide>*/ acc0 = samp1 + (acc0 >> NUM_PHASE_FRAC_BITS); /* save new output sample in buffer */ /*lint -e{704} <avoid divide>*/ *pOutputBuffer++ = (EAS_I16)(acc0 >> 2); /* increment phase */ phaseFrac += phaseInc; /*lint -e{704} <avoid divide>*/ acc0 = phaseFrac >> NUM_PHASE_FRAC_BITS; /* next sample */ if (acc0 > 0) { /* advance sample pointer */ pSamples += acc0; phaseFrac = (EAS_I32)((EAS_U32)phaseFrac & PHASE_FRAC_MASK); /* fetch new samples */ #if defined(_8_BIT_SAMPLES) /*lint -e{701} <avoid multiply for performance>*/ samp1 = pSamples[0] << 8; /*lint -e{701} <avoid multiply for performance>*/ samp2 = pSamples[1] << 8; #else samp1 = pSamples[0]; samp2 = pSamples[1]; #endif } } /* save pointer and phase */ pWTVoice->phaseAccum = (EAS_U32) pSamples; pWTVoice->phaseFrac = (EAS_U32) phaseFrac; } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119 Target: 1 Example 2: Code: static void dynamicPutchar(struct gdIOCtx *ctx, int a) { unsigned char b; dpIOCtxPtr dctx; b = a; dctx = (dpIOCtxPtr) ctx; appendDynamic(dctx->dp, &b, 1); } Commit Message: Avoid potentially dangerous signed to unsigned conversion We make sure to never pass a negative `rlen` as size to memcpy(). See also <https://bugs.php.net/bug.php?id=73280>. Patch provided by Emmanuel Law. 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 ServiceWorkerContextCore::UpdateVersionFailureCount( int64_t version_id, blink::ServiceWorkerStatusCode status) { if (status == blink::ServiceWorkerStatusCode::kErrorDisallowed) return; auto it = failure_counts_.find(version_id); if (it != failure_counts_.end()) { ServiceWorkerMetrics::RecordStartStatusAfterFailure(it->second.count, status); } if (status == blink::ServiceWorkerStatusCode::kOk) { if (it != failure_counts_.end()) failure_counts_.erase(it); return; } if (it != failure_counts_.end()) { FailureInfo& info = it->second; DCHECK_GT(info.count, 0); if (info.count < std::numeric_limits<int>::max()) { ++info.count; info.last_failure = status; } } else { FailureInfo info; info.count = 1; info.last_failure = status; failure_counts_[version_id] = info; } } 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 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 asn1_write_OctetString(struct asn1_data *data, const void *p, size_t length) { asn1_push_tag(data, ASN1_OCTET_STRING); asn1_write(data, p, length); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static void uas_do_work(struct work_struct *work) { struct uas_dev_info *devinfo = container_of(work, struct uas_dev_info, work); struct uas_cmd_info *cmdinfo; struct scsi_cmnd *cmnd; unsigned long flags; int i, err; spin_lock_irqsave(&devinfo->lock, flags); if (devinfo->resetting) goto out; for (i = 0; i < devinfo->qdepth; i++) { if (!devinfo->cmnd[i]) continue; cmnd = devinfo->cmnd[i]; cmdinfo = (void *)&cmnd->SCp; if (!(cmdinfo->state & IS_IN_WORK_LIST)) continue; err = uas_submit_urbs(cmnd, cmnd->device->hostdata); if (!err) cmdinfo->state &= ~IS_IN_WORK_LIST; else schedule_work(&devinfo->work); } out: spin_unlock_irqrestore(&devinfo->lock, flags); } Commit Message: USB: uas: fix bug in handling of alternate settings The uas driver has a subtle bug in the way it handles alternate settings. The uas_find_uas_alt_setting() routine returns an altsetting value (the bAlternateSetting number in the descriptor), but uas_use_uas_driver() then treats that value as an index to the intf->altsetting array, which it isn't. Normally this doesn't cause any problems because the various alternate settings have bAlternateSetting values 0, 1, 2, ..., so the value is equal to the index in the array. But this is not guaranteed, and Andrey Konovalov used the syzkaller fuzzer with KASAN to get a slab-out-of-bounds error by violating this assumption. This patch fixes the bug by making uas_find_uas_alt_setting() return a pointer to the altsetting entry rather than either the value or the index. Pointers are less subject to misinterpretation. Signed-off-by: Alan Stern <[email protected]> Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> CC: Oliver Neukum <[email protected]> CC: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void inet_register_protosw(struct inet_protosw *p) { struct list_head *lh; struct inet_protosw *answer; int protocol = p->protocol; struct list_head *last_perm; spin_lock_bh(&inetsw_lock); if (p->type >= SOCK_MAX) goto out_illegal; /* If we are trying to override a permanent protocol, bail. */ last_perm = &inetsw[p->type]; list_for_each(lh, &inetsw[p->type]) { answer = list_entry(lh, struct inet_protosw, list); /* Check only the non-wild match. */ if ((INET_PROTOSW_PERMANENT & answer->flags) == 0) break; if (protocol == answer->protocol) goto out_permanent; last_perm = lh; } /* Add the new entry after the last permanent entry if any, so that * the new entry does not override a permanent entry when matched with * a wild-card protocol. But it is allowed to override any existing * non-permanent entry. This means that when we remove this entry, the * system automatically returns to the old behavior. */ list_add_rcu(&p->list, last_perm); out: spin_unlock_bh(&inetsw_lock); return; out_permanent: pr_err("Attempt to override permanent protocol %d\n", protocol); goto out; out_illegal: pr_err("Ignoring attempt to register invalid socket type %d\n", p->type); goto out; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: 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 XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: static long ocfs2_fallocate(struct file *file, int mode, loff_t offset, loff_t len) { struct inode *inode = file_inode(file); struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); struct ocfs2_space_resv sr; int change_size = 1; int cmd = OCFS2_IOC_RESVSP64; if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE)) return -EOPNOTSUPP; if (!ocfs2_writes_unwritten_extents(osb)) return -EOPNOTSUPP; if (mode & FALLOC_FL_KEEP_SIZE) change_size = 0; if (mode & FALLOC_FL_PUNCH_HOLE) cmd = OCFS2_IOC_UNRESVSP64; sr.l_whence = 0; sr.l_start = (s64)offset; sr.l_len = (s64)len; return __ocfs2_change_file_space(NULL, inode, offset, cmd, &sr, change_size); } Commit Message: ocfs2: should wait dio before inode lock in ocfs2_setattr() we should wait dio requests to finish before inode lock in ocfs2_setattr(), otherwise the following deadlock will happen: process 1 process 2 process 3 truncate file 'A' end_io of writing file 'A' receiving the bast messages ocfs2_setattr ocfs2_inode_lock_tracker ocfs2_inode_lock_full inode_dio_wait __inode_dio_wait -->waiting for all dio requests finish dlm_proxy_ast_handler dlm_do_local_bast ocfs2_blocking_ast ocfs2_generic_handle_bast set OCFS2_LOCK_BLOCKED flag dio_end_io dio_bio_end_aio dio_complete ocfs2_dio_end_io ocfs2_dio_end_io_write ocfs2_inode_lock __ocfs2_cluster_lock ocfs2_wait_for_mask -->waiting for OCFS2_LOCK_BLOCKED flag to be cleared, that is waiting for 'process 1' unlocking the inode lock inode_dio_end -->here dec the i_dio_count, but will never be called, so a deadlock happened. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[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: static void multipath_postsuspend(struct dm_target *ti) { struct multipath *m = ti->private; mutex_lock(&m->work_mutex); flush_multipath_work(m); mutex_unlock(&m->work_mutex); } Commit Message: dm: do not forward ioctls from logical volumes to the underlying device A logical volume can map to just part of underlying physical volume. In this case, it must be treated like a partition. Based on a patch from Alasdair G Kergon. Cc: Alasdair G Kergon <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[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: png_get_int_32(png_bytep buf) { png_int_32 i = ((png_int_32)(*buf) << 24) + ((png_int_32)(*(buf + 1)) << 16) + ((png_int_32)(*(buf + 2)) << 8) + (png_int_32)(*(buf + 3)); return (i); } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: QList<Smb4KShare *> Smb4KGlobal::findShareByUNC(const QString &unc) { QList<Smb4KShare *> shares; mutex.lock(); if (!unc.isEmpty() && !p->mountedSharesList.isEmpty()) { for (Smb4KShare *s : p->mountedSharesList) { if (QString::compare(s->unc(), unc, Qt::CaseInsensitive) == 0) { shares += s; } else { } } } else { } mutex.unlock(); return shares; } 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 u64 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr) { struct kvm_shadow_walk_iterator iterator; u64 spte = 0ull; walk_shadow_page_lockless_begin(vcpu); for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) if (!is_shadow_present_pte(spte)) break; walk_shadow_page_lockless_end(vcpu); return spte; } 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: void AcceleratedStaticBitmapImage::RetainOriginalSkImage() { DCHECK(texture_holder_->IsSkiaTextureHolder()); original_skia_image_ = texture_holder_->GetSkImage(); original_skia_image_context_provider_wrapper_ = ContextProviderWrapper(); DCHECK(original_skia_image_); Thread* thread = Platform::Current()->CurrentThread(); original_skia_image_thread_id_ = thread->ThreadId(); original_skia_image_task_runner_ = thread->GetTaskRunner(); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119 Target: 1 Example 2: Code: RenderWidgetFullscreenPepper* RenderFrameImpl::CreatePepperFullscreenContainer( PepperPluginInstanceImpl* plugin) { GURL active_url; if (render_view()->webview()) active_url = render_view()->GetURLForGraphicsContext3D(); mojom::WidgetPtr widget_channel; mojom::WidgetRequest widget_channel_request = mojo::MakeRequest(&widget_channel); int32_t fullscreen_widget_routing_id = MSG_ROUTING_NONE; if (!RenderThreadImpl::current_render_message_filter() ->CreateFullscreenWidget(render_view()->routing_id(), std::move(widget_channel), &fullscreen_widget_routing_id)) { return nullptr; } RenderWidget::ShowCallback show_callback = base::Bind(&RenderViewImpl::ShowCreatedFullscreenWidget, render_view()->GetWeakPtr()); RenderWidgetFullscreenPepper* widget = RenderWidgetFullscreenPepper::Create( fullscreen_widget_routing_id, show_callback, GetRenderWidget()->compositor_deps(), plugin, active_url, GetRenderWidget()->screen_info(), std::move(widget_channel_request)); widget->Show(blink::kWebNavigationPolicyIgnore); return widget; } Commit Message: If a page calls |window.focus()|, kick it out of fullscreen. BUG=776418, 800056 Change-Id: I1880fe600e4814c073f247c43b1c1ac80c8fc017 Reviewed-on: https://chromium-review.googlesource.com/852378 Reviewed-by: Nasko Oskov <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#533790} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ExtensionDevToolsClientHost::~ExtensionDevToolsClientHost() { if (infobar_) infobar_->Remove(this); g_attached_client_hosts.Get().erase(this); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20 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: cff_parser_run( CFF_Parser parser, FT_Byte* start, FT_Byte* limit ) { FT_Byte* p = start; FT_Error error = FT_Err_Ok; FT_Library library = parser->library; FT_UNUSED( library ); parser->top = parser->stack; parser->start = start; parser->limit = limit; parser->cursor = start; while ( p < limit ) { FT_UInt v = *p; /* Opcode 31 is legacy MM T2 operator, not a number. */ /* Opcode 255 is reserved and should not appear in fonts; */ /* it is used internally for CFF2 blends. */ if ( v >= 27 && v != 31 && v != 255 ) { /* it's a number; we will push its position on the stack */ if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = p; /* now, skip it */ if ( v == 30 ) { /* skip real number */ p++; for (;;) { /* An unterminated floating point number at the */ /* end of a dictionary is invalid but harmless. */ if ( p >= limit ) goto Exit; v = p[0] >> 4; if ( v == 15 ) break; v = p[0] & 0xF; if ( v == 15 ) break; p++; } } else if ( v == 28 ) p += 2; else if ( v == 29 ) p += 4; else if ( v > 246 ) p += 1; } #ifdef CFF_CONFIG_OPTION_OLD_ENGINE else if ( v == 31 ) { /* a Type 2 charstring */ CFF_Decoder decoder; CFF_FontRec cff_rec; FT_Byte* charstring_base; FT_ULong charstring_len; FT_Fixed* stack; FT_Byte* q; charstring_base = ++p; /* search `endchar' operator */ for (;;) { if ( p >= limit ) goto Exit; if ( *p == 14 ) break; p++; } charstring_len = (FT_ULong)( p - charstring_base ) + 1; /* construct CFF_Decoder object */ FT_ZERO( &decoder ); FT_ZERO( &cff_rec ); cff_rec.top_font.font_dict.num_designs = parser->num_designs; cff_rec.top_font.font_dict.num_axes = parser->num_axes; decoder.cff = &cff_rec; error = cff_decoder_parse_charstrings( &decoder, charstring_base, charstring_len, 1 ); /* Now copy the stack data in the temporary decoder object, */ /* converting it back to charstring number representations */ /* (this is ugly, I know). */ /* */ /* We overwrite the original top DICT charstring under the */ /* assumption that the charstring representation of the result */ /* of `cff_decoder_parse_charstrings' is shorter, which should */ /* be always true. */ q = charstring_base - 1; stack = decoder.stack; while ( stack < decoder.top ) { FT_ULong num; FT_Bool neg; if ( (FT_UInt)( parser->top - parser->stack ) >= parser->stackSize ) goto Stack_Overflow; *parser->top++ = q; if ( *stack < 0 ) { num = (FT_ULong)-*stack; neg = 1; } else { num = (FT_ULong)*stack; neg = 0; } if ( num & 0xFFFFU ) { if ( neg ) num = (FT_ULong)-num; *q++ = 255; *q++ = ( num & 0xFF000000U ) >> 24; *q++ = ( num & 0x00FF0000U ) >> 16; *q++ = ( num & 0x0000FF00U ) >> 8; *q++ = num & 0x000000FFU; } else { num >>= 16; if ( neg ) { if ( num <= 107 ) *q++ = (FT_Byte)( 139 - num ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 251 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { num = (FT_ULong)-num; *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } else { if ( num <= 107 ) *q++ = (FT_Byte)( num + 139 ); else if ( num <= 1131 ) { *q++ = (FT_Byte)( ( ( num - 108 ) >> 8 ) + 247 ); *q++ = (FT_Byte)( ( num - 108 ) & 0xFF ); } else { *q++ = 28; *q++ = (FT_Byte)( num >> 8 ); *q++ = (FT_Byte)( num & 0xFF ); } } } stack++; } } #endif /* CFF_CONFIG_OPTION_OLD_ENGINE */ else { /* This is not a number, hence it's an operator. Compute its code */ /* and look for it in our current list. */ FT_UInt code; FT_UInt num_args = (FT_UInt) ( parser->top - parser->stack ); const CFF_Field_Handler* field; *parser->top = p; code = v; if ( v == 12 ) { /* two byte operator */ code = 0x100 | p[0]; } code = code | parser->object_code; for ( field = CFF_FIELD_HANDLERS_GET; field->kind; field++ ) { if ( field->code == (FT_Int)code ) { /* we found our field's handler; read it */ FT_Long val; FT_Byte* q = (FT_Byte*)parser->object + field->offset; #ifdef FT_DEBUG_LEVEL_TRACE FT_TRACE4(( " %s", field->id )); #endif /* check that we have enough arguments -- except for */ /* delta encoded arrays, which can be empty */ if ( field->kind != cff_kind_delta && num_args < 1 ) goto Stack_Underflow; switch ( field->kind ) { case cff_kind_bool: case cff_kind_string: case cff_kind_num: val = cff_parse_num( parser, parser->stack ); goto Store_Number; case cff_kind_fixed: val = cff_parse_fixed( parser, parser->stack ); goto Store_Number; case cff_kind_fixed_thousand: val = cff_parse_fixed_scaled( parser, parser->stack, 3 ); Store_Number: switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } #ifdef FT_DEBUG_LEVEL_TRACE switch ( field->kind ) { case cff_kind_bool: FT_TRACE4(( " %s\n", val ? "true" : "false" )); break; case cff_kind_string: FT_TRACE4(( " %ld (SID)\n", val )); break; case cff_kind_num: FT_TRACE4(( " %ld\n", val )); break; case cff_kind_fixed: FT_TRACE4(( " %f\n", (double)val / 65536 )); break; case cff_kind_fixed_thousand: FT_TRACE4(( " %f\n", (double)val / 65536 / 1000 )); default: ; /* never reached */ } #endif break; case cff_kind_delta: { FT_Byte* qcount = (FT_Byte*)parser->object + field->count_offset; FT_Byte** data = parser->stack; if ( num_args > field->array_max ) num_args = field->array_max; FT_TRACE4(( " [" )); /* store count */ *qcount = (FT_Byte)num_args; val = 0; while ( num_args > 0 ) { val += cff_parse_num( parser, data++ ); switch ( field->size ) { case (8 / FT_CHAR_BIT): *(FT_Byte*)q = (FT_Byte)val; break; case (16 / FT_CHAR_BIT): *(FT_Short*)q = (FT_Short)val; break; case (32 / FT_CHAR_BIT): *(FT_Int32*)q = (FT_Int)val; break; default: /* for 64-bit systems */ *(FT_Long*)q = val; } FT_TRACE4(( " %ld", val )); q += field->size; num_args--; } FT_TRACE4(( "]\n" )); } break; default: /* callback or blend */ error = field->reader( parser ); if ( error ) goto Exit; } goto Found; } } /* this is an unknown operator, or it is unsupported; */ /* we will ignore it for now. */ Found: /* clear stack */ /* TODO: could clear blend stack here, */ /* but we don't have access to subFont */ if ( field->kind != cff_kind_blend ) parser->top = parser->stack; } p++; } Exit: return error; Stack_Overflow: error = FT_THROW( Invalid_Argument ); goto Exit; Stack_Underflow: error = FT_THROW( Invalid_Argument ); goto Exit; Syntax_Error: error = FT_THROW( Invalid_Argument ); goto Exit; } Commit Message: CWE ID: CWE-787 Target: 1 Example 2: Code: on_window_deletion(void *user_data, Evas_Object *window, void *event_info) { window_close(browser_window_find(window)); } Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser https://bugs.webkit.org/show_bug.cgi?id=100942 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05 Reviewed by Kenneth Rohde Christiansen. Added window-size (-s) command line option to EFL MiniBrowser. * MiniBrowser/efl/main.c: (window_create): (parse_window_size): (elm_main): git-svn-id: svn://svn.chromium.org/blink/trunk@133450 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: GahpClient::condor_job_stage_in(const char *schedd_name, ClassAd *job_ad) { static const char* command = "CONDOR_JOB_STAGE_IN"; MyString ad_string; if (server->m_commands_supported->contains_anycase(command)==FALSE) { return GAHPCLIENT_COMMAND_NOT_SUPPORTED; } if (!schedd_name) schedd_name=NULLSTRING; if (!job_ad) { ad_string=NULLSTRING; } else { if ( useXMLClassads ) { ClassAdXMLUnparser unparser; unparser.SetUseCompactSpacing( true ); unparser.SetOutputType( false ); unparser.SetOutputTargetType( false ); unparser.Unparse( job_ad, ad_string ); } else { NewClassAdUnparser unparser; unparser.SetUseCompactSpacing( true ); unparser.SetOutputType( false ); unparser.SetOutputTargetType( false ); unparser.Unparse( job_ad, ad_string ); } } std::string reqline; char *esc1 = strdup( escapeGahpString(schedd_name) ); char *esc2 = strdup( escapeGahpString(ad_string.Value()) ); int x = sprintf(reqline, "%s %s", esc1, esc2); free( esc1 ); free( esc2 ); ASSERT( x > 0 ); const char *buf = reqline.c_str(); if ( !is_pending(command,buf) ) { if ( m_mode == results_only ) { return GAHPCLIENT_COMMAND_NOT_SUBMITTED; } now_pending(command,buf,deleg_proxy); } Gahp_Args* result = get_pending_result(command,buf); if ( result ) { if (result->argc != 3) { EXCEPT("Bad %s Result",command); } int rc = 1; if ( result->argv[1][0] == 'S' ) { rc = 0; } if ( strcasecmp(result->argv[2], NULLSTRING) ) { error_string = result->argv[2]; } else { error_string = ""; } delete result; return rc; } if ( check_pending_timeout(command,buf) ) { sprintf( error_string, "%s timed out", command ); return GAHPCLIENT_COMMAND_TIMED_OUT; } return GAHPCLIENT_COMMAND_PENDING; } 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: image_transform_png_set_expand_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 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: static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st) { AVIndexEntry *sample = NULL; int64_t best_dts = INT64_MAX; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *avst = s->streams[i]; MOVStreamContext *msc = avst->priv_data; if (msc->pb && msc->current_sample < avst->nb_index_entries) { AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample]; int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale); av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts); if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) || ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) || (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) { sample = current_sample; best_dts = dts; *st = avst; } } } return sample; } Commit Message: avformat/mov: Fix DoS in read_tfra() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: SPR_SetFieldsEntry(struct rx_call *call, afs_int32 id, afs_int32 mask, /* specify which fields to update */ afs_int32 flags, afs_int32 ngroups, afs_int32 nusers, afs_int32 spare1, afs_int32 spare2) { afs_int32 code; afs_int32 cid = ANONYMOUSID; code = setFieldsEntry(call, id, mask, flags, ngroups, nusers, spare1, spare2, &cid); osi_auditU(call, PTS_SetFldEntEvent, code, AUD_ID, id, AUD_END); ViceLog(5, ("PTS_SetFieldsEntry: code %d cid %d id %d\n", code, cid, id)); return code; } Commit Message: CWE ID: CWE-284 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: AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id) : cache_id_(cache_id), owning_group_(nullptr), online_whitelist_all_(false), is_complete_(false), cache_size_(0), storage_(storage) { storage_->working_set()->AddCache(this); } 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: GBool JBIG2Stream::isBinary(GBool last) { return str->isBinary(gTrue); } 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: bool IsReparentedNode(const AXNode* node) { return IsNewNode(node) && IsRemovedNode(node); } Commit Message: Position info (item n of m) incorrect if hidden focusable items in list Bug: 836997 Change-Id: I971fa7076f72d51829b36af8e379260d48ca25ec Reviewed-on: https://chromium-review.googlesource.com/c/1450235 Commit-Queue: Aaron Leventhal <[email protected]> Reviewed-by: Nektarios Paisios <[email protected]> Cr-Commit-Position: refs/heads/master@{#628890} CWE ID: CWE-190 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: size_t mptsas_config_manufacturing_1(MPTSASState *s, uint8_t **data, int address) { /* VPD - all zeros */ return MPTSAS_CONFIG_PACK(1, MPI_CONFIG_PAGETYPE_MANUFACTURING, 0x00, "s256"); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: static int opverr(RAsm *a, ut8 *data, const Opcode *op) { int l = 0; switch (op->operands_count) { case 1: if ( op->operands[0].type & OT_WORD ) { data[l++] = 0x0f; data[l++] = 0x00; if ( op->operands[0].type & OT_MEMORY ) { data[l++] = 0x20 | op->operands[0].regs[0]; } else { data[l++] = 0xe0 | op->operands[0].reg; } } else { return -1; } break; default: return -1; } return l; } Commit Message: Fix #12372 and #12373 - Crash in x86 assembler (#12380) 0 ,0,[bP-bL-bP-bL-bL-r-bL-bP-bL-bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- leA ,0,[bP-bL-bL-bP-bL-bP-bL-60@bL- leA ,0,[bP-bL-r-bP-bL-bP-bL-60@bL- mov ,0,[ax+Bx-ax+Bx-ax+ax+Bx-ax+Bx-- 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 dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req, int status) { struct dwc3 *dwc = dep->dwc; req->started = false; list_del(&req->list); req->remaining = 0; if (req->request.status == -EINPROGRESS) req->request.status = status; if (req->trb) usb_gadget_unmap_request_by_dev(dwc->sysdev, &req->request, req->direction); req->trb = NULL; trace_dwc3_gadget_giveback(req); spin_unlock(&dwc->lock); usb_gadget_giveback_request(&dep->endpoint, &req->request); spin_lock(&dwc->lock); if (dep->number > 1) pm_runtime_put(dwc->dev); } Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue() This is a requirement which has always existed but, somehow, wasn't reflected in the documentation and problems weren't found until now when Tuba Yavuz found a possible deadlock happening between dwc3 and f_hid. She described the situation as follows: spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire /* we our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, hidg->req); goto try_again; } [...] status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC); => [...] => usb_gadget_giveback_request => f_hidg_req_complete => spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire Note that this happens because dwc3 would call ->complete() on a failed usb_ep_queue() due to failed Start Transfer command. This is, anyway, a theoretical situation because dwc3 currently uses "No Response Update Transfer" command for Bulk and Interrupt endpoints. It's still good to make this case impossible to happen even if the "No Reponse Update Transfer" command is changed. Reported-by: Tuba Yavuz <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI, xsltPreComputeFunction precomp, xsltTransformFunction transform) { int ret; xsltExtElementPtr ext; if ((name == NULL) || (URI == NULL) || (transform == NULL)) return (-1); if (xsltElementsHash == NULL) xsltElementsHash = xmlHashCreate(10); if (xsltElementsHash == NULL) return (-1); xmlMutexLock(xsltExtMutex); ext = xsltNewExtElement(precomp, transform); if (ext == NULL) { ret = -1; goto done; } xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext, (xmlHashDeallocator) xsltFreeExtElement); done: xmlMutexUnlock(xsltExtMutex); return (0); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 1 Example 2: Code: static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us) { u64 rt_runtime, rt_period; rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period); rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC; if (rt_runtime_us < 0) rt_runtime = RUNTIME_INF; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann) Merge filesystem stacking fixes from Jann Horn. * emailed patches from Jann Horn <[email protected]>: sched: panic on corrupted stack end ecryptfs: forbid opening files without mmap handler proc: prevent stacking filesystems on top 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: ieee802_15_4_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int hdrlen; uint16_t fc; uint8_t seq; uint16_t panid = 0; if (caplen < 3) { ND_PRINT((ndo, "[|802.15.4]")); return caplen; } hdrlen = 3; fc = EXTRACT_LE_16BITS(p); seq = EXTRACT_LE_8BITS(p + 2); p += 3; caplen -= 3; ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)])); if (ndo->ndo_vflag) ND_PRINT((ndo,"seq %02x ", seq)); /* * Destination address and PAN ID, if present. */ switch (FC_DEST_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (fc & FC_PAN_ID_COMPRESSION) { /* * PAN ID compression; this requires that both * the source and destination addresses be present, * but the destination address is missing. */ ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved destination addressing mode")); return hdrlen; case FC_ADDRESSING_MODE_SHORT: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2))); p += 8; caplen -= 8; hdrlen += 8; break; } if (ndo->ndo_vflag) ND_PRINT((ndo,"< ")); /* * Source address and PAN ID, if present. */ switch (FC_SRC_ADDRESSING_MODE(fc)) { case FC_ADDRESSING_MODE_NONE: if (ndo->ndo_vflag) ND_PRINT((ndo,"none ")); break; case FC_ADDRESSING_MODE_RESERVED: if (ndo->ndo_vflag) ND_PRINT((ndo,"reserved source addressing mode")); return 0; case FC_ADDRESSING_MODE_SHORT: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p))); p += 2; caplen -= 2; hdrlen += 2; break; case FC_ADDRESSING_MODE_LONG: if (!(fc & FC_PAN_ID_COMPRESSION)) { /* * The source PAN ID is not compressed out, so * fetch it. (Otherwise, we'll use the destination * PAN ID, fetched above.) */ if (caplen < 2) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } panid = EXTRACT_LE_16BITS(p); p += 2; caplen -= 2; hdrlen += 2; } if (caplen < 8) { ND_PRINT((ndo, "[|802.15.4]")); return hdrlen; } if (ndo->ndo_vflag) ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p))); p += 8; caplen -= 8; hdrlen += 8; break; } if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); return hdrlen; } Commit Message: CVE-2017-13000/IEEE 802.15.4: Fix bug introduced by previous fix. We've already advanced the pointer past the PAN ID, if present; it now points to the address, so don't add 2 to it. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 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 xpm_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { XPMDecContext *x = avctx->priv_data; AVFrame *p=data; const uint8_t *end, *ptr = avpkt->data; int ncolors, cpp, ret, i, j; int64_t size; uint32_t *dst; avctx->pix_fmt = AV_PIX_FMT_BGRA; end = avpkt->data + avpkt->size; while (memcmp(ptr, "/* XPM */", 9) && ptr < end - 9) ptr++; if (ptr >= end) { av_log(avctx, AV_LOG_ERROR, "missing signature\n"); return AVERROR_INVALIDDATA; } ptr += mod_strcspn(ptr, "\""); if (sscanf(ptr, "\"%u %u %u %u\",", &avctx->width, &avctx->height, &ncolors, &cpp) != 4) { av_log(avctx, AV_LOG_ERROR, "missing image parameters\n"); return AVERROR_INVALIDDATA; } if ((ret = ff_set_dimensions(avctx, avctx->width, avctx->height)) < 0) return ret; if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; if (cpp <= 0 || cpp >= 5) { av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of chars per pixel: %d\n", cpp); return AVERROR_INVALIDDATA; } size = 1; for (i = 0; i < cpp; i++) size *= 94; if (ncolors <= 0 || ncolors > size) { av_log(avctx, AV_LOG_ERROR, "invalid number of colors: %d\n", ncolors); return AVERROR_INVALIDDATA; } size *= 4; av_fast_padded_malloc(&x->pixels, &x->pixels_size, size); if (!x->pixels) return AVERROR(ENOMEM); ptr += mod_strcspn(ptr, ",") + 1; for (i = 0; i < ncolors; i++) { const uint8_t *index; int len; ptr += mod_strcspn(ptr, "\"") + 1; if (ptr + cpp > end) return AVERROR_INVALIDDATA; index = ptr; ptr += cpp; ptr = strstr(ptr, "c "); if (ptr) { ptr += 2; } else { return AVERROR_INVALIDDATA; } len = strcspn(ptr, "\" "); if ((ret = ascii2index(index, cpp)) < 0) return ret; x->pixels[ret] = color_string_to_rgba(ptr, len); ptr += mod_strcspn(ptr, ",") + 1; } for (i = 0; i < avctx->height; i++) { dst = (uint32_t *)(p->data[0] + i * p->linesize[0]); ptr += mod_strcspn(ptr, "\"") + 1; for (j = 0; j < avctx->width; j++) { if (ptr + cpp > end) return AVERROR_INVALIDDATA; if ((ret = ascii2index(ptr, cpp)) < 0) return ret; *dst++ = x->pixels[ret]; ptr += cpp; } ptr += mod_strcspn(ptr, ",") + 1; } p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; *got_frame = 1; return avpkt->size; } Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues Most of these were found through code review in response to fixing 1466/clusterfuzz-testcase-minimized-5961584419536896 There is thus no testcase for most of this. The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: internal_ipc_send_recv(crm_ipc_t * client, const void *iov) { int rc = 0; do { rc = qb_ipcc_sendv_recv(client->ipc, iov, 2, client->buffer, client->buf_size, -1); } while (rc == -EAGAIN && crm_ipc_connected(client)); return rc; } Commit Message: High: libcrmcommon: fix CVE-2016-7035 (improper IPC guarding) It was discovered that at some not so uncommon circumstances, some pacemaker daemons could be talked to, via libqb-facilitated IPC, by unprivileged clients due to flawed authorization decision. Depending on the capabilities of affected daemons, this might equip unauthorized user with local privilege escalation or up to cluster-wide remote execution of possibly arbitrary commands when such user happens to reside at standard or remote/guest cluster node, respectively. The original vulnerability was introduced in an attempt to allow unprivileged IPC clients to clean up the file system materialized leftovers in case the server (otherwise responsible for the lifecycle of these files) crashes. While the intended part of such behavior is now effectively voided (along with the unintended one), a best-effort fix to address this corner case systemically at libqb is coming along (https://github.com/ClusterLabs/libqb/pull/231). Affected versions: 1.1.10-rc1 (2013-04-17) - 1.1.15 (2016-06-21) Impact: Important CVSSv3 ranking: 8.8 : AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H Credits for independent findings, in chronological order: Jan "poki" Pokorný, of Red Hat Alain Moulle, of ATOS/BULL CWE ID: CWE-285 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Ins_FLIPON( INS_ARG ) { DO_FLIPON } Commit Message: CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int get_client_master_key(SSL *s) { int is_export, i, n, keya, ek; unsigned long len; unsigned char *p; const SSL_CIPHER *cp; const EVP_CIPHER *c; const EVP_MD *md; p = (unsigned char *)s->init_buf->data; if (s->state == SSL2_ST_GET_CLIENT_MASTER_KEY_A) { i = ssl2_read(s, (char *)&(p[s->init_num]), 10 - s->init_num); if (i < (10 - s->init_num)) return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i)); s->init_num = 10; if (*(p++) != SSL2_MT_CLIENT_MASTER_KEY) { if (p[-1] != SSL2_MT_ERROR) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_READ_WRONG_PACKET_TYPE); } else SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PEER_ERROR); return (-1); } cp = ssl2_get_cipher_by_char(p); if (cp == NULL) { ssl2_return_error(s, SSL2_PE_NO_CIPHER); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_CIPHER_MATCH); return (-1); } s->session->cipher = cp; p += 3; n2s(p, i); s->s2->tmp.clear = i; n2s(p, i); s->s2->tmp.enc = i; n2s(p, i); if (i > SSL_MAX_KEY_ARG_LENGTH) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_KEY_ARG_TOO_LONG); return -1; } s->session->key_arg_length = i; s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_B; } /* SSL2_ST_GET_CLIENT_MASTER_KEY_B */ p = (unsigned char *)s->init_buf->data; if (s->init_buf->length < SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, ERR_R_INTERNAL_ERROR); return -1; } keya = s->session->key_arg_length; len = 10 + (unsigned long)s->s2->tmp.clear + (unsigned long)s->s2->tmp.enc + (unsigned long)keya; if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_MESSAGE_TOO_LONG); return -1; } n = (int)len - s->init_num; i = ssl2_read(s, (char *)&(p[s->init_num]), n); if (i != n) return (ssl2_part_read(s, SSL_F_GET_CLIENT_MASTER_KEY, i)); if (s->msg_callback) { /* CLIENT-MASTER-KEY */ s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); } p += 10; memcpy(s->session->key_arg, &(p[s->s2->tmp.clear + s->s2->tmp.enc]), (unsigned int)keya); if (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY); return (-1); } i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc, &(p[s->s2->tmp.clear]), &(p[s->s2->tmp.clear]), (s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING : RSA_PKCS1_PADDING); is_export = SSL_C_IS_EXPORT(s->session->cipher); (s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING : RSA_PKCS1_PADDING); is_export = SSL_C_IS_EXPORT(s->session->cipher); if (!ssl_cipher_get_evp(s->session, &c, &md, NULL, NULL, NULL)) { ssl2_return_error(s, SSL2_PE_NO_CIPHER); SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_PROBLEMS_MAPPING_CIPHER_FUNCTIONS); return (0); } else ek = 5; /* bad decrypt */ # if 1 /* * If a bad decrypt, continue with protocol but with a random master * secret (Bleichenbacher attack) */ if ((i < 0) || ((!is_export && (i != EVP_CIPHER_key_length(c))) || (is_export && ((i != ek) || (s->s2->tmp.clear + (unsigned int)i != (unsigned int) EVP_CIPHER_key_length(c)))))) { ERR_clear_error(); if (is_export) i = ek; else i = EVP_CIPHER_key_length(c); if (RAND_pseudo_bytes(p, i) <= 0) return 0; } # else unsigned long len; unsigned char *p; STACK_OF(SSL_CIPHER) *cs; /* a stack of SSL_CIPHERS */ STACK_OF(SSL_CIPHER) *cl; /* the ones we want to use */ STACK_OF(SSL_CIPHER) *prio, *allow; int z; /* * This is a bit of a hack to check for the correct packet type the first * time round. */ if (s->state == SSL2_ST_GET_CLIENT_HELLO_A) { s->first_packet = 1; s->state = SSL2_ST_GET_CLIENT_HELLO_B; } # endif if (is_export) i += s->s2->tmp.clear; if (i > SSL_MAX_MASTER_KEY_LENGTH) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); if (*(p++) != SSL2_MT_CLIENT_HELLO) { if (p[-1] != SSL2_MT_ERROR) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_READ_WRONG_PACKET_TYPE); } else SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_PEER_ERROR); return (-1); } n2s(p, i); if (i < s->version) s->version = i; n2s(p, i); s->s2->tmp.cipher_spec_length = i; n2s(p, i); s->s2->tmp.session_id_length = i; n2s(p, i); s->s2->challenge_length = i; if ((i < SSL2_MIN_CHALLENGE_LENGTH) || (i > SSL2_MAX_CHALLENGE_LENGTH)) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_INVALID_CHALLENGE_LENGTH); return (-1); } s->state = SSL2_ST_GET_CLIENT_HELLO_C; } /* SSL2_ST_GET_CLIENT_HELLO_C */ p = (unsigned char *)s->init_buf->data; len = 9 + (unsigned long)s->s2->tmp.cipher_spec_length + (unsigned long)s->s2->challenge_length + (unsigned long)s->s2->tmp.session_id_length; if (len > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_MESSAGE_TOO_LONG); return -1; } n = (int)len - s->init_num; i = ssl2_read(s, (char *)&(p[s->init_num]), n); if (i != n) return (ssl2_part_read(s, SSL_F_GET_CLIENT_HELLO, i)); if (s->msg_callback) { /* CLIENT-HELLO */ s->msg_callback(0, s->version, 0, p, (size_t)len, s, s->msg_callback_arg); } p += 9; /* * get session-id before cipher stuff so we can get out session structure * if it is cached */ /* session-id */ if ((s->s2->tmp.session_id_length != 0) && (s->s2->tmp.session_id_length != SSL2_SSL_SESSION_ID_LENGTH)) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_BAD_SSL_SESSION_ID_LENGTH); return (-1); } if (s->s2->tmp.session_id_length == 0) { if (!ssl_get_new_session(s, 1)) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); return (-1); } } else { i = ssl_get_prev_session(s, &(p[s->s2->tmp.cipher_spec_length]), s->s2->tmp.session_id_length, NULL); if (i == 1) { /* previous session */ s->hit = 1; } else if (i == -1) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); return (-1); } else { if (s->cert == NULL) { ssl2_return_error(s, SSL2_PE_NO_CERTIFICATE); SSLerr(SSL_F_GET_CLIENT_HELLO, SSL_R_NO_CERTIFICATE_SET); return (-1); } if (!ssl_get_new_session(s, 1)) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); return (-1); } } } if (!s->hit) { cs = ssl_bytes_to_cipher_list(s, p, s->s2->tmp.cipher_spec_length, &s->session->ciphers); if (cs == NULL) goto mem_err; cl = SSL_get_ciphers(s); if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) { prio = sk_SSL_CIPHER_dup(cl); if (prio == NULL) goto mem_err; allow = cs; } else { prio = cs; allow = cl; } for (z = 0; z < sk_SSL_CIPHER_num(prio); z++) { if (sk_SSL_CIPHER_find(allow, sk_SSL_CIPHER_value(prio, z)) < 0) { (void)sk_SSL_CIPHER_delete(prio, z); z--; } } if (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) { sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers = prio; } /* * s->session->ciphers should now have a list of ciphers that are on * both the client and server. This list is ordered by the order the * client sent the ciphers or in the order of the server's preference * if SSL_OP_CIPHER_SERVER_PREFERENCE was set. */ } p += s->s2->tmp.cipher_spec_length; /* done cipher selection */ /* session id extracted already */ p += s->s2->tmp.session_id_length; /* challenge */ if (s->s2->challenge_length > sizeof s->s2->challenge) { ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); return -1; } memcpy(s->s2->challenge, p, (unsigned int)s->s2->challenge_length); return (1); mem_err: SSLerr(SSL_F_GET_CLIENT_HELLO, ERR_R_MALLOC_FAILURE); return (0); } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: ScopedFramebufferCopyBinder::ScopedFramebufferCopyBinder( GLES2DecoderImpl* decoder, GLint x, GLint y, GLint width, GLint height) : decoder_(decoder) { const Framebuffer::Attachment* attachment = decoder->framebuffer_state_.bound_read_framebuffer.get() ->GetReadBufferAttachment(); DCHECK(attachment); auto* api = decoder_->api(); api->glGenTexturesFn(1, &temp_texture_); ScopedTextureBinder texture_binder(&decoder->state_, decoder->error_state_.get(), temp_texture_, GL_TEXTURE_2D); if (width == 0 || height == 0) { api->glCopyTexImage2DFn(GL_TEXTURE_2D, 0, attachment->internal_format(), 0, 0, attachment->width(), attachment->height(), 0); } else { api->glCopyTexImage2DFn(GL_TEXTURE_2D, 0, attachment->internal_format(), x, y, width, height, 0); } api->glGenFramebuffersEXTFn(1, &temp_framebuffer_); framebuffer_binder_ = std::make_unique<ScopedFramebufferBinder>(decoder, temp_framebuffer_); api->glFramebufferTexture2DEXTFn(GL_READ_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, temp_texture_, 0); api->glReadBufferFn(GL_COLOR_ATTACHMENT0); } Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM This makes the query of GL_COMPLETION_STATUS_KHR to programs much cheaper by minimizing the round-trip to the GPU thread. Bug: 881152, 957001 Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630 Commit-Queue: Kenneth Russell <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Reviewed-by: Geoff Lang <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Cr-Commit-Position: refs/heads/master@{#657568} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void my_init_source_fn(j_decompress_ptr cinfo) { struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src; rctx->pub.next_input_byte = rctx->buffer; rctx->pub.bytes_in_buffer = 0; } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void update_logging() { bool should_log = module_started && (logging_enabled_via_api || stack_config->get_btsnoop_turned_on()); if (should_log == is_logging) return; is_logging = should_log; if (should_log) { btsnoop_net_open(); const char *log_path = stack_config->get_btsnoop_log_path(); if (stack_config->get_btsnoop_should_save_last()) { char last_log_path[PATH_MAX]; snprintf(last_log_path, PATH_MAX, "%s.%llu", log_path, btsnoop_timestamp()); if (!rename(log_path, last_log_path) && errno != ENOENT) LOG_ERROR("%s unable to rename '%s' to '%s': %s", __func__, log_path, last_log_path, strerror(errno)); } logfile_fd = open(log_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); if (logfile_fd == INVALID_FD) { LOG_ERROR("%s unable to open '%s': %s", __func__, log_path, strerror(errno)); is_logging = false; return; } write(logfile_fd, "btsnoop\0\0\0\0\1\0\0\x3\xea", 16); } else { if (logfile_fd != INVALID_FD) close(logfile_fd); logfile_fd = INVALID_FD; btsnoop_net_close(); } } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 1 Example 2: Code: static inline void perf_read_regs(struct pt_regs *regs) { } Commit Message: perf, powerpc: Handle events that raise an exception without overflowing Events on POWER7 can roll back if a speculative event doesn't eventually complete. Unfortunately in some rare cases they will raise a performance monitor exception. We need to catch this to ensure we reset the PMC. In all cases the PMC will be 256 or less cycles from overflow. Signed-off-by: Anton Blanchard <[email protected]> Signed-off-by: Peter Zijlstra <[email protected]> Cc: <[email protected]> # as far back as it applies cleanly LKML-Reference: <20110309143842.6c22845e@kryten> Signed-off-by: Ingo Molnar <[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: gss_verify_mic (minor_status, context_handle, message_buffer, token_buffer, qop_state) OM_uint32 * minor_status; gss_ctx_id_t context_handle; gss_buffer_t message_buffer; gss_buffer_t token_buffer; gss_qop_t * qop_state; { OM_uint32 status; gss_union_ctx_id_t ctx; gss_mechanism mech; if (minor_status == NULL) return (GSS_S_CALL_INACCESSIBLE_WRITE); *minor_status = 0; if (context_handle == GSS_C_NO_CONTEXT) return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_NO_CONTEXT); if ((message_buffer == GSS_C_NO_BUFFER) || GSS_EMPTY_BUFFER(token_buffer)) return (GSS_S_CALL_INACCESSIBLE_READ); /* * select the approprate underlying mechanism routine and * call it. */ ctx = (gss_union_ctx_id_t) context_handle; mech = gssint_get_mechanism (ctx->mech_type); if (mech) { if (mech->gss_verify_mic) { status = mech->gss_verify_mic( minor_status, ctx->internal_ctx_id, message_buffer, token_buffer, qop_state); if (status != GSS_S_COMPLETE) map_error(minor_status, mech); } else status = GSS_S_UNAVAILABLE; return(status); } return (GSS_S_BAD_MECH); } Commit Message: Preserve GSS context on init/accept failure After gss_init_sec_context() or gss_accept_sec_context() has created a context, don't delete the mechglue context on failures from subsequent calls, even if the mechanism deletes the mech-specific context (which is allowed by RFC 2744 but not preferred). Check for union contexts with no mechanism context in each GSS function which accepts a gss_ctx_id_t. CVE-2017-11462: RFC 2744 permits a GSS-API implementation to delete an existing security context on a second or subsequent call to gss_init_sec_context() or gss_accept_sec_context() if the call results in an error. This API behavior has been found to be dangerous, leading to the possibility of memory errors in some callers. For safety, GSS-API implementations should instead preserve existing security contexts on error until the caller deletes them. All versions of MIT krb5 prior to this change may delete acceptor contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through 1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on error. ticket: 8598 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-415 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static bool vmxnet_tx_pkt_parse_headers(struct VmxnetTxPkt *pkt) { struct iovec *l2_hdr, *l3_hdr; size_t bytes_read; size_t full_ip6hdr_len; uint16_t l3_proto; assert(pkt); l2_hdr = &pkt->vec[VMXNET_TX_PKT_L2HDR_FRAG]; l3_hdr = &pkt->vec[VMXNET_TX_PKT_L3HDR_FRAG]; bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base, ETH_MAX_L2_HDR_LEN); if (bytes_read < ETH_MAX_L2_HDR_LEN) { l2_hdr->iov_len = 0; return false; } else { l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base); } l3_proto = eth_get_l3_proto(l2_hdr->iov_base, l2_hdr->iov_len); l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base); pkt->l4proto = ((struct ip_header *) l3_hdr->iov_base)->ip_p; /* copy optional IPv4 header data */ bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len + sizeof(struct ip_header), l3_hdr->iov_base + sizeof(struct ip_header), l3_hdr->iov_len - sizeof(struct ip_header)); if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) { l3_hdr->iov_len = 0; return false; } break; case ETH_P_IPV6: if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, &pkt->l4proto, &full_ip6hdr_len)) { l3_hdr->iov_len = 0; return false; } l3_hdr->iov_base = g_malloc(full_ip6hdr_len); bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len, l3_hdr->iov_base, full_ip6hdr_len); if (bytes_read < full_ip6hdr_len) { l3_hdr->iov_len = 0; return false; } else { l3_hdr->iov_len = full_ip6hdr_len; } break; default: l3_hdr->iov_len = 0; break; } Commit Message: CWE ID: CWE-20 Target: 1 Example 2: Code: status_t CameraService::BasicClient::finishCameraOps() { if (mOpsActive) { mAppOpsManager.finishOp(AppOpsManager::OP_CAMERA, mClientUid, mClientPackageName); mOpsActive = false; } mAppOpsManager.stopWatchingMode(mOpsCallback); mOpsCallback.clear(); return OK; } 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 int udp_v6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; struct udp_sock *up = udp_sk(sk); struct flowi6 fl6; int err = 0; if (up->pending == AF_INET) return udp_push_pending_frames(sk); /* ip6_finish_skb will release the cork, so make a copy of * fl6 here. */ fl6 = inet_sk(sk)->cork.fl.u.ip6; skb = ip6_finish_skb(sk); if (!skb) goto out; err = udp_v6_send_skb(skb, &fl6); out: up->len = 0; up->pending = 0; return err; } Commit Message: udp: fix behavior of wrong checksums We have two problems in UDP stack related to bogus checksums : 1) We return -EAGAIN to application even if receive queue is not empty. This breaks applications using edge trigger epoll() 2) Under UDP flood, we can loop forever without yielding to other processes, potentially hanging the host, especially on non SMP. This patch is an attempt to make things better. We might in the future add extra support for rt applications wanting to better control time spent doing a recv() in a hostile environment. For example we could validate checksums before queuing packets in socket receive queue. Signed-off-by: Eric Dumazet <[email protected]> Cc: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void RTCPeerConnection::setLocalDescription(PassRefPtr<RTCSessionDescription> prpSessionDescription, PassRefPtr<VoidCallback> successCallback, PassRefPtr<RTCErrorCallback> errorCallback, ExceptionCode& ec) { if (m_readyState == ReadyStateClosing || m_readyState == ReadyStateClosed) { ec = INVALID_STATE_ERR; return; } RefPtr<RTCSessionDescription> sessionDescription = prpSessionDescription; if (!sessionDescription) { ec = TYPE_MISMATCH_ERR; return; } RefPtr<RTCVoidRequestImpl> request = RTCVoidRequestImpl::create(scriptExecutionContext(), successCallback, errorCallback); m_peerHandler->setLocalDescription(request.release(), sessionDescription->descriptor()); } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: static handle_t *ocfs2_zero_start_ordered_transaction(struct inode *inode, struct buffer_head *di_bh) { struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); handle_t *handle = NULL; int ret = 0; if (!ocfs2_should_order_data(inode)) goto out; handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS); if (IS_ERR(handle)) { ret = -ENOMEM; mlog_errno(ret); goto out; } ret = ocfs2_jbd2_file_inode(handle, inode); if (ret < 0) { mlog_errno(ret); goto out; } ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh, OCFS2_JOURNAL_ACCESS_WRITE); if (ret) mlog_errno(ret); ocfs2_update_inode_fsync_trans(handle, inode, 1); out: if (ret) { if (!IS_ERR(handle)) ocfs2_commit_trans(osb, handle); handle = ERR_PTR(ret); } return handle; } Commit Message: ocfs2: should wait dio before inode lock in ocfs2_setattr() we should wait dio requests to finish before inode lock in ocfs2_setattr(), otherwise the following deadlock will happen: process 1 process 2 process 3 truncate file 'A' end_io of writing file 'A' receiving the bast messages ocfs2_setattr ocfs2_inode_lock_tracker ocfs2_inode_lock_full inode_dio_wait __inode_dio_wait -->waiting for all dio requests finish dlm_proxy_ast_handler dlm_do_local_bast ocfs2_blocking_ast ocfs2_generic_handle_bast set OCFS2_LOCK_BLOCKED flag dio_end_io dio_bio_end_aio dio_complete ocfs2_dio_end_io ocfs2_dio_end_io_write ocfs2_inode_lock __ocfs2_cluster_lock ocfs2_wait_for_mask -->waiting for OCFS2_LOCK_BLOCKED flag to be cleared, that is waiting for 'process 1' unlocking the inode lock inode_dio_end -->here dec the i_dio_count, but will never be called, so a deadlock happened. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Alex Chen <[email protected]> Reviewed-by: Jun Piao <[email protected]> Reviewed-by: Joseph Qi <[email protected]> Acked-by: Changwei Ge <[email protected]> Cc: Mark Fasheh <[email protected]> Cc: Joel Becker <[email protected]> Cc: Junxiao Bi <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[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: Plugin::Plugin(PP_Instance pp_instance) : pp::InstancePrivate(pp_instance), scriptable_plugin_(NULL), argc_(-1), argn_(NULL), argv_(NULL), main_subprocess_("main subprocess", NULL, NULL), nacl_ready_state_(UNSENT), nexe_error_reported_(false), wrapper_factory_(NULL), last_error_string_(""), ppapi_proxy_(NULL), enable_dev_interfaces_(false), init_time_(0), ready_time_(0), nexe_size_(0), time_of_last_progress_event_(0), using_ipc_proxy_(false) { PLUGIN_PRINTF(("Plugin::Plugin (this=%p, pp_instance=%" NACL_PRId32")\n", static_cast<void*>(this), pp_instance)); callback_factory_.Initialize(this); nexe_downloader_.Initialize(this); } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob) { ASSERT(&blob->registry() == this); ThreadableBlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url()); } 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: 1 Example 2: Code: int ip_mc_validate_source(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct in_device *in_dev, u32 *itag) { int err; /* Primary sanity checks. */ if (!in_dev) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) return -EINVAL; if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev)) return -EINVAL; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr) && ip_hdr(skb)->protocol != IPPROTO_IGMP) return -EINVAL; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, itag); if (err < 0) return err; } return 0; } Commit Message: inet: switch IP ID generator to siphash According to Amit Klein and Benny Pinkas, IP ID generation is too weak and might be used by attackers. Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix()) having 64bit key and Jenkins hash is risky. It is time to switch to siphash and its 128bit keys. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Amit Klein <[email protected]> Reported-by: Benny Pinkas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool AppCacheDatabase::FindOnlineWhiteListForCache( int64_t cache_id, std::vector<OnlineWhiteListRecord>* records) { DCHECK(records && records->empty()); if (!LazyOpen(kDontCreate)) return false; static const char kSql[] = "SELECT cache_id, namespace_url, is_pattern FROM OnlineWhiteLists" " WHERE cache_id = ?"; sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql)); statement.BindInt64(0, cache_id); while (statement.Step()) { records->push_back(OnlineWhiteListRecord()); this->ReadOnlineWhiteListRecord(statement, &records->back()); DCHECK(records->back().cache_id == cache_id); } return statement.Succeeded(); } 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 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 ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); } Commit Message: CWE ID: Target: 1 Example 2: Code: static inline long check_and_migrate_cma_pages(unsigned long start, long nr_pages, unsigned int gup_flags, struct page **pages, struct vm_area_struct **vmas) { return nr_pages; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit 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: HistogramBase* Histogram::Factory::Build() { HistogramBase* histogram = StatisticsRecorder::FindHistogram(name_); if (!histogram) { const BucketRanges* created_ranges = CreateRanges(); const BucketRanges* registered_ranges = StatisticsRecorder::RegisterOrDeleteDuplicateRanges(created_ranges); if (bucket_count_ == 0) { bucket_count_ = static_cast<uint32_t>(registered_ranges->bucket_count()); minimum_ = registered_ranges->range(1); maximum_ = registered_ranges->range(bucket_count_ - 1); } PersistentHistogramAllocator::Reference histogram_ref = 0; std::unique_ptr<HistogramBase> tentative_histogram; PersistentHistogramAllocator* allocator = GlobalHistogramAllocator::Get(); if (allocator) { tentative_histogram = allocator->AllocateHistogram( histogram_type_, name_, minimum_, maximum_, registered_ranges, flags_, &histogram_ref); } if (!tentative_histogram) { DCHECK(!histogram_ref); // Should never have been set. DCHECK(!allocator); // Shouldn't have failed. flags_ &= ~HistogramBase::kIsPersistent; tentative_histogram = HeapAlloc(registered_ranges); tentative_histogram->SetFlags(flags_); } FillHistogram(tentative_histogram.get()); const void* tentative_histogram_ptr = tentative_histogram.get(); histogram = StatisticsRecorder::RegisterOrDeleteDuplicate( tentative_histogram.release()); if (histogram_ref) { allocator->FinalizeHistogram(histogram_ref, histogram == tentative_histogram_ptr); } ReportHistogramActivity(*histogram, HISTOGRAM_CREATED); } else { ReportHistogramActivity(*histogram, HISTOGRAM_LOOKUP); } DCHECK_EQ(histogram_type_, histogram->GetHistogramType()) << name_; if (bucket_count_ != 0 && !histogram->HasConstructionArguments(minimum_, maximum_, bucket_count_)) { DLOG(ERROR) << "Histogram " << name_ << " has bad construction arguments"; return nullptr; } return histogram; } Commit Message: Convert DCHECKs to CHECKs for histogram types When a histogram is looked up by name, there is currently a DCHECK that verifies the type of the stored histogram matches the expected type. A mismatch represents a significant problem because the returned HistogramBase is cast to a Histogram in ValidateRangeChecksum, potentially causing a crash. This CL converts the DCHECK to a CHECK to prevent the possibility of type confusion in release builds. BUG=651443 [email protected] Review-Url: https://codereview.chromium.org/2381893003 Cr-Commit-Position: refs/heads/master@{#421929} CWE ID: CWE-476 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void AppControllerImpl::LaunchApp(const std::string& app_id) { app_service_proxy_->Launch(app_id, ui::EventFlags::EF_NONE, apps::mojom::LaunchSource::kFromAppListGrid, display::kDefaultDisplayId); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416 Target: 1 Example 2: Code: TT_RunIns( TT_ExecContext exc ) { FT_ULong ins_counter = 0; /* executed instructions counter */ FT_ULong num_twilight_points; FT_UShort i; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY FT_Byte opcode_pattern[1][2] = { /* #8 TypeMan Talk Align */ { 0x06, /* SPVTL */ 0x7D, /* RDTG */ }, }; FT_UShort opcode_patterns = 1; FT_UShort opcode_pointer[1] = { 0 }; FT_UShort opcode_size[1] = { 1 }; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY exc->iup_called = FALSE; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_SUPPORT_SUBPIXEL_HINTING_MINIMAL /* * Toggle backward compatibility according to what font wants, except * when * * 1) we have a `tricky' font that heavily relies on the interpreter to * render glyphs correctly, for example DFKai-SB, or * 2) FT_RENDER_MODE_MONO (i.e, monochome rendering) is requested. * * In those cases, backward compatibility needs to be turned off to get * correct rendering. The rendering is then completely up to the * font's programming. * */ if ( SUBPIXEL_HINTING_MINIMAL && exc->subpixel_hinting_lean && !FT_IS_TRICKY( &exc->face->root ) ) exc->backward_compatibility = !( exc->GS.instruct_control & 4 ); else exc->backward_compatibility = FALSE; exc->iupx_called = FALSE; exc->iupy_called = FALSE; #endif /* We restrict the number of twilight points to a reasonable, */ /* heuristic value to avoid slow execution of malformed bytecode. */ num_twilight_points = FT_MAX( 30, 2 * ( exc->pts.n_points + exc->cvtSize ) ); if ( exc->twilight.n_points > num_twilight_points ) { if ( num_twilight_points > 0xFFFFU ) num_twilight_points = 0xFFFFU; FT_TRACE5(( "TT_RunIns: Resetting number of twilight points\n" " from %d to the more reasonable value %d\n", exc->twilight.n_points, num_twilight_points )); exc->twilight.n_points = (FT_UShort)num_twilight_points; } /* Set up loop detectors. We restrict the number of LOOPCALL loops */ /* and the number of JMPR, JROT, and JROF calls with a negative */ /* argument to values that depend on various parameters like the */ /* size of the CVT table or the number of points in the current */ /* glyph (if applicable). */ /* */ /* The idea is that in real-world bytecode you either iterate over */ /* all CVT entries (in the `prep' table), or over all points (or */ /* contours, in the `glyf' table) of a glyph, and such iterations */ /* don't happen very often. */ exc->loopcall_counter = 0; exc->neg_jump_counter = 0; /* The maximum values are heuristic. */ if ( exc->pts.n_points ) exc->loopcall_counter_max = FT_MAX( 50, 10 * exc->pts.n_points ) + FT_MAX( 50, exc->cvtSize / 10 ); else exc->loopcall_counter_max = 300 + 8 * exc->cvtSize; /* as a protection against an unreasonable number of CVT entries */ /* we assume at most 100 control values per glyph for the counter */ if ( exc->loopcall_counter_max > 100 * (FT_ULong)exc->face->root.num_glyphs ) exc->loopcall_counter_max = 100 * (FT_ULong)exc->face->root.num_glyphs; FT_TRACE5(( "TT_RunIns: Limiting total number of loops in LOOPCALL" " to %d\n", exc->loopcall_counter_max )); exc->neg_jump_counter_max = exc->loopcall_counter_max; FT_TRACE5(( "TT_RunIns: Limiting total number of backward jumps" " to %d\n", exc->neg_jump_counter_max )); /* set PPEM and CVT functions */ exc->tt_metrics.ratio = 0; if ( exc->metrics.x_ppem != exc->metrics.y_ppem ) { /* non-square pixels, use the stretched routines */ exc->func_cur_ppem = Current_Ppem_Stretched; exc->func_read_cvt = Read_CVT_Stretched; exc->func_write_cvt = Write_CVT_Stretched; exc->func_move_cvt = Move_CVT_Stretched; } else { /* square pixels, use normal routines */ exc->func_cur_ppem = Current_Ppem; exc->func_read_cvt = Read_CVT; exc->func_write_cvt = Write_CVT; exc->func_move_cvt = Move_CVT; } Compute_Funcs( exc ); Compute_Round( exc, (FT_Byte)exc->GS.round_state ); do { exc->opcode = exc->code[exc->IP]; #ifdef FT_DEBUG_LEVEL_TRACE { FT_Long cnt = FT_MIN( 8, exc->top ); FT_Long n; /* if tracing level is 7, show current code position */ /* and the first few stack elements also */ FT_TRACE6(( " " )); FT_TRACE7(( "%06d ", exc->IP )); FT_TRACE6(( opcode_name[exc->opcode] + 2 )); FT_TRACE7(( "%*s", *opcode_name[exc->opcode] == 'A' ? 2 : 12 - ( *opcode_name[exc->opcode] - '0' ), "#" )); for ( n = 1; n <= cnt; n++ ) FT_TRACE7(( " %d", exc->stack[exc->top - n] )); FT_TRACE6(( "\n" )); } #endif /* FT_DEBUG_LEVEL_TRACE */ if ( ( exc->length = opcode_length[exc->opcode] ) < 0 ) { if ( exc->IP + 1 >= exc->codeSize ) goto LErrorCodeOverflow_; exc->length = 2 - exc->length * exc->code[exc->IP + 1]; } if ( exc->IP + exc->length > exc->codeSize ) goto LErrorCodeOverflow_; /* First, let's check for empty stack and overflow */ exc->args = exc->top - ( Pop_Push_Count[exc->opcode] >> 4 ); /* `args' is the top of the stack once arguments have been popped. */ /* One can also interpret it as the index of the last argument. */ if ( exc->args < 0 ) { if ( exc->pedantic_hinting ) { exc->error = FT_THROW( Too_Few_Arguments ); goto LErrorLabel_; } /* push zeroes onto the stack */ for ( i = 0; i < Pop_Push_Count[exc->opcode] >> 4; i++ ) exc->stack[i] = 0; exc->args = 0; } #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT if ( exc->opcode == 0x91 ) { /* this is very special: GETVARIATION returns */ /* a variable number of arguments */ /* it is the job of the application to `activate' GX handling, */ /* this is, calling any of the GX API functions on the current */ /* font to select a variation instance */ if ( exc->face->blend ) exc->new_top = exc->args + exc->face->blend->num_axis; } else #endif exc->new_top = exc->args + ( Pop_Push_Count[exc->opcode] & 15 ); /* `new_top' is the new top of the stack, after the instruction's */ /* execution. `top' will be set to `new_top' after the `switch' */ /* statement. */ if ( exc->new_top > exc->stackSize ) { exc->error = FT_THROW( Stack_Overflow ); goto LErrorLabel_; } exc->step_ins = TRUE; exc->error = FT_Err_Ok; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY if ( SUBPIXEL_HINTING_INFINALITY ) { for ( i = 0; i < opcode_patterns; i++ ) { if ( opcode_pointer[i] < opcode_size[i] && exc->opcode == opcode_pattern[i][opcode_pointer[i]] ) { opcode_pointer[i] += 1; if ( opcode_pointer[i] == opcode_size[i] ) { FT_TRACE6(( "sph: opcode ptrn: %d, %s %s\n", i, exc->face->root.family_name, exc->face->root.style_name )); switch ( i ) { case 0: break; } opcode_pointer[i] = 0; } } else opcode_pointer[i] = 0; } } #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ { FT_Long* args = exc->stack + exc->args; FT_Byte opcode = exc->opcode; switch ( opcode ) { case 0x00: /* SVTCA y */ case 0x01: /* SVTCA x */ case 0x02: /* SPvTCA y */ case 0x03: /* SPvTCA x */ case 0x04: /* SFvTCA y */ case 0x05: /* SFvTCA x */ Ins_SxyTCA( exc ); break; case 0x06: /* SPvTL // */ case 0x07: /* SPvTL + */ Ins_SPVTL( exc, args ); break; case 0x08: /* SFvTL // */ case 0x09: /* SFvTL + */ Ins_SFVTL( exc, args ); break; case 0x0A: /* SPvFS */ Ins_SPVFS( exc, args ); break; case 0x0B: /* SFvFS */ Ins_SFVFS( exc, args ); break; case 0x0C: /* GPv */ Ins_GPV( exc, args ); break; case 0x0D: /* GFv */ Ins_GFV( exc, args ); break; case 0x0E: /* SFvTPv */ Ins_SFVTPV( exc ); break; case 0x0F: /* ISECT */ Ins_ISECT( exc, args ); break; case 0x10: /* SRP0 */ Ins_SRP0( exc, args ); break; case 0x11: /* SRP1 */ Ins_SRP1( exc, args ); break; case 0x12: /* SRP2 */ Ins_SRP2( exc, args ); break; case 0x13: /* SZP0 */ Ins_SZP0( exc, args ); break; case 0x14: /* SZP1 */ Ins_SZP1( exc, args ); break; case 0x15: /* SZP2 */ Ins_SZP2( exc, args ); break; case 0x16: /* SZPS */ Ins_SZPS( exc, args ); break; case 0x17: /* SLOOP */ Ins_SLOOP( exc, args ); break; case 0x18: /* RTG */ Ins_RTG( exc ); break; case 0x19: /* RTHG */ Ins_RTHG( exc ); break; case 0x1A: /* SMD */ Ins_SMD( exc, args ); break; case 0x1B: /* ELSE */ Ins_ELSE( exc ); break; case 0x1C: /* JMPR */ Ins_JMPR( exc, args ); break; case 0x1D: /* SCVTCI */ Ins_SCVTCI( exc, args ); break; case 0x1E: /* SSWCI */ Ins_SSWCI( exc, args ); break; case 0x1F: /* SSW */ Ins_SSW( exc, args ); break; case 0x20: /* DUP */ Ins_DUP( args ); break; case 0x21: /* POP */ Ins_POP(); break; case 0x22: /* CLEAR */ Ins_CLEAR( exc ); break; case 0x23: /* SWAP */ Ins_SWAP( args ); break; case 0x24: /* DEPTH */ Ins_DEPTH( exc, args ); break; case 0x25: /* CINDEX */ Ins_CINDEX( exc, args ); break; case 0x26: /* MINDEX */ Ins_MINDEX( exc, args ); break; case 0x27: /* ALIGNPTS */ Ins_ALIGNPTS( exc, args ); break; case 0x28: /* RAW */ Ins_UNKNOWN( exc ); break; case 0x29: /* UTP */ Ins_UTP( exc, args ); break; case 0x2A: /* LOOPCALL */ Ins_LOOPCALL( exc, args ); break; case 0x2B: /* CALL */ Ins_CALL( exc, args ); break; case 0x2C: /* FDEF */ Ins_FDEF( exc, args ); break; case 0x2D: /* ENDF */ Ins_ENDF( exc ); break; case 0x2E: /* MDAP */ case 0x2F: /* MDAP */ Ins_MDAP( exc, args ); break; case 0x30: /* IUP */ case 0x31: /* IUP */ Ins_IUP( exc ); break; case 0x32: /* SHP */ case 0x33: /* SHP */ Ins_SHP( exc ); break; case 0x34: /* SHC */ case 0x35: /* SHC */ Ins_SHC( exc, args ); break; case 0x36: /* SHZ */ case 0x37: /* SHZ */ Ins_SHZ( exc, args ); break; case 0x38: /* SHPIX */ Ins_SHPIX( exc, args ); break; case 0x39: /* IP */ Ins_IP( exc ); break; case 0x3A: /* MSIRP */ case 0x3B: /* MSIRP */ Ins_MSIRP( exc, args ); break; case 0x3C: /* AlignRP */ Ins_ALIGNRP( exc ); break; case 0x3D: /* RTDG */ Ins_RTDG( exc ); break; case 0x3E: /* MIAP */ case 0x3F: /* MIAP */ Ins_MIAP( exc, args ); break; case 0x40: /* NPUSHB */ Ins_NPUSHB( exc, args ); break; case 0x41: /* NPUSHW */ Ins_NPUSHW( exc, args ); break; case 0x42: /* WS */ Ins_WS( exc, args ); break; case 0x43: /* RS */ Ins_RS( exc, args ); break; case 0x44: /* WCVTP */ Ins_WCVTP( exc, args ); break; case 0x45: /* RCVT */ Ins_RCVT( exc, args ); break; case 0x46: /* GC */ case 0x47: /* GC */ Ins_GC( exc, args ); break; case 0x48: /* SCFS */ Ins_SCFS( exc, args ); break; case 0x49: /* MD */ case 0x4A: /* MD */ Ins_MD( exc, args ); break; case 0x4B: /* MPPEM */ Ins_MPPEM( exc, args ); break; case 0x4C: /* MPS */ Ins_MPS( exc, args ); break; case 0x4D: /* FLIPON */ Ins_FLIPON( exc ); break; case 0x4E: /* FLIPOFF */ Ins_FLIPOFF( exc ); break; case 0x4F: /* DEBUG */ Ins_DEBUG( exc ); break; case 0x50: /* LT */ Ins_LT( args ); break; case 0x51: /* LTEQ */ Ins_LTEQ( args ); break; case 0x52: /* GT */ Ins_GT( args ); break; case 0x53: /* GTEQ */ Ins_GTEQ( args ); break; case 0x54: /* EQ */ Ins_EQ( args ); break; case 0x55: /* NEQ */ Ins_NEQ( args ); break; case 0x56: /* ODD */ Ins_ODD( exc, args ); break; case 0x57: /* EVEN */ Ins_EVEN( exc, args ); break; case 0x58: /* IF */ Ins_IF( exc, args ); break; case 0x59: /* EIF */ Ins_EIF(); break; case 0x5A: /* AND */ Ins_AND( args ); break; case 0x5B: /* OR */ Ins_OR( args ); break; case 0x5C: /* NOT */ Ins_NOT( args ); break; case 0x5D: /* DELTAP1 */ Ins_DELTAP( exc, args ); break; case 0x5E: /* SDB */ Ins_SDB( exc, args ); break; case 0x5F: /* SDS */ Ins_SDS( exc, args ); break; case 0x60: /* ADD */ Ins_ADD( args ); break; case 0x61: /* SUB */ Ins_SUB( args ); break; case 0x62: /* DIV */ Ins_DIV( exc, args ); break; case 0x63: /* MUL */ Ins_MUL( args ); break; case 0x64: /* ABS */ Ins_ABS( args ); break; case 0x65: /* NEG */ Ins_NEG( args ); break; case 0x66: /* FLOOR */ Ins_FLOOR( args ); break; case 0x67: /* CEILING */ Ins_CEILING( args ); break; case 0x68: /* ROUND */ case 0x69: /* ROUND */ case 0x6A: /* ROUND */ case 0x6B: /* ROUND */ Ins_ROUND( exc, args ); break; case 0x6C: /* NROUND */ case 0x6D: /* NROUND */ case 0x6E: /* NRRUND */ case 0x6F: /* NROUND */ Ins_NROUND( exc, args ); break; case 0x70: /* WCVTF */ Ins_WCVTF( exc, args ); break; case 0x71: /* DELTAP2 */ case 0x72: /* DELTAP3 */ Ins_DELTAP( exc, args ); break; case 0x73: /* DELTAC0 */ case 0x74: /* DELTAC1 */ case 0x75: /* DELTAC2 */ Ins_DELTAC( exc, args ); break; case 0x76: /* SROUND */ Ins_SROUND( exc, args ); break; case 0x77: /* S45Round */ Ins_S45ROUND( exc, args ); break; case 0x78: /* JROT */ Ins_JROT( exc, args ); break; case 0x79: /* JROF */ Ins_JROF( exc, args ); break; case 0x7A: /* ROFF */ Ins_ROFF( exc ); break; case 0x7B: /* ???? */ Ins_UNKNOWN( exc ); break; case 0x7C: /* RUTG */ Ins_RUTG( exc ); break; case 0x7D: /* RDTG */ Ins_RDTG( exc ); break; case 0x7E: /* SANGW */ Ins_SANGW(); break; case 0x7F: /* AA */ Ins_AA(); break; case 0x80: /* FLIPPT */ Ins_FLIPPT( exc ); break; case 0x81: /* FLIPRGON */ Ins_FLIPRGON( exc, args ); break; case 0x82: /* FLIPRGOFF */ Ins_FLIPRGOFF( exc, args ); break; case 0x83: /* UNKNOWN */ case 0x84: /* UNKNOWN */ Ins_UNKNOWN( exc ); break; case 0x85: /* SCANCTRL */ Ins_SCANCTRL( exc, args ); break; case 0x86: /* SDPvTL */ case 0x87: /* SDPvTL */ Ins_SDPVTL( exc, args ); break; case 0x88: /* GETINFO */ Ins_GETINFO( exc, args ); break; case 0x89: /* IDEF */ Ins_IDEF( exc, args ); break; case 0x8A: /* ROLL */ Ins_ROLL( args ); break; case 0x8B: /* MAX */ Ins_MAX( args ); break; case 0x8C: /* MIN */ Ins_MIN( args ); break; case 0x8D: /* SCANTYPE */ Ins_SCANTYPE( exc, args ); break; case 0x8E: /* INSTCTRL */ Ins_INSTCTRL( exc, args ); break; case 0x8F: /* ADJUST */ case 0x90: /* ADJUST */ Ins_UNKNOWN( exc ); break; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT case 0x91: /* it is the job of the application to `activate' GX handling, */ /* this is, calling any of the GX API functions on the current */ /* font to select a variation instance */ if ( exc->face->blend ) Ins_GETVARIATION( exc, args ); else Ins_UNKNOWN( exc ); break; case 0x92: /* there is at least one MS font (LaoUI.ttf version 5.01) that */ /* uses IDEFs for 0x91 and 0x92; for this reason we activate */ /* GETDATA for GX fonts only, similar to GETVARIATION */ if ( exc->face->blend ) Ins_GETDATA( args ); else Ins_UNKNOWN( exc ); break; #endif default: if ( opcode >= 0xE0 ) Ins_MIRP( exc, args ); else if ( opcode >= 0xC0 ) Ins_MDRP( exc, args ); else if ( opcode >= 0xB8 ) Ins_PUSHW( exc, args ); else if ( opcode >= 0xB0 ) Ins_PUSHB( exc, args ); else Ins_UNKNOWN( exc ); } } if ( exc->error ) { switch ( exc->error ) { /* looking for redefined instructions */ case FT_ERR( Invalid_Opcode ): { TT_DefRecord* def = exc->IDefs; TT_DefRecord* limit = def + exc->numIDefs; for ( ; def < limit; def++ ) { if ( def->active && exc->opcode == (FT_Byte)def->opc ) { TT_CallRec* callrec; if ( exc->callTop >= exc->callSize ) { exc->error = FT_THROW( Invalid_Reference ); goto LErrorLabel_; } callrec = &exc->callStack[exc->callTop]; callrec->Caller_Range = exc->curRange; callrec->Caller_IP = exc->IP + 1; callrec->Cur_Count = 1; callrec->Def = def; if ( Ins_Goto_CodeRange( exc, def->range, def->start ) == FAILURE ) goto LErrorLabel_; goto LSuiteLabel_; } } } exc->error = FT_THROW( Invalid_Opcode ); goto LErrorLabel_; #if 0 break; /* Unreachable code warning suppression. */ /* Leave to remind in case a later change the editor */ /* to consider break; */ #endif default: goto LErrorLabel_; #if 0 break; #endif } } exc->top = exc->new_top; if ( exc->step_ins ) exc->IP += exc->length; /* increment instruction counter and check if we didn't */ /* run this program for too long (e.g. infinite loops). */ if ( ++ins_counter > TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES ) return FT_THROW( Execution_Too_Long ); LSuiteLabel_: if ( exc->IP >= exc->codeSize ) { if ( exc->callTop > 0 ) { exc->error = FT_THROW( Code_Overflow ); goto LErrorLabel_; } else goto LNo_Error_; } } while ( !exc->instruction_trap ); LNo_Error_: FT_TRACE4(( " %d instruction%s executed\n", ins_counter == 1 ? "" : "s", ins_counter )); return FT_Err_Ok; LErrorCodeOverflow_: exc->error = FT_THROW( Code_Overflow ); LErrorLabel_: if ( exc->error && !exc->instruction_trap ) FT_TRACE1(( " The interpreter returned error 0x%x\n", exc->error )); return exc->error; } Commit Message: CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void OfflinePageModelImpl::OnInitialGetOfflinePagesDone( const base::TimeTicks& start_time, std::vector<OfflinePageItem> offline_pages) { DCHECK(!is_loaded_); UMA_HISTOGRAM_TIMES("OfflinePages.Model.ConstructionToLoadedEventTime", base::TimeTicks::Now() - start_time); CacheLoadedData(offline_pages); FinalizeModelLoad(); CheckMetadataConsistency(); } Commit Message: Add the method to check if offline archive is in internal dir Bug: 758690 Change-Id: I8bb4283fc40a87fa7a87df2c7e513e2e16903290 Reviewed-on: https://chromium-review.googlesource.com/828049 Reviewed-by: Filip Gorski <[email protected]> Commit-Queue: Jian Li <[email protected]> Cr-Commit-Position: refs/heads/master@{#524232} CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) { OPCODE_DESC *opcode_desc; ut16 ins = (buf[1] << 8) | buf[0]; int fail; char *t; memset (op, 0, sizeof (RAnalOp)); op->ptr = UT64_MAX; op->val = UT64_MAX; op->jump = UT64_MAX; r_strbuf_init (&op->esil); for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) { if ((ins & opcode_desc->mask) == opcode_desc->selector) { fail = 0; op->cycles = opcode_desc->cycles; op->size = opcode_desc->size; op->type = opcode_desc->type; op->jump = UT64_MAX; op->fail = UT64_MAX; op->addr = addr; r_strbuf_setf (&op->esil, ""); opcode_desc->handler (anal, op, buf, len, &fail, cpu); if (fail) { goto INVALID_OP; } if (op->cycles <= 0) { opcode_desc->cycles = 2; } op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK); t = r_strbuf_get (&op->esil); if (t && strlen (t) > 1) { t += strlen (t) - 1; if (*t == ',') { *t = '\0'; } } return opcode_desc; } } if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) { goto INVALID_OP; } INVALID_OP: op->family = R_ANAL_OP_FAMILY_UNKNOWN; op->type = R_ANAL_OP_TYPE_UNK; op->addr = addr; op->fail = UT64_MAX; op->jump = UT64_MAX; op->ptr = UT64_MAX; op->val = UT64_MAX; op->nopcode = 1; op->cycles = 1; op->size = 2; r_strbuf_set (&op->esil, "1,$"); return NULL; } Commit Message: Fix oobread in avr CWE ID: CWE-125 Target: 1 Example 2: Code: static int RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) { r->dmp1 = dmp1; r->dmq1 = dmq1; r->iqmp = iqmp; return 1; } Commit Message: CWE ID: CWE-754 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: pkinit_create_sequence_of_principal_identifiers( krb5_context context, pkinit_plg_crypto_context plg_cryptoctx, pkinit_req_crypto_context req_cryptoctx, pkinit_identity_crypto_context id_cryptoctx, int type, krb5_pa_data ***e_data_out) { krb5_error_code retval = KRB5KRB_ERR_GENERIC; krb5_external_principal_identifier **krb5_trusted_certifiers = NULL; krb5_data *td_certifiers = NULL; krb5_pa_data **pa_data = NULL; switch(type) { case TD_TRUSTED_CERTIFIERS: retval = create_krb5_trustedCertifiers(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers); if (retval) { pkiDebug("create_krb5_trustedCertifiers failed\n"); goto cleanup; } break; case TD_INVALID_CERTIFICATES: retval = create_krb5_invalidCertificates(context, plg_cryptoctx, req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers); if (retval) { pkiDebug("create_krb5_invalidCertificates failed\n"); goto cleanup; } break; default: retval = -1; goto cleanup; } retval = k5int_encode_krb5_td_trusted_certifiers((const krb5_external_principal_identifier **)krb5_trusted_certifiers, &td_certifiers); if (retval) { pkiDebug("encode_krb5_td_trusted_certifiers failed\n"); goto cleanup; } #ifdef DEBUG_ASN1 print_buffer_bin((unsigned char *)td_certifiers->data, td_certifiers->length, "/tmp/kdc_td_certifiers"); #endif pa_data = malloc(2 * sizeof(krb5_pa_data *)); if (pa_data == NULL) { retval = ENOMEM; goto cleanup; } pa_data[1] = NULL; pa_data[0] = malloc(sizeof(krb5_pa_data)); if (pa_data[0] == NULL) { free(pa_data); retval = ENOMEM; goto cleanup; } pa_data[0]->pa_type = type; pa_data[0]->length = td_certifiers->length; pa_data[0]->contents = (krb5_octet *)td_certifiers->data; *e_data_out = pa_data; retval = 0; cleanup: if (krb5_trusted_certifiers != NULL) free_krb5_external_principal_identifier(&krb5_trusted_certifiers); free(td_certifiers); return retval; } Commit Message: PKINIT null pointer deref [CVE-2013-1415] Don't dereference a null pointer when cleaning up. The KDC plugin for PKINIT can dereference a null pointer when a malformed packet causes processing to terminate early, leading to a crash of the KDC process. An attacker would need to have a valid PKINIT certificate or have observed a successful PKINIT authentication, or an unauthenticated attacker could execute the attack if anonymous PKINIT is enabled. CVSSv2 vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:P/RL:O/RC:C This is a minimal commit for pullup; style fixes in a followup. [[email protected]: reformat and edit commit message] (cherry picked from commit c773d3c775e9b2d88bcdff5f8a8ba88d7ec4e8ed) ticket: 7570 version_fixed: 1.11.1 status: resolved 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: WebRTCSessionDescriptionDescriptor MockWebRTCPeerConnectionHandler::localDescription() { return m_localDescription; } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: static void _gd_error_ex(int priority, const char *format, va_list args) { if (gd_error_method) { gd_error_method(priority, format, args); } } Commit Message: Fix #340: System frozen gdImageCreate() doesn't check for oversized images and as such is prone to DoS vulnerabilities. We fix that by applying the same overflow check that is already in place for gdImageCreateTrueColor(). CVE-2016-9317 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 ext4_destroy_lazyinit_thread(void) { /* * If thread exited earlier * there's nothing to be done. */ if (!ext4_li_info || !ext4_lazyinit_task) return; kthread_stop(ext4_lazyinit_task); } 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: static int do_ip_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_sock *inet = inet_sk(sk); int val; int len; if (level != SOL_IP) return -EOPNOTSUPP; if (ip_mroute_opt(optname)) return ip_mroute_getsockopt(sk, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; lock_sock(sk); switch (optname) { case IP_OPTIONS: { unsigned char optbuf[sizeof(struct ip_options)+40]; struct ip_options * opt = (struct ip_options *)optbuf; opt->optlen = 0; if (inet->opt) memcpy(optbuf, inet->opt, sizeof(struct ip_options)+ inet->opt->optlen); release_sock(sk); if (opt->optlen == 0) return put_user(0, optlen); ip_options_undo(opt); len = min_t(unsigned int, len, opt->optlen); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, opt->__data, len)) return -EFAULT; return 0; } case IP_PKTINFO: val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0; break; case IP_RECVTTL: val = (inet->cmsg_flags & IP_CMSG_TTL) != 0; break; case IP_RECVTOS: val = (inet->cmsg_flags & IP_CMSG_TOS) != 0; break; case IP_RECVOPTS: val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0; break; case IP_RETOPTS: val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0; break; case IP_PASSSEC: val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0; break; case IP_RECVORIGDSTADDR: val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0; break; case IP_TOS: val = inet->tos; break; case IP_TTL: val = (inet->uc_ttl == -1 ? sysctl_ip_default_ttl : inet->uc_ttl); break; case IP_HDRINCL: val = inet->hdrincl; break; case IP_NODEFRAG: val = inet->nodefrag; break; case IP_MTU_DISCOVER: val = inet->pmtudisc; break; case IP_MTU: { struct dst_entry *dst; val = 0; dst = sk_dst_get(sk); if (dst) { val = dst_mtu(dst); dst_release(dst); } if (!val) { release_sock(sk); return -ENOTCONN; } break; } case IP_RECVERR: val = inet->recverr; break; case IP_MULTICAST_TTL: val = inet->mc_ttl; break; case IP_MULTICAST_LOOP: val = inet->mc_loop; break; case IP_MULTICAST_IF: { struct in_addr addr; len = min_t(unsigned int, len, sizeof(struct in_addr)); addr.s_addr = inet->mc_addr; release_sock(sk); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &addr, len)) return -EFAULT; return 0; } case IP_MSFILTER: { struct ip_msfilter msf; int err; if (len < IP_MSFILTER_SIZE(0)) { release_sock(sk); return -EINVAL; } if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) { release_sock(sk); return -EFAULT; } err = ip_mc_msfget(sk, &msf, (struct ip_msfilter __user *)optval, optlen); release_sock(sk); return err; } case MCAST_MSFILTER: { struct group_filter gsf; int err; if (len < GROUP_FILTER_SIZE(0)) { release_sock(sk); return -EINVAL; } if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) { release_sock(sk); return -EFAULT; } err = ip_mc_gsfget(sk, &gsf, (struct group_filter __user *)optval, optlen); release_sock(sk); return err; } case IP_MULTICAST_ALL: val = inet->mc_all; break; case IP_PKTOPTIONS: { struct msghdr msg; release_sock(sk); if (sk->sk_type != SOCK_STREAM) return -ENOPROTOOPT; msg.msg_control = optval; msg.msg_controllen = len; msg.msg_flags = 0; if (inet->cmsg_flags & IP_CMSG_PKTINFO) { struct in_pktinfo info; info.ipi_addr.s_addr = inet->inet_rcv_saddr; info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr; info.ipi_ifindex = inet->mc_index; put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info); } if (inet->cmsg_flags & IP_CMSG_TTL) { int hlim = inet->mc_ttl; put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim); } len -= msg.msg_controllen; return put_user(len, optlen); } case IP_FREEBIND: val = inet->freebind; break; case IP_TRANSPARENT: val = inet->transparent; break; case IP_MINTTL: val = inet->min_ttl; break; default: release_sock(sk); return -ENOPROTOOPT; } release_sock(sk); if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) { unsigned char ucval = (unsigned char)val; len = 1; if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &ucval, 1)) return -EFAULT; } else { len = min_t(unsigned int, sizeof(int), len); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; } return 0; } 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: void ConfirmEmailDialogDelegate::OnLinkClicked( WindowOpenDisposition disposition) { content::OpenURLParams params( GURL(chrome::kChromeSyncMergeTroubleshootingURL), content::Referrer(), NEW_POPUP, content::PAGE_TRANSITION_AUTO_TOPLEVEL, false); web_contents_->OpenURL(params); } Commit Message: During redirects in the one click sign in flow, check the current URL instead of original URL to validate gaia http headers. BUG=307159 Review URL: https://codereview.chromium.org/77343002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@236563 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: stub_charset () { locale = get_locale_var ("LC_CTYPE"); locale = get_locale_var ("LC_CTYPE"); if (locale == 0 || *locale == 0) return "ASCII"; s = strrchr (locale, '.'); if (s) { t = strchr (s, '@'); if (t) *t = 0; return ++s; } else if (STREQ (locale, "UTF-8")) return "UTF-8"; else return "ASCII"; } 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: void SoftMPEG2::setDecodeArgs( ivd_video_decode_ip_t *ps_dec_ip, ivd_video_decode_op_t *ps_dec_op, OMX_BUFFERHEADERTYPE *inHeader, OMX_BUFFERHEADERTYPE *outHeader, size_t timeStampIx) { size_t sizeY = outputBufferWidth() * outputBufferHeight(); size_t sizeUV; uint8_t *pBuf; ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); ps_dec_ip->e_cmd = IVD_CMD_VIDEO_DECODE; /* When in flush and after EOS with zero byte input, * inHeader is set to zero. Hence check for non-null */ if (inHeader) { ps_dec_ip->u4_ts = timeStampIx; ps_dec_ip->pv_stream_buffer = inHeader->pBuffer + inHeader->nOffset; ps_dec_ip->u4_num_Bytes = inHeader->nFilledLen; } else { ps_dec_ip->u4_ts = 0; ps_dec_ip->pv_stream_buffer = NULL; ps_dec_ip->u4_num_Bytes = 0; } if (outHeader) { pBuf = outHeader->pBuffer; } else { pBuf = mFlushOutBuffer; } sizeUV = sizeY / 4; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; ps_dec_ip->s_out_buffer.u4_num_bufs = 3; return; } Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec Bug: 27833616 Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738 (cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d) CWE ID: CWE-20 Target: 1 Example 2: Code: LONG GetEntryWidth(HWND hDropDown, const char *entry) { HDC hDC; HFONT hFont, hDefFont = NULL; SIZE size; hDC = GetDC(hDropDown); hFont = (HFONT)SendMessage(hDropDown, WM_GETFONT, 0, 0); if (hFont != NULL) hDefFont = (HFONT)SelectObject(hDC, hFont); if (!GetTextExtentPointU(hDC, entry, &size)) size.cx = 0; if (hFont != NULL) SelectObject(hDC, hDefFont); if (hDC != NULL) ReleaseDC(hDropDown, hDC); return size.cx; } Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768 * This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as it is described per its revision 11, which is the latest revision at the time of this commit, by disabling Windows prompts, enacted during signature validation, that allow the user to bypass the intended signature verification checks. * It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed certificate"), which relies on the end-user actively ignoring a Windows prompt that tells them that the update failed the signature validation whilst also advising against running it, is being fully addressed, even as the update protocol remains HTTP. * It also need to be pointed out that the extended delay (48 hours) between the time the vulnerability was reported and the moment it is fixed in our codebase has to do with the fact that the reporter chose to deviate from standard security practices by not disclosing the details of the vulnerability with us, be it publicly or privately, before creating the cert.org report. The only advance notification we received was a generic note about the use of HTTP vs HTTPS, which, as have established, is not immediately relevant to addressing the reported vulnerability. * Closes #1009 * Note: The other vulnerability scenario described towards the end of #1009, which doesn't have to do with the "lack of CA checking", will be addressed separately. CWE ID: CWE-494 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 BluetoothDeviceChromeOS::RequestPasskey( const dbus::ObjectPath& device_path, const PasskeyCallback& callback) { DCHECK(agent_.get()); DCHECK(device_path == object_path_); VLOG(1) << object_path_.value() << ": RequestPasskey"; UMA_HISTOGRAM_ENUMERATION("Bluetooth.PairingMethod", UMA_PAIRING_METHOD_REQUEST_PASSKEY, UMA_PAIRING_METHOD_COUNT); DCHECK(pairing_delegate_); DCHECK(passkey_callback_.is_null()); passkey_callback_ = callback; pairing_delegate_->RequestPasskey(this); pairing_delegate_used_ = true; } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: 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: explicit CancelAndIgnoreNavigationForPluginFrameThrottle( NavigationHandle* handle) : NavigationThrottle(handle) {} Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper This CL is for the most part a mechanical change which extracts almost all the frame-based MimeHandlerView code out of ExtensionsGuestViewMessageFilter. This change both removes the current clutter form EGVMF as well as fixesa race introduced when the frame-based logic was added to EGVMF. The reason for the race was that EGVMF is destroyed on IO thread but all the access to it (for frame-based MHV) are from UI. [email protected],[email protected] Bug: 659750, 896679, 911161, 918861 Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda Reviewed-on: https://chromium-review.googlesource.com/c/1401451 Commit-Queue: Ehsan Karamad <[email protected]> Reviewed-by: James MacLean <[email protected]> Reviewed-by: Ehsan Karamad <[email protected]> Cr-Commit-Position: refs/heads/master@{#621155} CWE ID: CWE-362 Target: 1 Example 2: Code: ExtensionDevToolsClientHost::ExtensionDevToolsClientHost( WebContents* web_contents, const std::string& extension_id, const std::string& extension_name, int tab_id) : web_contents_(web_contents), extension_id_(extension_id), tab_id_(tab_id), last_request_id_(0), infobar_delegate_(NULL) { AttachedClientHosts::GetInstance()->Add(this); Profile* profile = Profile::FromBrowserContext(web_contents_->GetBrowserContext()); registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile)); DevToolsAgentHost* agent = DevToolsAgentHostRegistry::GetDevToolsAgentHost( web_contents_->GetRenderViewHost()); DevToolsManager::GetInstance()->RegisterDevToolsClientHostFor(agent, this); TabContentsWrapper* wrapper = TabContentsWrapper::GetCurrentWrapperForContents(web_contents_); infobar_delegate_ = new ExtensionDevToolsInfoBarDelegate( wrapper->infobar_tab_helper(), extension_name, this); wrapper->infobar_tab_helper()->AddInfoBar(infobar_delegate_); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool WebGLRenderingContextBase::ValidateImageBitmap( const char* function_name, ImageBitmap* bitmap, ExceptionState& exception_state) { if (bitmap->IsNeutered()) { SynthesizeGLError(GL_INVALID_VALUE, function_name, "The source data has been detached."); return false; } if (!bitmap->OriginClean()) { exception_state.ThrowSecurityError( "The ImageBitmap contains cross-origin data, and may not be loaded."); return false; } return true; } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int nf_ct_frag6_gather(struct net *net, struct sk_buff *skb, u32 user) { struct net_device *dev = skb->dev; int fhoff, nhoff, ret; struct frag_hdr *fhdr; struct frag_queue *fq; struct ipv6hdr *hdr; u8 prevhdr; /* Jumbo payload inhibits frag. header */ if (ipv6_hdr(skb)->payload_len == 0) { pr_debug("payload len = 0\n"); return -EINVAL; } if (find_prev_fhdr(skb, &prevhdr, &nhoff, &fhoff) < 0) return -EINVAL; if (!pskb_may_pull(skb, fhoff + sizeof(*fhdr))) return -ENOMEM; skb_set_transport_header(skb, fhoff); hdr = ipv6_hdr(skb); fhdr = (struct frag_hdr *)skb_transport_header(skb); fq = fq_find(net, fhdr->identification, user, &hdr->saddr, &hdr->daddr, skb->dev ? skb->dev->ifindex : 0, ip6_frag_ecn(hdr)); if (fq == NULL) { pr_debug("Can't find and can't create new queue\n"); return -ENOMEM; } spin_lock_bh(&fq->q.lock); if (nf_ct_frag6_queue(fq, skb, fhdr, nhoff) < 0) { ret = -EINVAL; goto out_unlock; } /* after queue has assumed skb ownership, only 0 or -EINPROGRESS * must be returned. */ ret = -EINPROGRESS; if (fq->q.flags == (INET_FRAG_FIRST_IN | INET_FRAG_LAST_IN) && fq->q.meat == fq->q.len && nf_ct_frag6_reasm(fq, skb, dev)) ret = 0; out_unlock: spin_unlock_bh(&fq->q.lock); inet_frag_put(&fq->q, &nf_frags); return ret; } Commit Message: netfilter: ipv6: nf_defrag: drop mangled skb on ream error Dmitry Vyukov reported GPF in network stack that Andrey traced down to negative nh offset in nf_ct_frag6_queue(). Problem is that all network headers before fragment header are pulled. Normal ipv6 reassembly will drop the skb when errors occur further down the line. netfilter doesn't do this, and instead passed the original fragment along. That was also fine back when netfilter ipv6 defrag worked with cloned fragments, as the original, pristine fragment was passed on. So we either have to undo the pull op, or discard such fragments. Since they're malformed after all (e.g. overlapping fragment) it seems preferrable to just drop them. Same for temporary errors -- it doesn't make sense to accept (and perhaps forward!) only some fragments of same datagram. Fixes: 029f7f3b8701cc7ac ("netfilter: ipv6: nf_defrag: avoid/free clone operations") Reported-by: Dmitry Vyukov <[email protected]> Debugged-by: Andrey Konovalov <[email protected]> Diagnosed-by: Eric Dumazet <Eric Dumazet <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-787 Target: 1 Example 2: Code: static double KapurThreshold(const Image *image,const double *histogram, ExceptionInfo *exception) { #define MaxIntensity 255 double *black_entropy, *cumulative_histogram, entropy, epsilon, maximum_entropy, *white_entropy; register ssize_t i, j; size_t threshold; /* Compute optimal threshold from the entopy of the histogram. */ cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*cumulative_histogram)); black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*black_entropy)); white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL, sizeof(*white_entropy)); if ((cumulative_histogram == (double *) NULL) || (black_entropy == (double *) NULL) || (white_entropy == (double *) NULL)) { if (white_entropy != (double *) NULL) white_entropy=(double *) RelinquishMagickMemory(white_entropy); if (black_entropy != (double *) NULL) black_entropy=(double *) RelinquishMagickMemory(black_entropy); if (cumulative_histogram != (double *) NULL) cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(-1.0); } /* Entropy for black and white parts of the histogram. */ cumulative_histogram[0]=histogram[0]; for (i=1; i <= MaxIntensity; i++) cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i]; epsilon=MagickMinimumValue; for (j=0; j <= MaxIntensity; j++) { /* Black entropy. */ black_entropy[j]=0.0; if (cumulative_histogram[j] > epsilon) { entropy=0.0; for (i=0; i <= j; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/cumulative_histogram[j]* log(histogram[i]/cumulative_histogram[j]); black_entropy[j]=entropy; } /* White entropy. */ white_entropy[j]=0.0; if ((1.0-cumulative_histogram[j]) > epsilon) { entropy=0.0; for (i=j+1; i <= MaxIntensity; i++) if (histogram[i] > epsilon) entropy-=histogram[i]/(1.0-cumulative_histogram[j])* log(histogram[i]/(1.0-cumulative_histogram[j])); white_entropy[j]=entropy; } } /* Find histogram bin with maximum entropy. */ maximum_entropy=black_entropy[0]+white_entropy[0]; threshold=0; for (j=1; j <= MaxIntensity; j++) if ((black_entropy[j]+white_entropy[j]) > maximum_entropy) { maximum_entropy=black_entropy[j]+white_entropy[j]; threshold=(size_t) j; } /* Free resources. */ white_entropy=(double *) RelinquishMagickMemory(white_entropy); black_entropy=(double *) RelinquishMagickMemory(black_entropy); cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram); return(100.0*threshold/MaxIntensity); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1609 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: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; } Commit Message: (for 4.9.3) LMP: Add some missing bounds checks In lmp_print_data_link_subobjs(), these problems were identified through code review. Moreover: Add and use tstr[]. Update two tests outputs accordingly. CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void Sp_search(js_State *J) { js_Regexp *re; const char *text; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!js_regexec(re->prog, text, &m, 0)) js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp)); else js_pushnumber(J, -1); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400 Target: 1 Example 2: Code: void ipv6_push_frag_opts(struct sk_buff *skb, struct ipv6_txoptions *opt, u8 *proto) { if (opt->dst1opt) ipv6_push_exthdr(skb, proto, NEXTHDR_DEST, opt->dst1opt); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void RenderFrameImpl::didFailLoad(blink::WebLocalFrame* frame, const blink::WebURLError& error, blink::WebHistoryCommitType commit_type) { TRACE_EVENT1("navigation", "RenderFrameImpl::didFailLoad", "id", routing_id_); DCHECK(!frame_ || frame_ == frame); WebDataSource* ds = frame->dataSource(); DCHECK(ds); FOR_EACH_OBSERVER(RenderViewObserver, render_view_->observers(), DidFailLoad(frame, error)); const WebURLRequest& failed_request = ds->request(); base::string16 error_description; GetContentClient()->renderer()->GetNavigationErrorStrings( render_view_.get(), frame, failed_request, error, NULL, &error_description); Send(new FrameHostMsg_DidFailLoadWithError(routing_id_, failed_request.url(), error.reason, error_description, error.wasIgnoredByHandler)); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static RList *r_bin_wasm_get_global_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmGlobalEntry *ptr = NULL; int buflen = bin->buf->length; if (sec->payload_data + 32 > buflen) { return NULL; } if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmGlobalEntry))) { return ret; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, (ut8*)&ptr->content_type, &i))) { goto beach; } if (len + 8 > buflen || !(consume_u8 (buf + i, buf + len, &ptr->mutability, &i))) { goto beach; } if (len + 8 > buflen || !(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } r_list_append (ret, ptr); r++; } return ret; beach: free (ptr); return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125 Target: 1 Example 2: Code: void shmem_unlock_mapping(struct address_space *mapping) { } Commit Message: tmpfs: fix use-after-free of mempolicy object The tmpfs remount logic preserves filesystem mempolicy if the mpol=M option is not specified in the remount request. A new policy can be specified if mpol=M is given. Before this patch remounting an mpol bound tmpfs without specifying mpol= mount option in the remount request would set the filesystem's mempolicy object to a freed mempolicy object. To reproduce the problem boot a DEBUG_PAGEALLOC kernel and run: # mkdir /tmp/x # mount -t tmpfs -o size=100M,mpol=interleave nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=102400k,mpol=interleave:0-3 0 0 # mount -o remount,size=200M nodev /tmp/x # grep /tmp/x /proc/mounts nodev /tmp/x tmpfs rw,relatime,size=204800k,mpol=??? 0 0 # note ? garbage in mpol=... output above # dd if=/dev/zero of=/tmp/x/f count=1 # panic here Panic: BUG: unable to handle kernel NULL pointer dereference at (null) IP: [< (null)>] (null) [...] Oops: 0010 [#1] SMP DEBUG_PAGEALLOC Call Trace: mpol_shared_policy_init+0xa5/0x160 shmem_get_inode+0x209/0x270 shmem_mknod+0x3e/0xf0 shmem_create+0x18/0x20 vfs_create+0xb5/0x130 do_last+0x9a1/0xea0 path_openat+0xb3/0x4d0 do_filp_open+0x42/0xa0 do_sys_open+0xfe/0x1e0 compat_sys_open+0x1b/0x20 cstar_dispatch+0x7/0x1f Non-debug kernels will not crash immediately because referencing the dangling mpol will not cause a fault. Instead the filesystem will reference a freed mempolicy object, which will cause unpredictable behavior. The problem boils down to a dropped mpol reference below if shmem_parse_options() does not allocate a new mpol: config = *sbinfo shmem_parse_options(data, &config, true) mpol_put(sbinfo->mpol) sbinfo->mpol = config.mpol /* BUG: saves unreferenced mpol */ This patch avoids the crash by not releasing the mempolicy if shmem_parse_options() doesn't create a new mpol. How far back does this issue go? I see it in both 2.6.36 and 3.3. I did not look back further. Signed-off-by: Greg Thelen <[email protected]> Acked-by: Hugh Dickins <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RTCSessionDescriptionRequestSuccededTask(MockWebRTCPeerConnectionHandler* object, const WebKit::WebRTCSessionDescriptionRequest& request, const WebKit::WebRTCSessionDescriptionDescriptor& result) : MethodTask<MockWebRTCPeerConnectionHandler>(object) , m_request(request) , m_result(result) { } Commit Message: Unreviewed, rolling out r127612, r127660, and r127664. http://trac.webkit.org/changeset/127612 http://trac.webkit.org/changeset/127660 http://trac.webkit.org/changeset/127664 https://bugs.webkit.org/show_bug.cgi?id=95920 Source/Platform: * Platform.gypi: * chromium/public/WebRTCPeerConnectionHandler.h: (WebKit): (WebRTCPeerConnectionHandler): * chromium/public/WebRTCVoidRequest.h: Removed. Source/WebCore: * CMakeLists.txt: * GNUmakefile.list.am: * Modules/mediastream/RTCErrorCallback.h: (WebCore): (RTCErrorCallback): * Modules/mediastream/RTCErrorCallback.idl: * Modules/mediastream/RTCPeerConnection.cpp: (WebCore::RTCPeerConnection::createOffer): * Modules/mediastream/RTCPeerConnection.h: (WebCore): (RTCPeerConnection): * Modules/mediastream/RTCPeerConnection.idl: * Modules/mediastream/RTCSessionDescriptionCallback.h: (WebCore): (RTCSessionDescriptionCallback): * Modules/mediastream/RTCSessionDescriptionCallback.idl: * Modules/mediastream/RTCSessionDescriptionRequestImpl.cpp: (WebCore::RTCSessionDescriptionRequestImpl::create): (WebCore::RTCSessionDescriptionRequestImpl::RTCSessionDescriptionRequestImpl): (WebCore::RTCSessionDescriptionRequestImpl::requestSucceeded): (WebCore::RTCSessionDescriptionRequestImpl::requestFailed): (WebCore::RTCSessionDescriptionRequestImpl::clear): * Modules/mediastream/RTCSessionDescriptionRequestImpl.h: (RTCSessionDescriptionRequestImpl): * Modules/mediastream/RTCVoidRequestImpl.cpp: Removed. * Modules/mediastream/RTCVoidRequestImpl.h: Removed. * WebCore.gypi: * platform/chromium/support/WebRTCVoidRequest.cpp: Removed. * platform/mediastream/RTCPeerConnectionHandler.cpp: (RTCPeerConnectionHandlerDummy): (WebCore::RTCPeerConnectionHandlerDummy::RTCPeerConnectionHandlerDummy): * platform/mediastream/RTCPeerConnectionHandler.h: (WebCore): (WebCore::RTCPeerConnectionHandler::~RTCPeerConnectionHandler): (RTCPeerConnectionHandler): (WebCore::RTCPeerConnectionHandler::RTCPeerConnectionHandler): * platform/mediastream/RTCVoidRequest.h: Removed. * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.cpp: * platform/mediastream/chromium/RTCPeerConnectionHandlerChromium.h: (RTCPeerConnectionHandlerChromium): Tools: * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.cpp: (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::SuccessCallbackTask): (MockWebRTCPeerConnectionHandler::SuccessCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::FailureCallbackTask): (MockWebRTCPeerConnectionHandler::FailureCallbackTask::runIfValid): (MockWebRTCPeerConnectionHandler::createOffer): * DumpRenderTree/chromium/MockWebRTCPeerConnectionHandler.h: (MockWebRTCPeerConnectionHandler): (SuccessCallbackTask): (FailureCallbackTask): LayoutTests: * fast/mediastream/RTCPeerConnection-createOffer.html: * fast/mediastream/RTCPeerConnection-localDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-localDescription.html: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription-expected.txt: Removed. * fast/mediastream/RTCPeerConnection-remoteDescription.html: Removed. git-svn-id: svn://svn.chromium.org/blink/trunk@127679 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 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 fwnet_incoming_packet(struct fwnet_device *dev, __be32 *buf, int len, int source_node_id, int generation, bool is_broadcast) { struct sk_buff *skb; struct net_device *net = dev->netdev; struct rfc2734_header hdr; unsigned lf; unsigned long flags; struct fwnet_peer *peer; struct fwnet_partial_datagram *pd; int fg_off; int dg_size; u16 datagram_label; int retval; u16 ether_type; hdr.w0 = be32_to_cpu(buf[0]); lf = fwnet_get_hdr_lf(&hdr); if (lf == RFC2374_HDR_UNFRAG) { /* * An unfragmented datagram has been received by the ieee1394 * bus. Build an skbuff around it so we can pass it to the * high level network layer. */ ether_type = fwnet_get_hdr_ether_type(&hdr); buf++; len -= RFC2374_UNFRAG_HDR_SIZE; skb = dev_alloc_skb(len + LL_RESERVED_SPACE(net)); if (unlikely(!skb)) { net->stats.rx_dropped++; return -ENOMEM; } skb_reserve(skb, LL_RESERVED_SPACE(net)); memcpy(skb_put(skb, len), buf, len); return fwnet_finish_incoming_packet(net, skb, source_node_id, is_broadcast, ether_type); } /* A datagram fragment has been received, now the fun begins. */ hdr.w1 = ntohl(buf[1]); buf += 2; len -= RFC2374_FRAG_HDR_SIZE; if (lf == RFC2374_HDR_FIRSTFRAG) { ether_type = fwnet_get_hdr_ether_type(&hdr); fg_off = 0; } else { ether_type = 0; fg_off = fwnet_get_hdr_fg_off(&hdr); } datagram_label = fwnet_get_hdr_dgl(&hdr); dg_size = fwnet_get_hdr_dg_size(&hdr); /* ??? + 1 */ spin_lock_irqsave(&dev->lock, flags); peer = fwnet_peer_find_by_node_id(dev, source_node_id, generation); if (!peer) { retval = -ENOENT; goto fail; } pd = fwnet_pd_find(peer, datagram_label); if (pd == NULL) { while (peer->pdg_size >= FWNET_MAX_FRAGMENTS) { /* remove the oldest */ fwnet_pd_delete(list_first_entry(&peer->pd_list, struct fwnet_partial_datagram, pd_link)); peer->pdg_size--; } pd = fwnet_pd_new(net, peer, datagram_label, dg_size, buf, fg_off, len); if (pd == NULL) { retval = -ENOMEM; goto fail; } peer->pdg_size++; } else { if (fwnet_frag_overlap(pd, fg_off, len) || pd->datagram_size != dg_size) { /* * Differing datagram sizes or overlapping fragments, * discard old datagram and start a new one. */ fwnet_pd_delete(pd); pd = fwnet_pd_new(net, peer, datagram_label, dg_size, buf, fg_off, len); if (pd == NULL) { peer->pdg_size--; retval = -ENOMEM; goto fail; } } else { if (!fwnet_pd_update(peer, pd, buf, fg_off, len)) { /* * Couldn't save off fragment anyway * so might as well obliterate the * datagram now. */ fwnet_pd_delete(pd); peer->pdg_size--; retval = -ENOMEM; goto fail; } } } /* new datagram or add to existing one */ if (lf == RFC2374_HDR_FIRSTFRAG) pd->ether_type = ether_type; if (fwnet_pd_is_complete(pd)) { ether_type = pd->ether_type; peer->pdg_size--; skb = skb_get(pd->skb); fwnet_pd_delete(pd); spin_unlock_irqrestore(&dev->lock, flags); return fwnet_finish_incoming_packet(net, skb, source_node_id, false, ether_type); } /* * Datagram is not complete, we're done for the * moment. */ retval = 0; fail: spin_unlock_irqrestore(&dev->lock, flags); return retval; } Commit Message: firewire: net: guard against rx buffer overflows The IP-over-1394 driver firewire-net lacked input validation when handling incoming fragmented datagrams. A maliciously formed fragment with a respectively large datagram_offset would cause a memcpy past the datagram buffer. So, drop any packets carrying a fragment with offset + length larger than datagram_size. In addition, ensure that - GASP header, unfragmented encapsulation header, or fragment encapsulation header actually exists before we access it, - the encapsulated datagram or fragment is of nonzero size. Reported-by: Eyal Itkin <[email protected]> Reviewed-by: Eyal Itkin <[email protected]> Fixes: CVE 2016-8633 Cc: [email protected] Signed-off-by: Stefan Richter <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval) { ++attrval->refcnt; return attrval; } 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: const String StyledMarkupAccumulator::styleNodeCloseTag(bool isBlock) { DEFINE_STATIC_LOCAL(const String, divClose, ("</div>")); DEFINE_STATIC_LOCAL(const String, styleSpanClose, ("</span>")); return isBlock ? divClose : styleSpanClose; } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 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: MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,0,0,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y, MagickMax(Ar_image->columns,Cr_image->columns),1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y, MagickMax(Ai_image->columns,Ci_image->columns),1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y, MagickMax(Br_image->columns,Cr_image->columns),1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y, MagickMax(Bi_image->columns,Ci_image->columns),1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1595 CWE ID: CWE-119 Target: 1 Example 2: Code: static inline unsigned rb_page_size(struct buffer_page *bpage) { return rb_page_commit(bpage); } Commit Message: ring-buffer: Prevent overflow of size in ring_buffer_resize() If the size passed to ring_buffer_resize() is greater than MAX_LONG - BUF_PAGE_SIZE then the DIV_ROUND_UP() will return zero. Here's the details: # echo 18014398509481980 > /sys/kernel/debug/tracing/buffer_size_kb tracing_entries_write() processes this and converts kb to bytes. 18014398509481980 << 10 = 18446744073709547520 and this is passed to ring_buffer_resize() as unsigned long size. size = DIV_ROUND_UP(size, BUF_PAGE_SIZE); Where DIV_ROUND_UP(a, b) is (a + b - 1)/b BUF_PAGE_SIZE is 4080 and here 18446744073709547520 + 4080 - 1 = 18446744073709551599 where 18446744073709551599 is still smaller than 2^64 2^64 - 18446744073709551599 = 17 But now 18446744073709551599 / 4080 = 4521260802379792 and size = size * 4080 = 18446744073709551360 This is checked to make sure its still greater than 2 * 4080, which it is. Then we convert to the number of buffer pages needed. nr_page = DIV_ROUND_UP(size, BUF_PAGE_SIZE) but this time size is 18446744073709551360 and 2^64 - (18446744073709551360 + 4080 - 1) = -3823 Thus it overflows and the resulting number is less than 4080, which makes 3823 / 4080 = 0 an nr_pages is set to this. As we already checked against the minimum that nr_pages may be, this causes the logic to fail as well, and we crash the kernel. There's no reason to have the two DIV_ROUND_UP() (that's just result of historical code changes), clean up the code and fix this bug. Cc: [email protected] # 3.5+ Fixes: 83f40318dab00 ("ring-buffer: Make removal of ring buffer pages atomic") Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int rds_send_queue_rm(struct rds_sock *rs, struct rds_connection *conn, struct rds_message *rm, __be16 sport, __be16 dport, int *queued) { unsigned long flags; u32 len; if (*queued) goto out; len = be32_to_cpu(rm->m_inc.i_hdr.h_len); /* this is the only place which holds both the socket's rs_lock * and the connection's c_lock */ spin_lock_irqsave(&rs->rs_lock, flags); /* * If there is a little space in sndbuf, we don't queue anything, * and userspace gets -EAGAIN. But poll() indicates there's send * room. This can lead to bad behavior (spinning) if snd_bytes isn't * freed up by incoming acks. So we check the *old* value of * rs_snd_bytes here to allow the last msg to exceed the buffer, * and poll() now knows no more data can be sent. */ if (rs->rs_snd_bytes < rds_sk_sndbuf(rs)) { rs->rs_snd_bytes += len; /* let recv side know we are close to send space exhaustion. * This is probably not the optimal way to do it, as this * means we set the flag on *all* messages as soon as our * throughput hits a certain threshold. */ if (rs->rs_snd_bytes >= rds_sk_sndbuf(rs) / 2) __set_bit(RDS_MSG_ACK_REQUIRED, &rm->m_flags); list_add_tail(&rm->m_sock_item, &rs->rs_send_queue); set_bit(RDS_MSG_ON_SOCK, &rm->m_flags); rds_message_addref(rm); rm->m_rs = rs; /* The code ordering is a little weird, but we're trying to minimize the time we hold c_lock */ rds_message_populate_header(&rm->m_inc.i_hdr, sport, dport, 0); rm->m_inc.i_conn = conn; rds_message_addref(rm); spin_lock(&conn->c_lock); rm->m_inc.i_hdr.h_sequence = cpu_to_be64(conn->c_next_tx_seq++); list_add_tail(&rm->m_conn_item, &conn->c_send_queue); set_bit(RDS_MSG_ON_CONN, &rm->m_flags); spin_unlock(&conn->c_lock); rdsdebug("queued msg %p len %d, rs %p bytes %d seq %llu\n", rm, len, rs, rs->rs_snd_bytes, (unsigned long long)be64_to_cpu(rm->m_inc.i_hdr.h_sequence)); *queued = 1; } spin_unlock_irqrestore(&rs->rs_lock, flags); out: return *queued; } Commit Message: RDS: fix race condition when sending a message on unbound socket Sasha's found a NULL pointer dereference in the RDS connection code when sending a message to an apparently unbound socket. The problem is caused by the code checking if the socket is bound in rds_sendmsg(), which checks the rs_bound_addr field without taking a lock on the socket. This opens a race where rs_bound_addr is temporarily set but where the transport is not in rds_bind(), leading to a NULL pointer dereference when trying to dereference 'trans' in __rds_conn_create(). Vegard wrote a reproducer for this issue, so kindly ask him to share if you're interested. I cannot reproduce the NULL pointer dereference using Vegard's reproducer with this patch, whereas I could without. Complete earlier incomplete fix to CVE-2015-6937: 74e98eb08588 ("RDS: verify the underlying transport exists before creating a connection") Cc: David S. Miller <[email protected]> Cc: [email protected] Reviewed-by: Vegard Nossum <[email protected]> Reviewed-by: Sasha Levin <[email protected]> Acked-by: Santosh Shilimkar <[email protected]> Signed-off-by: Quentin Casasnovas <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 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 opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } Commit Message: [MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: TestChunkerDisplayItem(const DisplayItemClient& client, DisplayItem::Type type = DisplayItem::kDrawingFirst) : DisplayItem(client, type, sizeof(*this)) {} Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} 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 HTMLFormElement::ShouldAutocomplete() const { return !DeprecatedEqualIgnoringCase(FastGetAttribute(autocompleteAttr), "off"); } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190 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: gs_pattern2_set_color(const gs_client_color * pcc, gs_gstate * pgs) { gs_pattern2_instance_t * pinst = (gs_pattern2_instance_t *)pcc->pattern; gs_color_space * pcs = pinst->templat.Shading->params.ColorSpace; int code; uchar k, num_comps; pinst->saved->overprint_mode = pgs->overprint_mode; pinst->saved->overprint = pgs->overprint; num_comps = pgs->device->color_info.num_components; for (k = 0; k < num_comps; k++) { pgs->color_component_map.color_map[k] = pinst->saved->color_component_map.color_map[k]; } code = pcs->type->set_overprint(pcs, pgs); return code; } Commit Message: CWE ID: CWE-704 Target: 1 Example 2: Code: SpeechRecognitionManagerImpl::GetSessionContext(int session_id) const { return GetSession(session_id)->context; } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: smb_com_flush(smb_request_t *sr) { smb_ofile_t *file; smb_llist_t *flist; int rc; if (smb_flush_required == 0) { rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); } if (sr->smb_fid != 0xffff) { smbsr_lookup_file(sr); if (sr->fid_ofile == NULL) { smbsr_error(sr, NT_STATUS_INVALID_HANDLE, ERRDOS, ERRbadfid); return (SDRC_ERROR); } smb_flush_file(sr, sr->fid_ofile); } else { flist = &sr->tid_tree->t_ofile_list; smb_llist_enter(flist, RW_READER); file = smb_llist_head(flist); while (file) { mutex_enter(&file->f_mutex); smb_flush_file(sr, file); mutex_exit(&file->f_mutex); file = smb_llist_next(flist, file); } smb_llist_exit(flist); } rc = smbsr_encode_empty_result(sr); return ((rc == 0) ? SDRC_SUCCESS : SDRC_ERROR); } Commit Message: 7483 SMB flush on pipe triggers NULL pointer dereference in module smbsrv Reviewed by: Gordon Ross <[email protected]> Reviewed by: Matt Barden <[email protected]> Reviewed by: Evan Layton <[email protected]> Reviewed by: Dan McDonald <[email protected]> Approved by: Gordon Ross <[email protected]> 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: png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, int num_weights, png_doublep filter_weights, png_doublep filter_costs) { int i; png_debug(1, "in png_set_filter_heuristics"); if (png_ptr == NULL) return; if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST) { png_warning(png_ptr, "Unknown filter heuristic method"); return; } if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT) { heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED; } if (num_weights < 0 || filter_weights == NULL || heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED) { num_weights = 0; } png_ptr->num_prev_filters = (png_byte)num_weights; png_ptr->heuristic_method = (png_byte)heuristic_method; if (num_weights > 0) { if (png_ptr->prev_filters == NULL) { png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_byte) * num_weights)); /* To make sure that the weighting starts out fairly */ for (i = 0; i < num_weights; i++) { png_ptr->prev_filters[i] = 255; } } if (png_ptr->filter_weights == NULL) { png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); for (i = 0; i < num_weights; i++) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } } for (i = 0; i < num_weights; i++) { if (filter_weights[i] < 0.0) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } else { png_ptr->inv_filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5); png_ptr->filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5); } } } /* If, in the future, there are other filter methods, this would * need to be based on png_ptr->filter. */ if (png_ptr->filter_costs == NULL) { png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } } /* Here is where we set the relative costs of the different filters. We * should take the desired compression level into account when setting * the costs, so that Paeth, for instance, has a high relative cost at low * compression levels, while it has a lower relative cost at higher * compression settings. The filter types are in order of increasing * relative cost, so it would be possible to do this with an algorithm. */ for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { if (filter_costs == NULL || filter_costs[i] < 0.0) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } else if (filter_costs[i] >= 1.0) { png_ptr->inv_filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5); png_ptr->filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5); } } } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119 Target: 1 Example 2: Code: static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to) { struct file *file = iocb->ki_filp; struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); ssize_t len = iov_iter_count(to), ret; if (!tun) return -EBADFD; ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK, NULL); ret = min_t(ssize_t, ret, len); if (ret > 0) iocb->ki_pos = ret; tun_put(tun); return ret; } Commit Message: tun: call dev_get_valid_name() before register_netdevice() register_netdevice() could fail early when we have an invalid dev name, in which case ->ndo_uninit() is not called. For tun device, this is a problem because a timer etc. are already initialized and it expects ->ndo_uninit() to clean them up. We could move these initializations into a ->ndo_init() so that register_netdevice() knows better, however this is still complicated due to the logic in tun_detach(). Therefore, I choose to just call dev_get_valid_name() before register_netdevice(), which is quicker and much easier to audit. And for this specific case, it is already enough. Fixes: 96442e42429e ("tuntap: choose the txq based on rxq") Reported-by: Dmitry Alexeev <[email protected]> Cc: Jason Wang <[email protected]> Cc: "Michael S. Tsirkin" <[email protected]> Signed-off-by: Cong Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 sas_unregister_devs_sas_addr(struct domain_device *parent, int phy_id, bool last) { struct expander_device *ex_dev = &parent->ex_dev; struct ex_phy *phy = &ex_dev->ex_phy[phy_id]; struct domain_device *child, *n, *found = NULL; if (last) { list_for_each_entry_safe(child, n, &ex_dev->children, siblings) { if (SAS_ADDR(child->sas_addr) == SAS_ADDR(phy->attached_sas_addr)) { set_bit(SAS_DEV_GONE, &child->state); if (child->dev_type == SAS_EDGE_EXPANDER_DEVICE || child->dev_type == SAS_FANOUT_EXPANDER_DEVICE) sas_unregister_ex_tree(parent->port, child); else sas_unregister_dev(parent->port, child); found = child; break; } } sas_disable_routing(parent, phy->attached_sas_addr); } memset(phy->attached_sas_addr, 0, SAS_ADDR_SIZE); if (phy->port) { sas_port_delete_phy(phy->port, phy->phy); sas_device_set_phy(found, phy->port); if (phy->port->num_phys == 0) sas_port_delete(phy->port); phy->port = NULL; } } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: 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 asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry, const u8 *obj, size_t objlen, int depth) { void *parm = entry->parm; int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj, size_t nobjlen, int ndepth); size_t *len = (size_t *) entry->arg; int r = 0; callback_func = parm; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n", depth, depth, "", entry->name, sc_dump_hex(obj, objlen > 16 ? 16 : objlen), objlen > 16 ? "..." : ""); switch (entry->type) { case SC_ASN1_STRUCT: if (parm != NULL) r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj, objlen, NULL, NULL, 0, depth + 1); break; case SC_ASN1_NULL: break; case SC_ASN1_BOOLEAN: if (parm != NULL) { if (objlen != 1) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n", objlen); r = SC_ERROR_INVALID_ASN1_OBJECT; } else *((int *) parm) = obj[0] ? 1 : 0; } break; case SC_ASN1_INTEGER: case SC_ASN1_ENUMERATED: if (parm != NULL) { r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm); sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "", entry->name, *((int *) entry->parm)); } break; case SC_ASN1_BIT_STRING_NI: case SC_ASN1_BIT_STRING: if (parm != NULL) { int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0; assert(len != NULL); if (objlen < 1) { r = SC_ERROR_INVALID_ASN1_OBJECT; break; } if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen-1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen-1; parm = *buf; } r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert); if (r >= 0) { *len = r; r = 0; } } break; case SC_ASN1_BIT_FIELD: if (parm != NULL) r = decode_bit_field(obj, objlen, (u8 *) parm, *len); break; case SC_ASN1_OCTET_STRING: if (parm != NULL) { size_t c; assert(len != NULL); /* Strip off padding zero */ if ((entry->flags & SC_ASN1_UNSIGNED) && obj[0] == 0x00 && objlen > 1) { objlen--; obj++; } /* Allocate buffer if needed */ if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_GENERALIZEDTIME: if (parm != NULL) { size_t c; assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_OBJECT: if (parm != NULL) r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm); break; case SC_ASN1_PRINTABLESTRING: case SC_ASN1_UTF8STRING: if (parm != NULL) { assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen+1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen+1; parm = *buf; } r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len); if (entry->flags & SC_ASN1_ALLOC) { *len -= 1; } } break; case SC_ASN1_PATH: if (entry->parm != NULL) r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth); break; case SC_ASN1_PKCS15_ID: if (entry->parm != NULL) { struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm; size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen; memcpy(id->value, obj, c); id->len = c; } break; case SC_ASN1_PKCS15_OBJECT: if (entry->parm != NULL) r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth); break; case SC_ASN1_ALGORITHM_ID: if (entry->parm != NULL) r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth); break; case SC_ASN1_SE_INFO: if (entry->parm != NULL) r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth); break; case SC_ASN1_CALLBACK: if (entry->parm != NULL) r = callback_func(ctx, entry->arg, obj, objlen, depth); break; default: sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type); return SC_ERROR_INVALID_ASN1_OBJECT; } if (r) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name, sc_strerror(r)); return r; } entry->flags |= SC_ASN1_PRESENT; return 0; } Commit Message: Fixed out of bounds access in ASN.1 Octet string Credit to OSS-Fuzz CWE ID: CWE-119 Target: 1 Example 2: Code: static void mem_cgroup_put(struct mem_cgroup *memcg) { __mem_cgroup_put(memcg, 1); } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: DocumentOnLoadCompletedInMainFrame() { devtools_bindings_->DocumentOnLoadCompletedInMainFrame(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200 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 do_ip_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct inet_sock *inet = inet_sk(sk); int val = 0, err; if (((1<<optname) & ((1<<IP_PKTINFO) | (1<<IP_RECVTTL) | (1<<IP_RECVOPTS) | (1<<IP_RECVTOS) | (1<<IP_RETOPTS) | (1<<IP_TOS) | (1<<IP_TTL) | (1<<IP_HDRINCL) | (1<<IP_MTU_DISCOVER) | (1<<IP_RECVERR) | (1<<IP_ROUTER_ALERT) | (1<<IP_FREEBIND) | (1<<IP_PASSSEC) | (1<<IP_TRANSPARENT) | (1<<IP_MINTTL) | (1<<IP_NODEFRAG))) || optname == IP_MULTICAST_TTL || optname == IP_MULTICAST_ALL || optname == IP_MULTICAST_LOOP || optname == IP_RECVORIGDSTADDR) { if (optlen >= sizeof(int)) { if (get_user(val, (int __user *) optval)) return -EFAULT; } else if (optlen >= sizeof(char)) { unsigned char ucval; if (get_user(ucval, (unsigned char __user *) optval)) return -EFAULT; val = (int) ucval; } } /* If optlen==0, it is equivalent to val == 0 */ if (ip_mroute_opt(optname)) return ip_mroute_setsockopt(sk, optname, optval, optlen); err = 0; lock_sock(sk); switch (optname) { case IP_OPTIONS: { struct ip_options *opt = NULL; if (optlen > 40) goto e_inval; err = ip_options_get_from_user(sock_net(sk), &opt, optval, optlen); if (err) break; if (inet->is_icsk) { struct inet_connection_sock *icsk = inet_csk(sk); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) if (sk->sk_family == PF_INET || (!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) && inet->inet_daddr != LOOPBACK4_IPV6)) { #endif if (inet->opt) icsk->icsk_ext_hdr_len -= inet->opt->optlen; if (opt) icsk->icsk_ext_hdr_len += opt->optlen; icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) } #endif } opt = xchg(&inet->opt, opt); kfree(opt); break; } case IP_PKTINFO: if (val) inet->cmsg_flags |= IP_CMSG_PKTINFO; else inet->cmsg_flags &= ~IP_CMSG_PKTINFO; break; case IP_RECVTTL: if (val) inet->cmsg_flags |= IP_CMSG_TTL; else inet->cmsg_flags &= ~IP_CMSG_TTL; break; case IP_RECVTOS: if (val) inet->cmsg_flags |= IP_CMSG_TOS; else inet->cmsg_flags &= ~IP_CMSG_TOS; break; case IP_RECVOPTS: if (val) inet->cmsg_flags |= IP_CMSG_RECVOPTS; else inet->cmsg_flags &= ~IP_CMSG_RECVOPTS; break; case IP_RETOPTS: if (val) inet->cmsg_flags |= IP_CMSG_RETOPTS; else inet->cmsg_flags &= ~IP_CMSG_RETOPTS; break; case IP_PASSSEC: if (val) inet->cmsg_flags |= IP_CMSG_PASSSEC; else inet->cmsg_flags &= ~IP_CMSG_PASSSEC; break; case IP_RECVORIGDSTADDR: if (val) inet->cmsg_flags |= IP_CMSG_ORIGDSTADDR; else inet->cmsg_flags &= ~IP_CMSG_ORIGDSTADDR; break; case IP_TOS: /* This sets both TOS and Precedence */ if (sk->sk_type == SOCK_STREAM) { val &= ~3; val |= inet->tos & 3; } if (inet->tos != val) { inet->tos = val; sk->sk_priority = rt_tos2priority(val); sk_dst_reset(sk); } break; case IP_TTL: if (optlen < 1) goto e_inval; if (val != -1 && (val < 0 || val > 255)) goto e_inval; inet->uc_ttl = val; break; case IP_HDRINCL: if (sk->sk_type != SOCK_RAW) { err = -ENOPROTOOPT; break; } inet->hdrincl = val ? 1 : 0; break; case IP_NODEFRAG: if (sk->sk_type != SOCK_RAW) { err = -ENOPROTOOPT; break; } inet->nodefrag = val ? 1 : 0; break; case IP_MTU_DISCOVER: if (val < IP_PMTUDISC_DONT || val > IP_PMTUDISC_PROBE) goto e_inval; inet->pmtudisc = val; break; case IP_RECVERR: inet->recverr = !!val; if (!val) skb_queue_purge(&sk->sk_error_queue); break; case IP_MULTICAST_TTL: if (sk->sk_type == SOCK_STREAM) goto e_inval; if (optlen < 1) goto e_inval; if (val == -1) val = 1; if (val < 0 || val > 255) goto e_inval; inet->mc_ttl = val; break; case IP_MULTICAST_LOOP: if (optlen < 1) goto e_inval; inet->mc_loop = !!val; break; case IP_MULTICAST_IF: { struct ip_mreqn mreq; struct net_device *dev = NULL; if (sk->sk_type == SOCK_STREAM) goto e_inval; /* * Check the arguments are allowable */ if (optlen < sizeof(struct in_addr)) goto e_inval; err = -EFAULT; if (optlen >= sizeof(struct ip_mreqn)) { if (copy_from_user(&mreq, optval, sizeof(mreq))) break; } else { memset(&mreq, 0, sizeof(mreq)); if (optlen >= sizeof(struct in_addr) && copy_from_user(&mreq.imr_address, optval, sizeof(struct in_addr))) break; } if (!mreq.imr_ifindex) { if (mreq.imr_address.s_addr == htonl(INADDR_ANY)) { inet->mc_index = 0; inet->mc_addr = 0; err = 0; break; } dev = ip_dev_find(sock_net(sk), mreq.imr_address.s_addr); if (dev) mreq.imr_ifindex = dev->ifindex; } else dev = dev_get_by_index(sock_net(sk), mreq.imr_ifindex); err = -EADDRNOTAVAIL; if (!dev) break; dev_put(dev); err = -EINVAL; if (sk->sk_bound_dev_if && mreq.imr_ifindex != sk->sk_bound_dev_if) break; inet->mc_index = mreq.imr_ifindex; inet->mc_addr = mreq.imr_address.s_addr; err = 0; break; } case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: { struct ip_mreqn mreq; err = -EPROTO; if (inet_sk(sk)->is_icsk) break; if (optlen < sizeof(struct ip_mreq)) goto e_inval; err = -EFAULT; if (optlen >= sizeof(struct ip_mreqn)) { if (copy_from_user(&mreq, optval, sizeof(mreq))) break; } else { memset(&mreq, 0, sizeof(mreq)); if (copy_from_user(&mreq, optval, sizeof(struct ip_mreq))) break; } if (optname == IP_ADD_MEMBERSHIP) err = ip_mc_join_group(sk, &mreq); else err = ip_mc_leave_group(sk, &mreq); break; } case IP_MSFILTER: { struct ip_msfilter *msf; if (optlen < IP_MSFILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { err = -ENOBUFS; break; } msf = kmalloc(optlen, GFP_KERNEL); if (!msf) { err = -ENOBUFS; break; } err = -EFAULT; if (copy_from_user(msf, optval, optlen)) { kfree(msf); break; } /* numsrc >= (1G-4) overflow in 32 bits */ if (msf->imsf_numsrc >= 0x3ffffffcU || msf->imsf_numsrc > sysctl_igmp_max_msf) { kfree(msf); err = -ENOBUFS; break; } if (IP_MSFILTER_SIZE(msf->imsf_numsrc) > optlen) { kfree(msf); err = -EINVAL; break; } err = ip_mc_msfilter(sk, msf, 0); kfree(msf); break; } case IP_BLOCK_SOURCE: case IP_UNBLOCK_SOURCE: case IP_ADD_SOURCE_MEMBERSHIP: case IP_DROP_SOURCE_MEMBERSHIP: { struct ip_mreq_source mreqs; int omode, add; if (optlen != sizeof(struct ip_mreq_source)) goto e_inval; if (copy_from_user(&mreqs, optval, sizeof(mreqs))) { err = -EFAULT; break; } if (optname == IP_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == IP_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == IP_ADD_SOURCE_MEMBERSHIP) { struct ip_mreqn mreq; mreq.imr_multiaddr.s_addr = mreqs.imr_multiaddr; mreq.imr_address.s_addr = mreqs.imr_interface; mreq.imr_ifindex = 0; err = ip_mc_join_group(sk, &mreq); if (err && err != -EADDRINUSE) break; omode = MCAST_INCLUDE; add = 1; } else /* IP_DROP_SOURCE_MEMBERSHIP */ { omode = MCAST_INCLUDE; add = 0; } err = ip_mc_source(add, omode, sk, &mreqs, 0); break; } case MCAST_JOIN_GROUP: case MCAST_LEAVE_GROUP: { struct group_req greq; struct sockaddr_in *psin; struct ip_mreqn mreq; if (optlen < sizeof(struct group_req)) goto e_inval; err = -EFAULT; if (copy_from_user(&greq, optval, sizeof(greq))) break; psin = (struct sockaddr_in *)&greq.gr_group; if (psin->sin_family != AF_INET) goto e_inval; memset(&mreq, 0, sizeof(mreq)); mreq.imr_multiaddr = psin->sin_addr; mreq.imr_ifindex = greq.gr_interface; if (optname == MCAST_JOIN_GROUP) err = ip_mc_join_group(sk, &mreq); else err = ip_mc_leave_group(sk, &mreq); break; } case MCAST_JOIN_SOURCE_GROUP: case MCAST_LEAVE_SOURCE_GROUP: case MCAST_BLOCK_SOURCE: case MCAST_UNBLOCK_SOURCE: { struct group_source_req greqs; struct ip_mreq_source mreqs; struct sockaddr_in *psin; int omode, add; if (optlen != sizeof(struct group_source_req)) goto e_inval; if (copy_from_user(&greqs, optval, sizeof(greqs))) { err = -EFAULT; break; } if (greqs.gsr_group.ss_family != AF_INET || greqs.gsr_source.ss_family != AF_INET) { err = -EADDRNOTAVAIL; break; } psin = (struct sockaddr_in *)&greqs.gsr_group; mreqs.imr_multiaddr = psin->sin_addr.s_addr; psin = (struct sockaddr_in *)&greqs.gsr_source; mreqs.imr_sourceaddr = psin->sin_addr.s_addr; mreqs.imr_interface = 0; /* use index for mc_source */ if (optname == MCAST_BLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 1; } else if (optname == MCAST_UNBLOCK_SOURCE) { omode = MCAST_EXCLUDE; add = 0; } else if (optname == MCAST_JOIN_SOURCE_GROUP) { struct ip_mreqn mreq; psin = (struct sockaddr_in *)&greqs.gsr_group; mreq.imr_multiaddr = psin->sin_addr; mreq.imr_address.s_addr = 0; mreq.imr_ifindex = greqs.gsr_interface; err = ip_mc_join_group(sk, &mreq); if (err && err != -EADDRINUSE) break; greqs.gsr_interface = mreq.imr_ifindex; omode = MCAST_INCLUDE; add = 1; } else /* MCAST_LEAVE_SOURCE_GROUP */ { omode = MCAST_INCLUDE; add = 0; } err = ip_mc_source(add, omode, sk, &mreqs, greqs.gsr_interface); break; } case MCAST_MSFILTER: { struct sockaddr_in *psin; struct ip_msfilter *msf = NULL; struct group_filter *gsf = NULL; int msize, i, ifindex; if (optlen < GROUP_FILTER_SIZE(0)) goto e_inval; if (optlen > sysctl_optmem_max) { err = -ENOBUFS; break; } gsf = kmalloc(optlen, GFP_KERNEL); if (!gsf) { err = -ENOBUFS; break; } err = -EFAULT; if (copy_from_user(gsf, optval, optlen)) goto mc_msf_out; /* numsrc >= (4G-140)/128 overflow in 32 bits */ if (gsf->gf_numsrc >= 0x1ffffff || gsf->gf_numsrc > sysctl_igmp_max_msf) { err = -ENOBUFS; goto mc_msf_out; } if (GROUP_FILTER_SIZE(gsf->gf_numsrc) > optlen) { err = -EINVAL; goto mc_msf_out; } msize = IP_MSFILTER_SIZE(gsf->gf_numsrc); msf = kmalloc(msize, GFP_KERNEL); if (!msf) { err = -ENOBUFS; goto mc_msf_out; } ifindex = gsf->gf_interface; psin = (struct sockaddr_in *)&gsf->gf_group; if (psin->sin_family != AF_INET) { err = -EADDRNOTAVAIL; goto mc_msf_out; } msf->imsf_multiaddr = psin->sin_addr.s_addr; msf->imsf_interface = 0; msf->imsf_fmode = gsf->gf_fmode; msf->imsf_numsrc = gsf->gf_numsrc; err = -EADDRNOTAVAIL; for (i = 0; i < gsf->gf_numsrc; ++i) { psin = (struct sockaddr_in *)&gsf->gf_slist[i]; if (psin->sin_family != AF_INET) goto mc_msf_out; msf->imsf_slist[i] = psin->sin_addr.s_addr; } kfree(gsf); gsf = NULL; err = ip_mc_msfilter(sk, msf, ifindex); mc_msf_out: kfree(msf); kfree(gsf); break; } case IP_MULTICAST_ALL: if (optlen < 1) goto e_inval; if (val != 0 && val != 1) goto e_inval; inet->mc_all = val; break; case IP_ROUTER_ALERT: err = ip_ra_control(sk, val ? 1 : 0, NULL); break; case IP_FREEBIND: if (optlen < 1) goto e_inval; inet->freebind = !!val; break; case IP_IPSEC_POLICY: case IP_XFRM_POLICY: err = -EPERM; if (!capable(CAP_NET_ADMIN)) break; err = xfrm_user_policy(sk, optname, optval, optlen); break; case IP_TRANSPARENT: if (!capable(CAP_NET_ADMIN)) { err = -EPERM; break; } if (optlen < 1) goto e_inval; inet->transparent = !!val; break; case IP_MINTTL: if (optlen < 1) goto e_inval; if (val < 0 || val > 255) goto e_inval; inet->min_ttl = val; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; e_inval: release_sock(sk); return -EINVAL; } 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: Eina_Bool ewk_frame_mixed_content_run_get(const Evas_Object* ewkFrame) { EWK_FRAME_SD_GET_OR_RETURN(ewkFrame, smartData, false); return smartData->hasRunMixedContent; } Commit Message: [EFL] fast/frames/frame-crash-with-page-cache.html is crashing https://bugs.webkit.org/show_bug.cgi?id=85879 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-05-17 Reviewed by Noam Rosenthal. Source/WebKit/efl: _ewk_frame_smart_del() is considering now that the frame can be present in cache. loader()->detachFromParent() is only applied for the main frame. loader()->cancelAndClear() is not used anymore. * ewk/ewk_frame.cpp: (_ewk_frame_smart_del): LayoutTests: * platform/efl/test_expectations.txt: Removed fast/frames/frame-crash-with-page-cache.html. git-svn-id: svn://svn.chromium.org/blink/trunk@117409 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool Document::AllowInlineEventHandler(Node* node, EventListener* listener, const String& context_url, const WTF::OrdinalNumber& context_line) { Element* element = node && node->IsElementNode() ? ToElement(node) : nullptr; if (!ContentSecurityPolicy::ShouldBypassMainWorld(this) && !GetContentSecurityPolicy()->AllowInlineEventHandler( element, listener->Code(), context_url, context_line)) return false; LocalFrame* frame = ExecutingFrame(); if (!frame) return false; if (!ContextDocument()->CanExecuteScripts(kNotAboutToExecuteScript)) return false; if (node && node->GetDocument() != this && !node->GetDocument().AllowInlineEventHandler(node, listener, context_url, context_line)) return false; return true; } Commit Message: Inherit CSP when we inherit the security origin This prevents attacks that use main window navigation to get out of the existing csp constraints such as the related bug Bug: 747847 Change-Id: I1e57b50da17f65d38088205b0a3c7c49ef2ae4d8 Reviewed-on: https://chromium-review.googlesource.com/592027 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#492333} CWE ID: CWE-732 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) { if (err != OK) { mMetaDataSize = -1ll; mContentType = ""; mSniffedMIME = ""; { sp<DataSource> dataSource = mDataSource; sp<NuCachedSource2> cachedSource = mCachedSource; sp<DataSource> httpSource = mHttpSource; { Mutex::Autolock _l(mDisconnectLock); mDataSource.clear(); mCachedSource.clear(); mHttpSource.clear(); } } cancelPollBuffering(); } notifyPrepared(err); } Commit Message: GenericSource: reset mDrmManagerClient when mDataSource is cleared. Bug: 25070434 Change-Id: Iade3472c496ac42456e42db35e402f7b66416f5b (cherry picked from commit b41fd0d4929f0a89811bafcc4fd944b128f00ce2) CWE ID: CWE-119 Target: 1 Example 2: Code: static int btrfs_rmdir(struct inode *dir, struct dentry *dentry) { struct inode *inode = d_inode(dentry); int err = 0; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) return -EPERM; trans = __unlink_start_trans(dir); if (IS_ERR(trans)) return PTR_ERR(trans); if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { err = btrfs_unlink_subvol(trans, root, dir, BTRFS_I(inode)->location.objectid, dentry->d_name.name, dentry->d_name.len); goto out; } err = btrfs_orphan_add(trans, inode); if (err) goto out; /* now the directory is empty */ err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry), dentry->d_name.name, dentry->d_name.len); if (!err) btrfs_i_size_write(inode, 0); out: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); return err; } Commit Message: Btrfs: fix truncation of compressed and inlined extents When truncating a file to a smaller size which consists of an inline extent that is compressed, we did not discard (or made unusable) the data between the new file size and the old file size, wasting metadata space and allowing for the truncated data to be leaked and the data corruption/loss mentioned below. We were also not correctly decrementing the number of bytes used by the inode, we were setting it to zero, giving a wrong report for callers of the stat(2) syscall. The fsck tool also reported an error about a mismatch between the nbytes of the file versus the real space used by the file. Now because we weren't discarding the truncated region of the file, it was possible for a caller of the clone ioctl to actually read the data that was truncated, allowing for a security breach without requiring root access to the system, using only standard filesystem operations. The scenario is the following: 1) User A creates a file which consists of an inline and compressed extent with a size of 2000 bytes - the file is not accessible to any other users (no read, write or execution permission for anyone else); 2) The user truncates the file to a size of 1000 bytes; 3) User A makes the file world readable; 4) User B creates a file consisting of an inline extent of 2000 bytes; 5) User B issues a clone operation from user A's file into its own file (using a length argument of 0, clone the whole range); 6) User B now gets to see the 1000 bytes that user A truncated from its file before it made its file world readbale. User B also lost the bytes in the range [1000, 2000[ bytes from its own file, but that might be ok if his/her intention was reading stale data from user A that was never supposed to be public. Note that this contrasts with the case where we truncate a file from 2000 bytes to 1000 bytes and then truncate it back from 1000 to 2000 bytes. In this case reading any byte from the range [1000, 2000[ will return a value of 0x00, instead of the original data. This problem exists since the clone ioctl was added and happens both with and without my recent data loss and file corruption fixes for the clone ioctl (patch "Btrfs: fix file corruption and data loss after cloning inline extents"). So fix this by truncating the compressed inline extents as we do for the non-compressed case, which involves decompressing, if the data isn't already in the page cache, compressing the truncated version of the extent, writing the compressed content into the inline extent and then truncate it. The following test case for fstests reproduces the problem. In order for the test to pass both this fix and my previous fix for the clone ioctl that forbids cloning a smaller inline extent into a larger one, which is titled "Btrfs: fix file corruption and data loss after cloning inline extents", are needed. Without that other fix the test fails in a different way that does not leak the truncated data, instead part of destination file gets replaced with zeroes (because the destination file has a larger inline extent than the source). seq=`basename $0` seqres=$RESULT_DIR/$seq echo "QA output created by $seq" tmp=/tmp/$$ status=1 # failure is the default! trap "_cleanup; exit \$status" 0 1 2 3 15 _cleanup() { rm -f $tmp.* } # get standard environment, filters and checks . ./common/rc . ./common/filter # real QA test starts here _need_to_be_root _supported_fs btrfs _supported_os Linux _require_scratch _require_cloner rm -f $seqres.full _scratch_mkfs >>$seqres.full 2>&1 _scratch_mount "-o compress" # Create our test files. File foo is going to be the source of a clone operation # and consists of a single inline extent with an uncompressed size of 512 bytes, # while file bar consists of a single inline extent with an uncompressed size of # 256 bytes. For our test's purpose, it's important that file bar has an inline # extent with a size smaller than foo's inline extent. $XFS_IO_PROG -f -c "pwrite -S 0xa1 0 128" \ -c "pwrite -S 0x2a 128 384" \ $SCRATCH_MNT/foo | _filter_xfs_io $XFS_IO_PROG -f -c "pwrite -S 0xbb 0 256" $SCRATCH_MNT/bar | _filter_xfs_io # Now durably persist all metadata and data. We do this to make sure that we get # on disk an inline extent with a size of 512 bytes for file foo. sync # Now truncate our file foo to a smaller size. Because it consists of a # compressed and inline extent, btrfs did not shrink the inline extent to the # new size (if the extent was not compressed, btrfs would shrink it to 128 # bytes), it only updates the inode's i_size to 128 bytes. $XFS_IO_PROG -c "truncate 128" $SCRATCH_MNT/foo # Now clone foo's inline extent into bar. # This clone operation should fail with errno EOPNOTSUPP because the source # file consists only of an inline extent and the file's size is smaller than # the inline extent of the destination (128 bytes < 256 bytes). However the # clone ioctl was not prepared to deal with a file that has a size smaller # than the size of its inline extent (something that happens only for compressed # inline extents), resulting in copying the full inline extent from the source # file into the destination file. # # Note that btrfs' clone operation for inline extents consists of removing the # inline extent from the destination inode and copy the inline extent from the # source inode into the destination inode, meaning that if the destination # inode's inline extent is larger (N bytes) than the source inode's inline # extent (M bytes), some bytes (N - M bytes) will be lost from the destination # file. Btrfs could copy the source inline extent's data into the destination's # inline extent so that we would not lose any data, but that's currently not # done due to the complexity that would be needed to deal with such cases # (specially when one or both extents are compressed), returning EOPNOTSUPP, as # it's normally not a very common case to clone very small files (only case # where we get inline extents) and copying inline extents does not save any # space (unlike for normal, non-inlined extents). $CLONER_PROG -s 0 -d 0 -l 0 $SCRATCH_MNT/foo $SCRATCH_MNT/bar # Now because the above clone operation used to succeed, and due to foo's inline # extent not being shinked by the truncate operation, our file bar got the whole # inline extent copied from foo, making us lose the last 128 bytes from bar # which got replaced by the bytes in range [128, 256[ from foo before foo was # truncated - in other words, data loss from bar and being able to read old and # stale data from foo that should not be possible to read anymore through normal # filesystem operations. Contrast with the case where we truncate a file from a # size N to a smaller size M, truncate it back to size N and then read the range # [M, N[, we should always get the value 0x00 for all the bytes in that range. # We expected the clone operation to fail with errno EOPNOTSUPP and therefore # not modify our file's bar data/metadata. So its content should be 256 bytes # long with all bytes having the value 0xbb. # # Without the btrfs bug fix, the clone operation succeeded and resulted in # leaking truncated data from foo, the bytes that belonged to its range # [128, 256[, and losing data from bar in that same range. So reading the # file gave us the following content: # # 0000000 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 a1 # * # 0000200 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a 2a # * # 0000400 echo "File bar's content after the clone operation:" od -t x1 $SCRATCH_MNT/bar # Also because the foo's inline extent was not shrunk by the truncate # operation, btrfs' fsck, which is run by the fstests framework everytime a # test completes, failed reporting the following error: # # root 5 inode 257 errors 400, nbytes wrong status=0 exit Cc: [email protected] Signed-off-by: Filipe Manana <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool IsElementEditable(const blink::WebInputElement& element) { return element.isEnabled() && !element.isReadOnly(); } Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent Unlike in AutofillAgent, the factory is no longer used in PAA. [email protected] BUG=609010,609007,608100,608101,433486 Review-Url: https://codereview.chromium.org/1945723003 Cr-Commit-Position: refs/heads/master@{#391475} CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac) { struct cm_id_private *cm_id_priv; cm_id_priv = container_of(id, struct cm_id_private, id); if (smac != NULL) memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac)); if (alt_smac != NULL) memcpy(cm_id_priv->alt_av.smac, alt_smac, sizeof(cm_id_priv->alt_av.smac)); return 0; } Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <[email protected]> Signed-off-by: Or Gerlitz <[email protected]> Signed-off-by: Roland Dreier <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: static MagickStatusType ReadPSDMergedImage(Image* image, const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *offsets; MagickStatusType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } offsets=(MagickOffsetType *) NULL; if (compression == RLE) { offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels); if (offsets == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,offsets+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if (image->colorspace == CMYKColorspace) (void) NegateImage(image,MagickFalse); if (offsets != (MagickOffsetType *) NULL) offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets); return(status); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: long Cluster::Load(long long& pos, long& len) const { assert(m_pSegment); assert(m_pos >= m_element_start); if (m_timecode >= 0) //at least partially loaded return 0; assert(m_pos == m_element_start); assert(m_element_size < 0); IMkvReader* const pReader = m_pSegment->m_pReader; long long total, avail; const int status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); assert((total < 0) || (m_pos <= total)); //TODO: verify this pos = m_pos; long long cluster_size = -1; { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error or underflow return static_cast<long>(result); if (result > 0) //underflow (weird) return E_BUFFER_NOT_FULL; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id_ = ReadUInt(pReader, pos, len); if (id_ < 0) //error return static_cast<long>(id_); if (id_ != 0x0F43B675) //Cluster ID return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(cluster_size); if (size == 0) return E_FILE_FORMAT_INVALID; //TODO: verify this pos += len; //consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) cluster_size = size; } //// pos points to start of payload #if 0 len = static_cast<long>(size_); if (cluster_stop > avail) return E_BUFFER_NOT_FULL; #endif long long timecode = -1; long long new_pos = -1; bool bBlock = false; long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size; for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) break; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0) return E_FILE_FORMAT_INVALID; if (id == 0x0F43B675) //Cluster ID break; if (id == 0x0C53BB6B) //Cues ID break; pos += len; //consume ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x67) //TimeCode ID { len = static_cast<long>(size); if ((pos + size) > avail) return E_BUFFER_NOT_FULL; timecode = UnserializeUInt(pReader, pos, size); if (timecode < 0) //error (or underflow) return static_cast<long>(timecode); new_pos = pos + size; if (bBlock) break; } else if (id == 0x20) //BlockGroup ID { bBlock = true; break; } else if (id == 0x23) //SimpleBlock ID { bBlock = true; break; } pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } assert((cluster_stop < 0) || (pos <= cluster_stop)); if (timecode < 0) //no timecode found return E_FILE_FORMAT_INVALID; if (!bBlock) return E_FILE_FORMAT_INVALID; m_pos = new_pos; //designates position just beyond timecode payload m_timecode = timecode; // m_timecode >= 0 means we're partially loaded if (cluster_size >= 0) m_element_size = cluster_stop - m_element_start; return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long Cues::GetCount() const { if (m_cue_points == NULL) return -1; return m_count; //TODO: really ignore preload count? } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: void blk_mq_freeze_queue_start(struct request_queue *q) { int freeze_depth; freeze_depth = atomic_inc_return(&q->mq_freeze_depth); if (freeze_depth == 1) { percpu_ref_kill(&q->mq_usage_counter); blk_mq_run_hw_queues(q, false); } } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BrowserView::SetDownloadShelfVisible(bool visible) { DCHECK(download_shelf_); browser_->UpdateDownloadShelfVisibility(visible); ToolbarSizeChanged(false); } Commit Message: Mac: turn popups into new tabs while in fullscreen. It's platform convention to show popups as new tabs while in non-HTML5 fullscreen. (Popups cause tabs to lose HTML5 fullscreen.) This was implemented for Cocoa in a BrowserWindow override, but it makes sense to just stick it into Browser and remove a ton of override code put in just to support this. BUG=858929, 868416 TEST=as in bugs Change-Id: I43471f242813ec1159d9c690bab73dab3e610b7d Reviewed-on: https://chromium-review.googlesource.com/1153455 Reviewed-by: Sidney San Martín <[email protected]> Commit-Queue: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#578755} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void RegisterPropertiesHandler( void* object, const ImePropertyList& prop_list) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { LOG(ERROR) << "Not on UI thread"; return; } InputMethodLibraryImpl* input_method_library = static_cast<InputMethodLibraryImpl*>(object); input_method_library->RegisterProperties(prop_list); } 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: OnPinStateSet(drive::FileError error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error == drive::FILE_ERROR_OK) { SendResponse(true); } else { SetError(drive::FileErrorToString(error)); SendResponse(false); } } Commit Message: Reland r286968: The CL borrows ShareDialog from Files.app and add it to Gallery. Previous Review URL: https://codereview.chromium.org/431293002 BUG=374667 TEST=manually [email protected], [email protected] Review URL: https://codereview.chromium.org/433733004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286975 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, struct stream *s, struct attr *attr, struct bpacket_attr_vec_arr *vecarr, struct prefix *p, afi_t afi, safi_t safi, struct peer *from, struct prefix_rd *prd, mpls_label_t *label, uint32_t num_labels, int addpath_encode, uint32_t addpath_tx_id) { size_t cp; size_t aspath_sizep; struct aspath *aspath; int send_as4_path = 0; int send_as4_aggregator = 0; int use32bit = (CHECK_FLAG(peer->cap, PEER_CAP_AS4_RCV)) ? 1 : 0; if (!bgp) bgp = peer->bgp; /* Remember current pointer. */ cp = stream_get_endp(s); if (p && !((afi == AFI_IP && safi == SAFI_UNICAST) && !peer_cap_enhe(peer, afi, safi))) { size_t mpattrlen_pos = 0; mpattrlen_pos = bgp_packet_mpattr_start(s, peer, afi, safi, vecarr, attr); bgp_packet_mpattr_prefix(s, afi, safi, p, prd, label, num_labels, addpath_encode, addpath_tx_id, attr); bgp_packet_mpattr_end(s, mpattrlen_pos); } /* Origin attribute. */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ORIGIN); stream_putc(s, 1); stream_putc(s, attr->origin); /* AS path attribute. */ /* If remote-peer is EBGP */ if (peer->sort == BGP_PEER_EBGP && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_AS_PATH_UNCHANGED) || attr->aspath->segments == NULL) && (!CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_RSERVER_CLIENT))) { aspath = aspath_dup(attr->aspath); /* Even though we may not be configured for confederations we * may have * RXed an AS_PATH with AS_CONFED_SEQUENCE or AS_CONFED_SET */ aspath = aspath_delete_confed_seq(aspath); if (CHECK_FLAG(bgp->config, BGP_CONFIG_CONFEDERATION)) { /* Stuff our path CONFED_ID on the front */ aspath = aspath_add_seq(aspath, bgp->confed_id); } else { if (peer->change_local_as) { /* If replace-as is specified, we only use the change_local_as when advertising routes. */ if (!CHECK_FLAG( peer->flags, PEER_FLAG_LOCAL_AS_REPLACE_AS)) { aspath = aspath_add_seq(aspath, peer->local_as); } aspath = aspath_add_seq(aspath, peer->change_local_as); } else { aspath = aspath_add_seq(aspath, peer->local_as); } } } else if (peer->sort == BGP_PEER_CONFED) { /* A confed member, so we need to do the AS_CONFED_SEQUENCE * thing */ aspath = aspath_dup(attr->aspath); aspath = aspath_add_confed_seq(aspath, peer->local_as); } else aspath = attr->aspath; /* If peer is not AS4 capable, then: * - send the created AS_PATH out as AS4_PATH (optional, transitive), * but ensure that no AS_CONFED_SEQUENCE and AS_CONFED_SET path * segment * types are in it (i.e. exclude them if they are there) * AND do this only if there is at least one asnum > 65535 in the * path! * - send an AS_PATH out, but put 16Bit ASnums in it, not 32bit, and * change * all ASnums > 65535 to BGP_AS_TRANS */ stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, use32bit)); /* OLD session may need NEW_AS_PATH sent, if there are 4-byte ASNs * in the path */ if (!use32bit && aspath_has_as4(aspath)) send_as4_path = 1; /* we'll do this later, at the correct place */ /* Nexthop attribute. */ if (afi == AFI_IP && safi == SAFI_UNICAST && !peer_cap_enhe(peer, afi, safi)) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEXT_HOP)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, attr); stream_putc(s, 4); stream_put_ipv4(s, attr->nexthop.s_addr); } else if (peer_cap_enhe(from, afi, safi)) { /* * Likely this is the case when an IPv4 prefix was * received with * Extended Next-hop capability and now being advertised * to * non-ENHE peers. * Setting the mandatory (ipv4) next-hop attribute here * to enable * implicit next-hop self with correct (ipv4 address * family). */ stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_NEXT_HOP); bpacket_attr_vec_arr_set_vec(vecarr, BGP_ATTR_VEC_NH, s, NULL); stream_putc(s, 4); stream_put_ipv4(s, 0); } } /* MED attribute. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_MULTI_EXIT_DISC) || bgp->maxmed_active) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_MULTI_EXIT_DISC); stream_putc(s, 4); stream_putl(s, (bgp->maxmed_active ? bgp->maxmed_value : attr->med)); } /* Local preference. */ if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LOCAL_PREF); stream_putc(s, 4); stream_putl(s, attr->local_pref); } /* Atomic aggregate. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ATOMIC_AGGREGATE)) { stream_putc(s, BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_ATOMIC_AGGREGATE); stream_putc(s, 0); } /* Aggregator. */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR)) { /* Common to BGP_ATTR_AGGREGATOR, regardless of ASN size */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AGGREGATOR); if (use32bit) { /* AS4 capable peer */ stream_putc(s, 8); stream_putl(s, attr->aggregator_as); } else { /* 2-byte AS peer */ stream_putc(s, 6); /* Is ASN representable in 2-bytes? Or must AS_TRANS be * used? */ if (attr->aggregator_as > 65535) { stream_putw(s, BGP_AS_TRANS); /* we have to send AS4_AGGREGATOR, too. * we'll do that later in order to send * attributes in ascending * order. */ send_as4_aggregator = 1; } else stream_putw(s, (uint16_t)attr->aggregator_as); } stream_put_ipv4(s, attr->aggregator_addr.s_addr); } /* Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_COMMUNITIES))) { if (attr->community->size * 4 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putw(s, attr->community->size * 4); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_COMMUNITIES); stream_putc(s, attr->community->size * 4); } stream_put(s, attr->community->val, attr->community->size * 4); } /* * Large Community attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_LARGE_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_LARGE_COMMUNITIES))) { if (lcom_length(attr->lcommunity) > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putw(s, lcom_length(attr->lcommunity)); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_LARGE_COMMUNITIES); stream_putc(s, lcom_length(attr->lcommunity)); } stream_put(s, attr->lcommunity->val, lcom_length(attr->lcommunity)); } /* Route Reflector. */ if (peer->sort == BGP_PEER_IBGP && from && from->sort == BGP_PEER_IBGP) { /* Originator ID. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_ORIGINATOR_ID); stream_putc(s, 4); if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_ORIGINATOR_ID)) stream_put_in_addr(s, &attr->originator_id); else stream_put_in_addr(s, &from->remote_id); /* Cluster list. */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL); stream_putc(s, BGP_ATTR_CLUSTER_LIST); if (attr->cluster) { stream_putc(s, attr->cluster->length + 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); stream_put(s, attr->cluster->list, attr->cluster->length); } else { stream_putc(s, 4); /* If this peer configuration's parent BGP has * cluster_id. */ if (bgp->config & BGP_CONFIG_CLUSTER_ID) stream_put_in_addr(s, &bgp->cluster_id); else stream_put_in_addr(s, &bgp->router_id); } } /* Extended Communities attribute. */ if (CHECK_FLAG(peer->af_flags[afi][safi], PEER_FLAG_SEND_EXT_COMMUNITY) && (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_EXT_COMMUNITIES))) { if (peer->sort == BGP_PEER_IBGP || peer->sort == BGP_PEER_CONFED) { if (attr->ecommunity->size * 8 > 255) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, attr->ecommunity->size * 8); } else { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, attr->ecommunity->size * 8); } stream_put(s, attr->ecommunity->val, attr->ecommunity->size * 8); } else { uint8_t *pnt; int tbit; int ecom_tr_size = 0; int i; for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG(tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; ecom_tr_size++; } if (ecom_tr_size) { if (ecom_tr_size * 8 > 255) { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putw(s, ecom_tr_size * 8); } else { stream_putc( s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_EXT_COMMUNITIES); stream_putc(s, ecom_tr_size * 8); } for (i = 0; i < attr->ecommunity->size; i++) { pnt = attr->ecommunity->val + (i * 8); tbit = *pnt; if (CHECK_FLAG( tbit, ECOMMUNITY_FLAG_NON_TRANSITIVE)) continue; stream_put(s, pnt, 8); } } } } /* Label index attribute. */ if (safi == SAFI_LABELED_UNICAST) { if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PREFIX_SID)) { uint32_t label_index; label_index = attr->label_index; if (label_index != BGP_INVALID_LABEL_INDEX) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PREFIX_SID); stream_putc(s, 10); stream_putc(s, BGP_PREFIX_SID_LABEL_INDEX); stream_putw(s, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); stream_putc(s, 0); // reserved stream_putw(s, 0); // flags stream_putl(s, label_index); } } } if (send_as4_path) { /* If the peer is NOT As4 capable, AND */ /* there are ASnums > 65535 in path THEN * give out AS4_PATH */ /* Get rid of all AS_CONFED_SEQUENCE and AS_CONFED_SET * path segments! * Hm, I wonder... confederation things *should* only be at * the beginning of an aspath, right? Then we should use * aspath_delete_confed_seq for this, because it is already * there! (JK) * Folks, talk to me: what is reasonable here!? */ aspath = aspath_delete_confed_seq(aspath); stream_putc(s, BGP_ATTR_FLAG_TRANS | BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_EXTLEN); stream_putc(s, BGP_ATTR_AS4_PATH); aspath_sizep = stream_get_endp(s); stream_putw(s, 0); stream_putw_at(s, aspath_sizep, aspath_put(s, aspath, 1)); } if (aspath != attr->aspath) aspath_free(aspath); if (send_as4_aggregator) { /* send AS4_AGGREGATOR, at this place */ /* this section of code moved here in order to ensure the * correct * *ascending* order of attributes */ stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_AS4_AGGREGATOR); stream_putc(s, 8); stream_putl(s, attr->aggregator_as); stream_put_ipv4(s, attr->aggregator_addr.s_addr); } if (((afi == AFI_IP || afi == AFI_IP6) && (safi == SAFI_ENCAP || safi == SAFI_MPLS_VPN)) || (afi == AFI_L2VPN && safi == SAFI_EVPN)) { /* Tunnel Encap attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); #if ENABLE_BGP_VNC /* VNC attribute */ bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); #endif } /* PMSI Tunnel */ if (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_PMSI_TUNNEL)) { stream_putc(s, BGP_ATTR_FLAG_OPTIONAL | BGP_ATTR_FLAG_TRANS); stream_putc(s, BGP_ATTR_PMSI_TUNNEL); stream_putc(s, 9); // Length stream_putc(s, 0); // Flags stream_putc(s, PMSI_TNLTYPE_INGR_REPL); // IR (6) stream_put(s, &(attr->label), BGP_LABEL_BYTES); // MPLS Label / VXLAN VNI stream_put_ipv4(s, attr->nexthop.s_addr); } /* Unknown transit attribute. */ if (attr->transit) stream_put(s, attr->transit->val, attr->transit->length); /* Return total size of attribute. */ return stream_get_endp(s) - cp; } Commit Message: bgpd: don't use BGP_ATTR_VNC(255) unless ENABLE_BGP_VNC_ATTR is defined Signed-off-by: Lou Berger <[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: int inet6_sk_rebuild_header(struct sock *sk) { struct ipv6_pinfo *np = inet6_sk(sk); struct dst_entry *dst; dst = __sk_dst_check(sk, np->dst_cookie); if (!dst) { struct inet_sock *inet = inet_sk(sk); struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowlabel = np->flow_label; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); final_p = fl6_update_dst(&fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) { sk->sk_route_caps = 0; sk->sk_err_soft = -PTR_ERR(dst); return PTR_ERR(dst); } __ip6_dst_store(sk, dst, NULL, NULL); } return 0; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: static int iw_random_dither(struct iw_context *ctx, double fraction, int x, int y, int dithersubtype, int channel) { double threshold; threshold = ((double)iwpvt_prng_rand(ctx->prng)) / (double)0xffffffff; if(fraction>=threshold) return 1; return 0; } Commit Message: Fixed a bug that could cause invalid memory to be accessed The bug could happen when transparency is removed from an image. Also fixed a semi-related BMP error handling logic bug. Fixes issue #21 CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: AppCacheDatabase::NamespaceRecord::NamespaceRecord() : cache_id(0) { } 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 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 build_l4proto_icmp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_u8(ct, ATTR_ICMP_TYPE, n, NTA_ICMP_TYPE); ct_build_u8(ct, ATTR_ICMP_CODE, n, NTA_ICMP_CODE); ct_build_u16(ct, ATTR_ICMP_ID, n, NTA_ICMP_ID); ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); } Commit Message: CWE ID: CWE-17 Target: 1 Example 2: Code: static int __init parse_reservelow(char *p) { unsigned long long size; if (!p) return -EINVAL; size = memparse(p, &p); if (size < 4096) size = 4096; if (size > 640*1024) size = 640*1024; reserve_low = size; return 0; } Commit Message: acpi: Disable ACPI table override if securelevel is set From the kernel documentation (initrd_table_override.txt): If the ACPI_INITRD_TABLE_OVERRIDE compile option is true, it is possible to override nearly any ACPI table provided by the BIOS with an instrumented, modified one. When securelevel is set, the kernel should disallow any unauthenticated changes to kernel space. ACPI tables contain code invoked by the kernel, so do not allow ACPI tables to be overridden if securelevel is set. Signed-off-by: Linn Crosetto <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void iwl_sta_ucode_activate(struct iwl_priv *priv, u8 sta_id) { if (!(priv->stations[sta_id].used & IWL_STA_DRIVER_ACTIVE)) IWL_ERR(priv, "ACTIVATE a non DRIVER active station id %u " "addr %pM\n", sta_id, priv->stations[sta_id].sta.sta.addr); if (priv->stations[sta_id].used & IWL_STA_UCODE_ACTIVE) { IWL_DEBUG_ASSOC(priv, "STA id %u addr %pM already present in uCode " "(according to driver)\n", sta_id, priv->stations[sta_id].sta.sta.addr); } else { priv->stations[sta_id].used |= IWL_STA_UCODE_ACTIVE; IWL_DEBUG_ASSOC(priv, "Added STA id %u addr %pM to uCode\n", sta_id, priv->stations[sta_id].sta.sta.addr); } } Commit Message: iwlwifi: Sanity check for sta_id On my testing, I saw some strange behavior [ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00 [ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode not sure how it happen, but adding the sanity check to prevent memory corruption Signed-off-by: Wey-Yi Guy <[email protected]> Signed-off-by: John W. Linville <[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 AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string &element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { *upload_required_ = USE_UPLOAD_RATES; if (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops, struct ofp13_port_stats *ps13) { ofputil_port_stats_to_ofp11(ops, &ps13->ps); ps13->duration_sec = htonl(ops->duration_sec); ps13->duration_nsec = htonl(ops->duration_nsec); } 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: T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( face_index > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* We only set this flag if we have the patented bytecode interpreter. */ /* There are no known `tricky' Type42 fonts that could be loaded with */ /* the unpatented interpreter. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = 0; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY; args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); } Commit Message: CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int WebContentsImpl::DownloadImage( const GURL& url, bool is_favicon, uint32_t max_bitmap_size, bool bypass_cache, const WebContents::ImageDownloadCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static int next_image_download_id = 0; const image_downloader::ImageDownloaderPtr& mojo_image_downloader = GetMainFrame()->GetMojoImageDownloader(); const int download_id = ++next_image_download_id; if (!mojo_image_downloader) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&WebContents::ImageDownloadCallback::Run, base::Owned(new ImageDownloadCallback(callback)), download_id, 400, url, std::vector<SkBitmap>(), std::vector<gfx::Size>())); return download_id; } image_downloader::DownloadRequestPtr req = image_downloader::DownloadRequest::New(); req->url = mojo::String::From(url); req->is_favicon = is_favicon; req->max_bitmap_size = max_bitmap_size; req->bypass_cache = bypass_cache; mojo_image_downloader->DownloadImage( std::move(req), base::Bind(&DidDownloadImage, callback, download_id, url)); return download_id; } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID: Target: 1 Example 2: Code: static int setenv_int(const char *opt, int value) { char buf[16]; sprintf(buf, "%d", value); return setenv(opt, buf, 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: MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1629 CWE ID: CWE-369 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 SoftOpus::onQueueFilled(OMX_U32 portIndex) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mOutputPortSettingsChange != NONE) { return; } if (portIndex == 0 && mInputBufferCount < 3) { BufferInfo *info = *inQueue.begin(); OMX_BUFFERHEADERTYPE *header = info->mHeader; const uint8_t *data = header->pBuffer + header->nOffset; size_t size = header->nFilledLen; if (mInputBufferCount == 0) { CHECK(mHeader == NULL); mHeader = new OpusHeader(); memset(mHeader, 0, sizeof(*mHeader)); if (!ParseOpusHeader(data, size, mHeader)) { ALOGV("Parsing Opus Header failed."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } uint8_t channel_mapping[kMaxChannels] = {0}; if (mHeader->channels <= kMaxChannelsWithDefaultLayout) { memcpy(&channel_mapping, kDefaultOpusChannelLayout, kMaxChannelsWithDefaultLayout); } else { memcpy(&channel_mapping, mHeader->stream_map, mHeader->channels); } int status = OPUS_INVALID_STATE; mDecoder = opus_multistream_decoder_create(kRate, mHeader->channels, mHeader->num_streams, mHeader->num_coupled, channel_mapping, &status); if (!mDecoder || status != OPUS_OK) { ALOGV("opus_multistream_decoder_create failed status=%s", opus_strerror(status)); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } status = opus_multistream_decoder_ctl(mDecoder, OPUS_SET_GAIN(mHeader->gain_db)); if (status != OPUS_OK) { ALOGV("Failed to set OPUS header gain; status=%s", opus_strerror(status)); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } } else if (mInputBufferCount == 1) { mCodecDelay = ns_to_samples( *(reinterpret_cast<int64_t*>(header->pBuffer + header->nOffset)), kRate); mSamplesToDiscard = mCodecDelay; } else { mSeekPreRoll = ns_to_samples( *(reinterpret_cast<int64_t*>(header->pBuffer + header->nOffset)), kRate); notify(OMX_EventPortSettingsChanged, 1, 0, NULL); mOutputPortSettingsChange = AWAITING_DISABLED; } inQueue.erase(inQueue.begin()); info->mOwnedByUs = false; notifyEmptyBufferDone(header); ++mInputBufferCount; return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); return; } BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumFramesOutput = 0; } if (inHeader->nTimeStamp == 0) { mSamplesToDiscard = mCodecDelay; } const uint8_t *data = inHeader->pBuffer + inHeader->nOffset; const uint32_t size = inHeader->nFilledLen; int numFrames = opus_multistream_decode(mDecoder, data, size, (int16_t *)outHeader->pBuffer, kMaxOpusOutputPacketSizeSamples, 0); if (numFrames < 0) { ALOGE("opus_multistream_decode returned %d", numFrames); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } outHeader->nOffset = 0; if (mSamplesToDiscard > 0) { if (mSamplesToDiscard > numFrames) { mSamplesToDiscard -= numFrames; numFrames = 0; } else { numFrames -= mSamplesToDiscard; outHeader->nOffset = mSamplesToDiscard * sizeof(int16_t) * mHeader->channels; mSamplesToDiscard = 0; } } outHeader->nFilledLen = numFrames * sizeof(int16_t) * mHeader->channels; outHeader->nFlags = 0; outHeader->nTimeStamp = mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / kRate; mNumFramesOutput += numFrames; inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } } Commit Message: DO NOT MERGE codecs: check OMX buffer size before use in (vorbis|opus)dec Bug: 27833616 Change-Id: I1ccdd16a00741da072527a6d13e87fd7c7fe8c54 CWE ID: CWE-20 Target: 1 Example 2: Code: int MyProxyGetDelegationReaper(Service *, int exitPid, int exitStatus) { dprintf (D_ALWAYS, "MyProxyGetDelegationReaper pid = %d, rc = %d\n", exitPid, exitStatus); credentials.Rewind(); CredentialWrapper * cred_wrapper; X509CredentialWrapper * matched_entry = NULL; while (credentials.Next (cred_wrapper)) { if (cred_wrapper->cred->GetType() == X509_CREDENTIAL_TYPE) { if (((X509CredentialWrapper*)cred_wrapper)->get_delegation_pid == exitPid) { matched_entry = (X509CredentialWrapper*)cred_wrapper; break; } } } //elihw if (matched_entry) { while (exitStatus != 0) { int read_fd = matched_entry->get_delegation_err_fd; // shorthand off_t offset = lseek(read_fd, 0, SEEK_SET); // rewind if (offset == (off_t)-1) { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "stderr tmp file %s lseek() failed: %s\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), matched_entry->get_delegation_err_filename, strerror(errno) ); break; } struct stat statbuf; int status = fstat(read_fd, &statbuf); if (status == -1) { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "stderr tmp file %s fstat() failed: %s\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), matched_entry->get_delegation_err_filename, strerror(errno) ); break; } matched_entry->get_delegation_err_buff = (char *) calloc ( statbuf.st_size + 1, sizeof(char) ); int bytes_read = read ( read_fd, matched_entry->get_delegation_err_buff, statbuf.st_size ); if (bytes_read < 0 ) { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "stderr tmp file %s read() failed: %s\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), matched_entry->get_delegation_err_filename, strerror(errno) ); break; } if ( WIFEXITED(exitStatus) ) { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "exited with status %d, output (top):\n%s\n\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), WEXITSTATUS(exitStatus), matched_entry->get_delegation_err_buff ); break; } else if ( WIFSIGNALED(exitStatus) ) { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "terminated by signal %d, output (top):\n%s\n\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), WTERMSIG(exitStatus), matched_entry->get_delegation_err_buff ); break; } else { dprintf (D_ALWAYS, "myproxy-get-delegation for proxy (%s, %s), " "unknown status %d, output (top):\n%s\n\n", matched_entry->cred->GetOwner(), matched_entry->cred->GetName(), exitStatus, matched_entry->get_delegation_err_buff ); break; } } // if exitStatus != 0 matched_entry->get_delegation_reset(); } else { dprintf (D_ALWAYS, "Unable to find X509Credential entry for myproxy-get-delegation pid=%d\n", exitPid); } return TRUE; } Commit Message: CWE ID: CWE-134 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 MessageService::OpenChannelToNativeApp( int source_process_id, int source_routing_id, int receiver_port_id, const std::string& source_extension_id, const std::string& native_app_name, const std::string& channel_name, const std::string& connect_message) { content::RenderProcessHost* source = content::RenderProcessHost::FromID(source_process_id); if (!source) return; WebContents* source_contents = tab_util::GetWebContentsByID( source_process_id, source_routing_id); std::string tab_json = "null"; if (source_contents) { scoped_ptr<DictionaryValue> tab_value(ExtensionTabUtil::CreateTabValue( source_contents, ExtensionTabUtil::INCLUDE_PRIVACY_SENSITIVE_FIELDS)); base::JSONWriter::Write(tab_value.get(), &tab_json); } scoped_ptr<MessageChannel> channel(new MessageChannel()); channel->opener.reset(new ExtensionMessagePort(source, MSG_ROUTING_CONTROL, source_extension_id)); NativeMessageProcessHost::MessageType type = channel_name == "chrome.runtime.sendNativeMessage" ? NativeMessageProcessHost::TYPE_SEND_MESSAGE_REQUEST : NativeMessageProcessHost::TYPE_CONNECT; content::BrowserThread::PostTask( content::BrowserThread::FILE, FROM_HERE, base::Bind(&NativeMessageProcessHost::Create, base::WeakPtr<NativeMessageProcessHost::Client>( weak_factory_.GetWeakPtr()), native_app_name, connect_message, receiver_port_id, type, base::Bind(&MessageService::FinalizeOpenChannelToNativeApp, weak_factory_.GetWeakPtr(), receiver_port_id, channel_name, base::Passed(&channel), tab_json))); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
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: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; switch (cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } Commit Message: * Enforce limit of 8K on regex searches that have no limits * Allow the l modifier for regex to mean line count. Default to byte count. If line count is specified, assume a max of 80 characters per line to limit the byte count. * Don't allow conversions to be used for dates, allowing the mask field to be used as an offset. * Bump the version of the magic format so that regex changes are visible. CWE ID: CWE-399 Target: 1 Example 2: Code: static void free_filters_list(struct list_head *filters) { struct perf_addr_filter *filter, *iter; list_for_each_entry_safe(filter, iter, filters, entry) { if (filter->inode) iput(filter->inode); list_del(&filter->entry); kfree(filter); } } Commit Message: perf/core: Fix concurrent sys_perf_event_open() vs. 'move_group' race Di Shen reported a race between two concurrent sys_perf_event_open() calls where both try and move the same pre-existing software group into a hardware context. The problem is exactly that described in commit: f63a8daa5812 ("perf: Fix event->ctx locking") ... where, while we wait for a ctx->mutex acquisition, the event->ctx relation can have changed under us. That very same commit failed to recognise sys_perf_event_context() as an external access vector to the events and thereby didn't apply the established locking rules correctly. So while one sys_perf_event_open() call is stuck waiting on mutex_lock_double(), the other (which owns said locks) moves the group about. So by the time the former sys_perf_event_open() acquires the locks, the context we've acquired is stale (and possibly dead). Apply the established locking rules as per perf_event_ctx_lock_nested() to the mutex_lock_double() for the 'move_group' case. This obviously means we need to validate state after we acquire the locks. Reported-by: Di Shen (Keen Lab) Tested-by: John Dias <[email protected]> Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Alexander Shishkin <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Kees Cook <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Min Chong <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Stephane Eranian <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: Vince Weaver <[email protected]> Fixes: f63a8daa5812 ("perf: Fix event->ctx locking") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void vga_sync_dirty_bitmap(VGACommonState *s) { memory_region_sync_dirty_bitmap(&s->vram); } Commit Message: 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: int sas_discover_sata(struct domain_device *dev) { int res; if (dev->dev_type == SAS_SATA_PM) return -ENODEV; dev->sata_dev.class = sas_get_ata_command_set(dev); sas_fill_in_rphy(dev, dev->rphy); res = sas_notify_lldd_dev_found(dev); if (res) return res; sas_discover_event(dev->port, DISCE_PROBE); return 0; } Commit Message: scsi: libsas: direct call probe and destruct In commit 87c8331fcf72 ("[SCSI] libsas: prevent domain rediscovery competing with ata error handling") introduced disco mutex to prevent rediscovery competing with ata error handling and put the whole revalidation in the mutex. But the rphy add/remove needs to wait for the error handling which also grabs the disco mutex. This may leads to dead lock.So the probe and destruct event were introduce to do the rphy add/remove asynchronously and out of the lock. The asynchronously processed workers makes the whole discovery process not atomic, the other events may interrupt the process. For example, if a loss of signal event inserted before the probe event, the sas_deform_port() is called and the port will be deleted. And sas_port_delete() may run before the destruct event, but the port-x:x is the top parent of end device or expander. This leads to a kernel WARNING such as: [ 82.042979] sysfs group 'power' not found for kobject 'phy-1:0:22' [ 82.042983] ------------[ cut here ]------------ [ 82.042986] WARNING: CPU: 54 PID: 1714 at fs/sysfs/group.c:237 sysfs_remove_group+0x94/0xa0 [ 82.043059] Call trace: [ 82.043082] [<ffff0000082e7624>] sysfs_remove_group+0x94/0xa0 [ 82.043085] [<ffff00000864e320>] dpm_sysfs_remove+0x60/0x70 [ 82.043086] [<ffff00000863ee10>] device_del+0x138/0x308 [ 82.043089] [<ffff00000869a2d0>] sas_phy_delete+0x38/0x60 [ 82.043091] [<ffff00000869a86c>] do_sas_phy_delete+0x6c/0x80 [ 82.043093] [<ffff00000863dc20>] device_for_each_child+0x58/0xa0 [ 82.043095] [<ffff000008696f80>] sas_remove_children+0x40/0x50 [ 82.043100] [<ffff00000869d1bc>] sas_destruct_devices+0x64/0xa0 [ 82.043102] [<ffff0000080e93bc>] process_one_work+0x1fc/0x4b0 [ 82.043104] [<ffff0000080e96c0>] worker_thread+0x50/0x490 [ 82.043105] [<ffff0000080f0364>] kthread+0xfc/0x128 [ 82.043107] [<ffff0000080836c0>] ret_from_fork+0x10/0x50 Make probe and destruct a direct call in the disco and revalidate function, but put them outside the lock. The whole discovery or revalidate won't be interrupted by other events. And the DISCE_PROBE and DISCE_DESTRUCT event are deleted as a result of the direct call. Introduce a new list to destruct the sas_port and put the port delete after the destruct. This makes sure the right order of destroying the sysfs kobject and fix the warning above. In sas_ex_revalidate_domain() have a loop to find all broadcasted device, and sometimes we have a chance to find the same expander twice. Because the sas_port will be deleted at the end of the whole revalidate process, sas_port with the same name cannot be added before this. Otherwise the sysfs will complain of creating duplicate filename. Since the LLDD will send broadcast for every device change, we can only process one expander's revalidation. [mkp: kbuild test robot warning] Signed-off-by: Jason Yan <[email protected]> CC: John Garry <[email protected]> CC: Johannes Thumshirn <[email protected]> CC: Ewan Milne <[email protected]> CC: Christoph Hellwig <[email protected]> CC: Tomas Henzl <[email protected]> CC: Dan Williams <[email protected]> Reviewed-by: Hannes Reinecke <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: Target: 1 Example 2: Code: static void bt_free(struct blk_mq_bitmap_tags *bt) { kfree(bt->map); kfree(bt->bs); } Commit Message: blk-mq: fix race between timeout and freeing request Inside timeout handler, blk_mq_tag_to_rq() is called to retrieve the request from one tag. This way is obviously wrong because the request can be freed any time and some fiedds of the request can't be trusted, then kernel oops might be triggered[1]. Currently wrt. blk_mq_tag_to_rq(), the only special case is that the flush request can share same tag with the request cloned from, and the two requests can't be active at the same time, so this patch fixes the above issue by updating tags->rqs[tag] with the active request(either flush rq or the request cloned from) of the tag. Also blk_mq_tag_to_rq() gets much simplified with this patch. Given blk_mq_tag_to_rq() is mainly for drivers and the caller must make sure the request can't be freed, so in bt_for_each() this helper is replaced with tags->rqs[tag]. [1] kernel oops log [ 439.696220] BUG: unable to handle kernel NULL pointer dereference at 0000000000000158^M [ 439.697162] IP: [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.700653] PGD 7ef765067 PUD 7ef764067 PMD 0 ^M [ 439.700653] Oops: 0000 [#1] PREEMPT SMP DEBUG_PAGEALLOC ^M [ 439.700653] Dumping ftrace buffer:^M [ 439.700653] (ftrace buffer empty)^M [ 439.700653] Modules linked in: nbd ipv6 kvm_intel kvm serio_raw^M [ 439.700653] CPU: 6 PID: 2779 Comm: stress-ng-sigfd Not tainted 4.2.0-rc5-next-20150805+ #265^M [ 439.730500] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011^M [ 439.730500] task: ffff880605308000 ti: ffff88060530c000 task.ti: ffff88060530c000^M [ 439.730500] RIP: 0010:[<ffffffff812d89ba>] [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.730500] RSP: 0018:ffff880819203da0 EFLAGS: 00010283^M [ 439.730500] RAX: ffff880811b0e000 RBX: ffff8800bb465f00 RCX: 0000000000000002^M [ 439.730500] RDX: 0000000000000000 RSI: 0000000000000202 RDI: 0000000000000000^M [ 439.730500] RBP: ffff880819203db0 R08: 0000000000000002 R09: 0000000000000000^M [ 439.730500] R10: 0000000000000000 R11: 0000000000000000 R12: 0000000000000202^M [ 439.730500] R13: ffff880814104800 R14: 0000000000000002 R15: ffff880811a2ea00^M [ 439.730500] FS: 00007f165b3f5740(0000) GS:ffff880819200000(0000) knlGS:0000000000000000^M [ 439.730500] CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b^M [ 439.730500] CR2: 0000000000000158 CR3: 00000007ef766000 CR4: 00000000000006e0^M [ 439.730500] Stack:^M [ 439.730500] 0000000000000008 ffff8808114eed90 ffff880819203e00 ffffffff812dc104^M [ 439.755663] ffff880819203e40 ffffffff812d9f5e 0000020000000000 ffff8808114eed80^M [ 439.755663] Call Trace:^M [ 439.755663] <IRQ> ^M [ 439.755663] [<ffffffff812dc104>] bt_for_each+0x6e/0xc8^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812d9f5e>] ? blk_mq_rq_timed_out+0x6a/0x6a^M [ 439.755663] [<ffffffff812dc1b3>] blk_mq_tag_busy_iter+0x55/0x5e^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff812d8911>] blk_mq_rq_timer+0x5d/0xd4^M [ 439.755663] [<ffffffff810a3e10>] call_timer_fn+0xf7/0x284^M [ 439.755663] [<ffffffff810a3d1e>] ? call_timer_fn+0x5/0x284^M [ 439.755663] [<ffffffff812d88b4>] ? blk_mq_bio_to_request+0x38/0x38^M [ 439.755663] [<ffffffff810a46d6>] run_timer_softirq+0x1ce/0x1f8^M [ 439.755663] [<ffffffff8104c367>] __do_softirq+0x181/0x3a4^M [ 439.755663] [<ffffffff8104c76e>] irq_exit+0x40/0x94^M [ 439.755663] [<ffffffff81031482>] smp_apic_timer_interrupt+0x33/0x3e^M [ 439.755663] [<ffffffff815559a4>] apic_timer_interrupt+0x84/0x90^M [ 439.755663] <EOI> ^M [ 439.755663] [<ffffffff81554350>] ? _raw_spin_unlock_irq+0x32/0x4a^M [ 439.755663] [<ffffffff8106a98b>] finish_task_switch+0xe0/0x163^M [ 439.755663] [<ffffffff8106a94d>] ? finish_task_switch+0xa2/0x163^M [ 439.755663] [<ffffffff81550066>] __schedule+0x469/0x6cd^M [ 439.755663] [<ffffffff8155039b>] schedule+0x82/0x9a^M [ 439.789267] [<ffffffff8119b28b>] signalfd_read+0x186/0x49a^M [ 439.790911] [<ffffffff8106d86a>] ? wake_up_q+0x47/0x47^M [ 439.790911] [<ffffffff811618c2>] __vfs_read+0x28/0x9f^M [ 439.790911] [<ffffffff8117a289>] ? __fget_light+0x4d/0x74^M [ 439.790911] [<ffffffff811620a7>] vfs_read+0x7a/0xc6^M [ 439.790911] [<ffffffff8116292b>] SyS_read+0x49/0x7f^M [ 439.790911] [<ffffffff81554c17>] entry_SYSCALL_64_fastpath+0x12/0x6f^M [ 439.790911] Code: 48 89 e5 e8 a9 b8 e7 ff 5d c3 0f 1f 44 00 00 55 89 f2 48 89 e5 41 54 41 89 f4 53 48 8b 47 60 48 8b 1c d0 48 8b 7b 30 48 8b 53 38 <48> 8b 87 58 01 00 00 48 85 c0 75 09 48 8b 97 88 0c 00 00 eb 10 ^M [ 439.790911] RIP [<ffffffff812d89ba>] blk_mq_tag_to_rq+0x21/0x6e^M [ 439.790911] RSP <ffff880819203da0>^M [ 439.790911] CR2: 0000000000000158^M [ 439.790911] ---[ end trace d40af58949325661 ]---^M Cc: <[email protected]> Signed-off-by: Ming Lei <[email protected]> Signed-off-by: Jens Axboe <[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: pgm_print(netdissect_options *ndo, register const u_char *bp, register u_int length, register const u_char *bp2) { register const struct pgm_header *pgm; register const struct ip *ip; register char ch; uint16_t sport, dport; u_int nla_afnum; char nla_buf[INET6_ADDRSTRLEN]; register const struct ip6_hdr *ip6; uint8_t opt_type, opt_len; uint32_t seq, opts_len, len, offset; pgm = (const struct pgm_header *)bp; ip = (const struct ip *)bp2; if (IP_V(ip) == 6) ip6 = (const struct ip6_hdr *)bp2; else ip6 = NULL; ch = '\0'; if (!ND_TTEST(pgm->pgm_dport)) { if (ip6) { ND_PRINT((ndo, "%s > %s: [|pgm]", ip6addr_string(ndo, &ip6->ip6_src), ip6addr_string(ndo, &ip6->ip6_dst))); return; } else { ND_PRINT((ndo, "%s > %s: [|pgm]", ipaddr_string(ndo, &ip->ip_src), ipaddr_string(ndo, &ip->ip_dst))); return; } } sport = EXTRACT_16BITS(&pgm->pgm_sport); dport = EXTRACT_16BITS(&pgm->pgm_dport); if (ip6) { if (ip6->ip6_nxt == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ip6addr_string(ndo, &ip6->ip6_src), tcpport_string(ndo, sport), ip6addr_string(ndo, &ip6->ip6_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } else { if (ip->ip_p == IPPROTO_PGM) { ND_PRINT((ndo, "%s.%s > %s.%s: ", ipaddr_string(ndo, &ip->ip_src), tcpport_string(ndo, sport), ipaddr_string(ndo, &ip->ip_dst), tcpport_string(ndo, dport))); } else { ND_PRINT((ndo, "%s > %s: ", tcpport_string(ndo, sport), tcpport_string(ndo, dport))); } } ND_TCHECK(*pgm); ND_PRINT((ndo, "PGM, length %u", EXTRACT_16BITS(&pgm->pgm_length))); if (!ndo->ndo_vflag) return; ND_PRINT((ndo, " 0x%02x%02x%02x%02x%02x%02x ", pgm->pgm_gsid[0], pgm->pgm_gsid[1], pgm->pgm_gsid[2], pgm->pgm_gsid[3], pgm->pgm_gsid[4], pgm->pgm_gsid[5])); switch (pgm->pgm_type) { case PGM_SPM: { const struct pgm_spm *spm; spm = (const struct pgm_spm *)(pgm + 1); ND_TCHECK(*spm); bp = (const u_char *) (spm + 1); switch (EXTRACT_16BITS(&spm->pgms_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, "SPM seq %u trail %u lead %u nla %s", EXTRACT_32BITS(&spm->pgms_seq), EXTRACT_32BITS(&spm->pgms_trailseq), EXTRACT_32BITS(&spm->pgms_leadseq), nla_buf)); break; } case PGM_POLL: { const struct pgm_poll *poll_msg; poll_msg = (const struct pgm_poll *)(pgm + 1); ND_TCHECK(*poll_msg); ND_PRINT((ndo, "POLL seq %u round %u", EXTRACT_32BITS(&poll_msg->pgmp_seq), EXTRACT_16BITS(&poll_msg->pgmp_round))); bp = (const u_char *) (poll_msg + 1); break; } case PGM_POLR: { const struct pgm_polr *polr; uint32_t ivl, rnd, mask; polr = (const struct pgm_polr *)(pgm + 1); ND_TCHECK(*polr); bp = (const u_char *) (polr + 1); switch (EXTRACT_16BITS(&polr->pgmp_nla_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } ND_TCHECK2(*bp, sizeof(uint32_t)); ivl = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); rnd = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_TCHECK2(*bp, sizeof(uint32_t)); mask = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, "POLR seq %u round %u nla %s ivl %u rnd 0x%08x " "mask 0x%08x", EXTRACT_32BITS(&polr->pgmp_seq), EXTRACT_16BITS(&polr->pgmp_round), nla_buf, ivl, rnd, mask)); break; } case PGM_ODATA: { const struct pgm_data *odata; odata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*odata); ND_PRINT((ndo, "ODATA trail %u seq %u", EXTRACT_32BITS(&odata->pgmd_trailseq), EXTRACT_32BITS(&odata->pgmd_seq))); bp = (const u_char *) (odata + 1); break; } case PGM_RDATA: { const struct pgm_data *rdata; rdata = (const struct pgm_data *)(pgm + 1); ND_TCHECK(*rdata); ND_PRINT((ndo, "RDATA trail %u seq %u", EXTRACT_32BITS(&rdata->pgmd_trailseq), EXTRACT_32BITS(&rdata->pgmd_seq))); bp = (const u_char *) (rdata + 1); break; } case PGM_NAK: case PGM_NULLNAK: case PGM_NCF: { const struct pgm_nak *nak; char source_buf[INET6_ADDRSTRLEN], group_buf[INET6_ADDRSTRLEN]; nak = (const struct pgm_nak *)(pgm + 1); ND_TCHECK(*nak); bp = (const u_char *) (nak + 1); /* * Skip past the source, saving info along the way * and stopping if we don't have enough. */ switch (EXTRACT_16BITS(&nak->pgmn_source_afi)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, source_buf, sizeof(source_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Skip past the group, saving info along the way * and stopping if we don't have enough. */ bp += (2 * sizeof(uint16_t)); switch (EXTRACT_16BITS(bp)) { case AFNUM_INET: ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in_addr); break; case AFNUM_INET6: ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, group_buf, sizeof(group_buf)); bp += sizeof(struct in6_addr); break; default: goto trunc; break; } /* * Options decoding can go here. */ switch (pgm->pgm_type) { case PGM_NAK: ND_PRINT((ndo, "NAK ")); break; case PGM_NULLNAK: ND_PRINT((ndo, "NNAK ")); break; case PGM_NCF: ND_PRINT((ndo, "NCF ")); break; default: break; } ND_PRINT((ndo, "(%s -> %s), seq %u", source_buf, group_buf, EXTRACT_32BITS(&nak->pgmn_seq))); break; } case PGM_ACK: { const struct pgm_ack *ack; ack = (const struct pgm_ack *)(pgm + 1); ND_TCHECK(*ack); ND_PRINT((ndo, "ACK seq %u", EXTRACT_32BITS(&ack->pgma_rx_max_seq))); bp = (const u_char *) (ack + 1); break; } case PGM_SPMR: ND_PRINT((ndo, "SPMR")); break; default: ND_PRINT((ndo, "UNKNOWN type 0x%02x", pgm->pgm_type)); break; } if (pgm->pgm_options & PGM_OPT_BIT_PRESENT) { /* * make sure there's enough for the first option header */ if (!ND_TTEST2(*bp, PGM_MIN_OPT_LEN)) { ND_PRINT((ndo, "[|OPT]")); return; } /* * That option header MUST be an OPT_LENGTH option * (see the first paragraph of section 9.1 in RFC 3208). */ opt_type = *bp++; if ((opt_type & PGM_OPT_MASK) != PGM_OPT_LENGTH) { ND_PRINT((ndo, "[First option bad, should be PGM_OPT_LENGTH, is %u]", opt_type & PGM_OPT_MASK)); return; } opt_len = *bp++; if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } opts_len = EXTRACT_16BITS(bp); if (opts_len < 4) { ND_PRINT((ndo, "[Bad total option length %u < 4]", opts_len)); return; } bp += sizeof(uint16_t); ND_PRINT((ndo, " OPTS LEN %d", opts_len)); opts_len -= 4; while (opts_len) { if (opts_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, 2)) { ND_PRINT((ndo, " [|OPT]")); return; } opt_type = *bp++; opt_len = *bp++; if (opt_len < PGM_MIN_OPT_LEN) { ND_PRINT((ndo, "[Bad option, length %u < %u]", opt_len, PGM_MIN_OPT_LEN)); break; } if (opts_len < opt_len) { ND_PRINT((ndo, "[Total option length leaves no room for final option]")); return; } if (!ND_TTEST2(*bp, opt_len - 2)) { ND_PRINT((ndo, " [|OPT]")); return; } switch (opt_type & PGM_OPT_MASK) { case PGM_OPT_LENGTH: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_LENGTH option, length %u != 4]", opt_len)); return; } ND_PRINT((ndo, " OPTS LEN (extra?) %d", EXTRACT_16BITS(bp))); bp += sizeof(uint16_t); opts_len -= 4; break; case PGM_OPT_FRAGMENT: if (opt_len != 16) { ND_PRINT((ndo, "[Bad OPT_FRAGMENT option, length %u != 16]", opt_len)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); offset = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); len = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " FRAG seq %u off %u len %u", seq, offset, len)); opts_len -= 16; break; case PGM_OPT_NAK_LIST: bp += 2; opt_len -= sizeof(uint32_t); /* option header */ ND_PRINT((ndo, " NAK LIST")); while (opt_len) { if (opt_len < sizeof(uint32_t)) { ND_PRINT((ndo, "[Option length not a multiple of 4]")); return; } ND_TCHECK2(*bp, sizeof(uint32_t)); ND_PRINT((ndo, " %u", EXTRACT_32BITS(bp))); bp += sizeof(uint32_t); opt_len -= sizeof(uint32_t); opts_len -= sizeof(uint32_t); } break; case PGM_OPT_JOIN: if (opt_len != 8) { ND_PRINT((ndo, "[Bad OPT_JOIN option, length %u != 8]", opt_len)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " JOIN %u", seq)); opts_len -= 8; break; case PGM_OPT_NAK_BO_IVL: if (opt_len != 12) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_IVL option, length %u != 12]", opt_len)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); seq = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " BACKOFF ivl %u ivlseq %u", offset, seq)); opts_len -= 12; break; case PGM_OPT_NAK_BO_RNG: if (opt_len != 12) { ND_PRINT((ndo, "[Bad OPT_NAK_BO_RNG option, length %u != 12]", opt_len)); return; } bp += 2; offset = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); seq = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " BACKOFF max %u min %u", offset, seq)); opts_len -= 12; break; case PGM_OPT_REDIRECT: bp += 2; nla_afnum = EXTRACT_16BITS(bp); bp += (2 * sizeof(uint16_t)); switch (nla_afnum) { case AFNUM_INET: if (opt_len != 4 + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= 4 + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != 4 + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_REDIRECT option, length %u != 4 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= 4 + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " REDIRECT %s", nla_buf)); break; case PGM_OPT_PARITY_PRM: if (opt_len != 8) { ND_PRINT((ndo, "[Bad OPT_PARITY_PRM option, length %u != 8]", opt_len)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " PARITY MAXTGS %u", len)); opts_len -= 8; break; case PGM_OPT_PARITY_GRP: if (opt_len != 8) { ND_PRINT((ndo, "[Bad OPT_PARITY_GRP option, length %u != 8]", opt_len)); return; } bp += 2; seq = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " PARITY GROUP %u", seq)); opts_len -= 8; break; case PGM_OPT_CURR_TGSIZE: if (opt_len != 8) { ND_PRINT((ndo, "[Bad OPT_CURR_TGSIZE option, length %u != 8]", opt_len)); return; } bp += 2; len = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); ND_PRINT((ndo, " PARITY ATGS %u", len)); opts_len -= 8; break; case PGM_OPT_NBR_UNREACH: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_NBR_UNREACH option, length %u != 4]", opt_len)); return; } bp += 2; ND_PRINT((ndo, " NBR_UNREACH")); opts_len -= 4; break; case PGM_OPT_PATH_NLA: ND_PRINT((ndo, " PATH_NLA [%d]", opt_len)); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_SYN: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_SYN option, length %u != 4]", opt_len)); return; } bp += 2; ND_PRINT((ndo, " SYN")); opts_len -= 4; break; case PGM_OPT_FIN: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_FIN option, length %u != 4]", opt_len)); return; } bp += 2; ND_PRINT((ndo, " FIN")); opts_len -= 4; break; case PGM_OPT_RST: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_RST option, length %u != 4]", opt_len)); return; } bp += 2; ND_PRINT((ndo, " RST")); opts_len -= 4; break; case PGM_OPT_CR: ND_PRINT((ndo, " CR")); bp += opt_len; opts_len -= opt_len; break; case PGM_OPT_CRQST: if (opt_len != 4) { ND_PRINT((ndo, "[Bad OPT_CRQST option, length %u != 4]", opt_len)); return; } bp += 2; ND_PRINT((ndo, " CRQST")); opts_len -= 4; break; case PGM_OPT_PGMCC_DATA: bp += 2; offset = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); nla_afnum = EXTRACT_16BITS(bp); bp += (2 * sizeof(uint16_t)); switch (nla_afnum) { case AFNUM_INET: if (opt_len != 12 + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= 12 + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != 12 + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= 12 + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC DATA %u %s", offset, nla_buf)); break; case PGM_OPT_PGMCC_FEEDBACK: bp += 2; offset = EXTRACT_32BITS(bp); bp += sizeof(uint32_t); nla_afnum = EXTRACT_16BITS(bp); bp += (2 * sizeof(uint16_t)); switch (nla_afnum) { case AFNUM_INET: if (opt_len != 12 + sizeof(struct in_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in_addr)); addrtostr(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in_addr); opts_len -= 12 + sizeof(struct in_addr); break; case AFNUM_INET6: if (opt_len != 12 + sizeof(struct in6_addr)) { ND_PRINT((ndo, "[Bad OPT_PGMCC_DATA option, length %u != 12 + address size]", opt_len)); return; } ND_TCHECK2(*bp, sizeof(struct in6_addr)); addrtostr6(bp, nla_buf, sizeof(nla_buf)); bp += sizeof(struct in6_addr); opts_len -= 12 + sizeof(struct in6_addr); break; default: goto trunc; break; } ND_PRINT((ndo, " PGMCC FEEDBACK %u %s", offset, nla_buf)); break; default: ND_PRINT((ndo, " OPT_%02X [%d] ", opt_type, opt_len)); bp += opt_len; opts_len -= opt_len; break; } if (opt_type & PGM_OPT_END) break; } } ND_PRINT((ndo, " [%u]", length)); if (ndo->ndo_packettype == PT_PGM_ZMTP1 && (pgm->pgm_type == PGM_ODATA || pgm->pgm_type == PGM_RDATA)) zmtp1_print_datagram(ndo, bp, EXTRACT_16BITS(&pgm->pgm_length)); return; trunc: ND_PRINT((ndo, "[|pgm]")); if (ch != '\0') ND_PRINT((ndo, ">")); } Commit Message: CVE-2017-13019: Clean up PGM option processing. Add #defines for option lengths or the lengths of the fixed-length part of the option. Sometimes those #defines differ from what was there before; what was there before was wrong, probably because the option lengths given in RFC 3208 were sometimes wrong - some lengths included the length of the option header, some lengths didn't. Don't use "sizeof(uintXX_t)" for sizes in the packet, just use the number of bytes directly. For the options that include an IPv4 or IPv6 address, check the option length against the length of what precedes the address before fetching any of that data. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. 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: long dgnc_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned long flags; void __user *uarg = (void __user *)arg; switch (cmd) { case DIGI_GETDD: { /* * This returns the total number of boards * in the system, as well as driver version * and has space for a reserved entry */ struct digi_dinfo ddi; spin_lock_irqsave(&dgnc_global_lock, flags); ddi.dinfo_nboards = dgnc_NumBoards; sprintf(ddi.dinfo_version, "%s", DG_PART); spin_unlock_irqrestore(&dgnc_global_lock, flags); if (copy_to_user(uarg, &ddi, sizeof(ddi))) return -EFAULT; break; } case DIGI_GETBD: { int brd; struct digi_info di; if (copy_from_user(&brd, uarg, sizeof(int))) return -EFAULT; if (brd < 0 || brd >= dgnc_NumBoards) return -ENODEV; memset(&di, 0, sizeof(di)); di.info_bdnum = brd; spin_lock_irqsave(&dgnc_Board[brd]->bd_lock, flags); di.info_bdtype = dgnc_Board[brd]->dpatype; di.info_bdstate = dgnc_Board[brd]->dpastatus; di.info_ioport = 0; di.info_physaddr = (ulong)dgnc_Board[brd]->membase; di.info_physsize = (ulong)dgnc_Board[brd]->membase - dgnc_Board[brd]->membase_end; if (dgnc_Board[brd]->state != BOARD_FAILED) di.info_nports = dgnc_Board[brd]->nasync; else di.info_nports = 0; spin_unlock_irqrestore(&dgnc_Board[brd]->bd_lock, flags); if (copy_to_user(uarg, &di, sizeof(di))) return -EFAULT; break; } case DIGI_GET_NI_INFO: { struct channel_t *ch; struct ni_info ni; unsigned char mstat = 0; uint board = 0; uint channel = 0; if (copy_from_user(&ni, uarg, sizeof(ni))) return -EFAULT; board = ni.board; channel = ni.channel; /* Verify boundaries on board */ if (board >= dgnc_NumBoards) return -ENODEV; /* Verify boundaries on channel */ if (channel >= dgnc_Board[board]->nasync) return -ENODEV; ch = dgnc_Board[board]->channels[channel]; if (!ch || ch->magic != DGNC_CHANNEL_MAGIC) return -ENODEV; memset(&ni, 0, sizeof(ni)); ni.board = board; ni.channel = channel; spin_lock_irqsave(&ch->ch_lock, flags); mstat = (ch->ch_mostat | ch->ch_mistat); if (mstat & UART_MCR_DTR) { ni.mstat |= TIOCM_DTR; ni.dtr = TIOCM_DTR; } if (mstat & UART_MCR_RTS) { ni.mstat |= TIOCM_RTS; ni.rts = TIOCM_RTS; } if (mstat & UART_MSR_CTS) { ni.mstat |= TIOCM_CTS; ni.cts = TIOCM_CTS; } if (mstat & UART_MSR_RI) { ni.mstat |= TIOCM_RI; ni.ri = TIOCM_RI; } if (mstat & UART_MSR_DCD) { ni.mstat |= TIOCM_CD; ni.dcd = TIOCM_CD; } if (mstat & UART_MSR_DSR) ni.mstat |= TIOCM_DSR; ni.iflag = ch->ch_c_iflag; ni.oflag = ch->ch_c_oflag; ni.cflag = ch->ch_c_cflag; ni.lflag = ch->ch_c_lflag; if (ch->ch_digi.digi_flags & CTSPACE || ch->ch_c_cflag & CRTSCTS) ni.hflow = 1; else ni.hflow = 0; if ((ch->ch_flags & CH_STOPI) || (ch->ch_flags & CH_FORCED_STOPI)) ni.recv_stopped = 1; else ni.recv_stopped = 0; if ((ch->ch_flags & CH_STOP) || (ch->ch_flags & CH_FORCED_STOP)) ni.xmit_stopped = 1; else ni.xmit_stopped = 0; ni.curtx = ch->ch_txcount; ni.currx = ch->ch_rxcount; ni.baud = ch->ch_old_baud; spin_unlock_irqrestore(&ch->ch_lock, flags); if (copy_to_user(uarg, &ni, sizeof(ni))) return -EFAULT; break; } } return 0; } Commit Message: staging/dgnc: fix info leak in ioctl The dgnc_mgmt_ioctl() code fails to initialize the 16 _reserved bytes of struct digi_dinfo after the ->dinfo_nboards member. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Salva Peiró <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: iasecc_init(struct sc_card *card) { struct sc_context *ctx = card->ctx; struct iasecc_private_data *private_data = NULL; int rv = SC_ERROR_NO_CARD_SUPPORT; LOG_FUNC_CALLED(ctx); private_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data)); if (private_data == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); card->cla = 0x00; card->drv_data = private_data; if (card->type == SC_CARD_TYPE_IASECC_GEMALTO) rv = iasecc_init_gemalto(card); else if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) rv = iasecc_init_oberthur(card); else if (card->type == SC_CARD_TYPE_IASECC_SAGEM) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_AMOS) rv = iasecc_init_amos_or_sagem(card); else if (card->type == SC_CARD_TYPE_IASECC_MI) rv = iasecc_init_amos_or_sagem(card); else LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD); if (!rv) { if (card->ef_atr && card->ef_atr->aid.len) { struct sc_path path; memset(&path, 0, sizeof(struct sc_path)); path.type = SC_PATH_TYPE_DF_NAME; memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len); path.len = card->ef_atr->aid.len; rv = iasecc_select_file(card, &path, NULL); sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv); LOG_TEST_RET(ctx, rv, "Select EF.ATR AID failed"); } rv = iasecc_get_serialnr(card, NULL); } #ifdef ENABLE_SM card->sm_ctx.ops.read_binary = _iasecc_sm_read_binary; card->sm_ctx.ops.update_binary = _iasecc_sm_update_binary; #endif if (!rv) { sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len)); rv = SC_ERROR_INVALID_CARD; } LOG_FUNC_RETURN(ctx, rv); } 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: OMX_ERRORTYPE SoftAVCEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *) params; if (bitRate->nPortIndex != 1 || bitRate->eControlRate != OMX_Video_ControlRateVariable) { return OMX_ErrorUndefined; } mBitrate = bitRate->nTargetBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcType = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcType->nPortIndex != 1) { return OMX_ErrorUndefined; } if (avcType->eProfile != OMX_VIDEO_AVCProfileBaseline || avcType->nRefFrames != 1 || avcType->nBFrames != 0 || avcType->bUseHadamard != OMX_TRUE || (avcType->nAllowedPictureTypes & OMX_VIDEO_PictureTypeB) != 0 || avcType->nRefIdx10ActiveMinus1 != 0 || avcType->nRefIdx11ActiveMinus1 != 0 || avcType->bWeightedPPrediction != OMX_FALSE || avcType->bEntropyCodingCABAC != OMX_FALSE || avcType->bconstIpred != OMX_FALSE || avcType->bDirect8x8Inference != OMX_FALSE || avcType->bDirectSpatialTemporal != OMX_FALSE || avcType->nCabacInitIdc != 0) { return OMX_ErrorUndefined; } if (OK != ConvertOmxAvcLevelToAvcSpecLevel(avcType->eLevel, &mAVCEncLevel)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: PredictorEncodeRow(TIFF* tif, uint8* bp, tmsize_t cc, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encoderow != NULL); /* XXX horizontal differencing alters user's data XXX */ (*sp->encodepfunc)(tif, bp, cc); return (*sp->encoderow)(tif, bp, cc, s); } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119 Target: 1 Example 2: Code: LIBOPENMPT_MODPLUG_API char ModPlug_ExportS3M(ModPlugFile* file, const char* filepath) { (void)file; /* not implemented */ fprintf(stderr,"libopenmpt-modplug: error: ModPlug_ExportS3M(%s) not implemented.\n",filepath); return 0; } Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-120 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len) { const sp<ProcessState> proc(ProcessState::self()); status_t err; const uint8_t *data = parcel->mData; const binder_size_t *objects = parcel->mObjects; size_t size = parcel->mObjectsSize; int startPos = mDataPos; int firstIndex = -1, lastIndex = -2; if (len == 0) { return NO_ERROR; } if ((offset > parcel->mDataSize) || (len > parcel->mDataSize) || (offset + len > parcel->mDataSize)) { return BAD_VALUE; } for (int i = 0; i < (int) size; i++) { size_t off = objects[i]; if ((off >= offset) && (off < offset + len)) { if (firstIndex == -1) { firstIndex = i; } lastIndex = i; } } int numObjects = lastIndex - firstIndex + 1; if ((mDataSize+len) > mDataCapacity) { err = growData(len); if (err != NO_ERROR) { return err; } } memcpy(mData + mDataPos, data + offset, len); mDataPos += len; mDataSize += len; err = NO_ERROR; if (numObjects > 0) { if (mObjectsCapacity < mObjectsSize + numObjects) { int newSize = ((mObjectsSize + numObjects)*3)/2; binder_size_t *objects = (binder_size_t*)realloc(mObjects, newSize*sizeof(binder_size_t)); if (objects == (binder_size_t*)0) { return NO_MEMORY; } mObjects = objects; mObjectsCapacity = newSize; } int idx = mObjectsSize; for (int i = firstIndex; i <= lastIndex; i++) { size_t off = objects[i] - offset + startPos; mObjects[idx++] = off; mObjectsSize++; flat_binder_object* flat = reinterpret_cast<flat_binder_object*>(mData + off); acquire_object(proc, *flat, this); if (flat->type == BINDER_TYPE_FD) { flat->handle = dup(flat->handle); flat->cookie = 1; mHasFds = mFdsKnown = true; if (!mAllowFds) { err = FDS_NOT_ALLOWED; } } } } return err; } Commit Message: Disregard alleged binder entities beyond parcel bounds When appending one parcel's contents to another, ignore binder objects within the source Parcel that appear to lie beyond the formal bounds of that Parcel's data buffer. Bug 17312693 Change-Id: If592a260f3fcd9a56fc160e7feb2c8b44c73f514 (cherry picked from commit 27182be9f20f4f5b48316666429f09b9ecc1f22e) 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 FindBarController::UpdateFindBarForCurrentResult() { FindManager* find_manager = tab_contents_->GetFindManager(); const FindNotificationDetails& find_result = find_manager->find_result(); if (find_result.number_of_matches() > -1) { if (last_reported_matchcount_ > 0 && find_result.number_of_matches() == 1 && !find_result.final_update()) return; // Don't let interim result override match count. last_reported_matchcount_ = find_result.number_of_matches(); } find_bar_->UpdateUIForFindResult(find_result, find_manager->find_text()); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc) { /* * TODO take core out of low power mode when that's * implemented. */ if (dwc->gadget_driver && dwc->gadget_driver->resume) { spin_unlock(&dwc->lock); dwc->gadget_driver->resume(&dwc->gadget); spin_lock(&dwc->lock); } } Commit Message: usb: dwc3: gadget: never call ->complete() from ->ep_queue() This is a requirement which has always existed but, somehow, wasn't reflected in the documentation and problems weren't found until now when Tuba Yavuz found a possible deadlock happening between dwc3 and f_hid. She described the situation as follows: spin_lock_irqsave(&hidg->write_spinlock, flags); // first acquire /* we our function has been disabled by host */ if (!hidg->req) { free_ep_req(hidg->in_ep, hidg->req); goto try_again; } [...] status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC); => [...] => usb_gadget_giveback_request => f_hidg_req_complete => spin_lock_irqsave(&hidg->write_spinlock, flags); // second acquire Note that this happens because dwc3 would call ->complete() on a failed usb_ep_queue() due to failed Start Transfer command. This is, anyway, a theoretical situation because dwc3 currently uses "No Response Update Transfer" command for Bulk and Interrupt endpoints. It's still good to make this case impossible to happen even if the "No Reponse Update Transfer" command is changed. Reported-by: Tuba Yavuz <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: _PUBLIC_ char *strupper_talloc_n_handle(struct smb_iconv_handle *iconv_handle, TALLOC_CTX *ctx, const char *src, size_t n) { size_t size=0; char *dest; if (!src) { return NULL; } /* this takes advantage of the fact that upper/lower can't change the length of a character by more than 1 byte */ dest = talloc_array(ctx, char, 2*(n+1)); if (dest == NULL) { return NULL; } while (n-- && *src) { size_t c_size; codepoint_t c = next_codepoint_handle(iconv_handle, src, &c_size); src += c_size; c = toupper_m(c); c_size = push_codepoint_handle(iconv_handle, dest+size, c); if (c_size == -1) { talloc_free(dest); return NULL; } size += c_size; } dest[size] = 0; /* trim it so talloc_append_string() works */ dest = talloc_realloc(ctx, dest, char, size+1); talloc_set_name_const(dest, dest); return dest; } Commit Message: CWE ID: CWE-200 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node, struct stop *stops, int maxcount) { fz_colorspace *colorspace; float sample[8]; float rgb[3]; int before, after; int count; int i; /* We may have to insert 2 extra stops when postprocessing */ maxcount -= 2; count = 0; while (node && count < maxcount) { if (!strcmp(fz_xml_tag(node), "GradientStop")) { char *offset = fz_xml_att(node, "Offset"); char *color = fz_xml_att(node, "Color"); if (offset && color) { stops[count].offset = fz_atof(offset); stops[count].index = count; xps_parse_color(doc, base_uri, color, &colorspace, sample); fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1); stops[count].r = rgb[0]; stops[count].g = rgb[1]; stops[count].b = rgb[2]; stops[count].a = sample[0]; count ++; } } node = fz_xml_next(node); } if (count == 0) { fz_warn(doc->ctx, "gradient brush has no gradient stops"); stops[0].offset = 0; stops[0].r = 0; stops[0].g = 0; stops[0].b = 0; stops[0].a = 1; stops[1].offset = 1; stops[1].r = 1; stops[1].g = 1; stops[1].b = 1; stops[1].a = 1; return 2; } if (count == maxcount) fz_warn(doc->ctx, "gradient brush exceeded maximum number of gradient stops"); /* Postprocess to make sure the range of offsets is 0.0 to 1.0 */ qsort(stops, count, sizeof(struct stop), cmp_stop); before = -1; after = -1; for (i = 0; i < count; i++) { if (stops[i].offset < 0) before = i; if (stops[i].offset > 1) { after = i; break; } } /* Remove all stops < 0 except the largest one */ if (before > 0) { memmove(stops, stops + before, (count - before) * sizeof(struct stop)); count -= before; } /* Remove all stops > 1 except the smallest one */ if (after >= 0) count = after + 1; /* Expand single stop to 0 .. 1 */ if (count == 1) { stops[1] = stops[0]; stops[0].offset = 0; stops[1].offset = 1; return 2; } /* First stop < 0 -- interpolate value to 0 */ if (stops[0].offset < 0) { float d = -stops[0].offset / (stops[1].offset - stops[0].offset); stops[0].offset = 0; stops[0].r = lerp(stops[0].r, stops[1].r, d); stops[0].g = lerp(stops[0].g, stops[1].g, d); stops[0].b = lerp(stops[0].b, stops[1].b, d); stops[0].a = lerp(stops[0].a, stops[1].a, d); } /* Last stop > 1 -- interpolate value to 1 */ if (stops[count-1].offset > 1) { float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset); stops[count-1].offset = 1; stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d); stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d); stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d); stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d); } /* First stop > 0 -- insert a duplicate at 0 */ if (stops[0].offset > 0) { memmove(stops + 1, stops, count * sizeof(struct stop)); stops[0] = stops[1]; stops[0].offset = 0; count++; } /* Last stop < 1 -- insert a duplicate at 1 */ if (stops[count-1].offset < 1) { stops[count] = stops[count-1]; stops[count].offset = 1; count++; } return count; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static u16 get_segment_reg(struct task_struct *task, unsigned long offset) { /* * Returning the value truncates it to 16 bits. */ unsigned int seg; switch (offset) { case offsetof(struct user_regs_struct, fs): if (task == current) { /* Older gas can't assemble movq %?s,%r?? */ asm("movl %%fs,%0" : "=r" (seg)); return seg; } return task->thread.fsindex; case offsetof(struct user_regs_struct, gs): if (task == current) { asm("movl %%gs,%0" : "=r" (seg)); return seg; } return task->thread.gsindex; case offsetof(struct user_regs_struct, ds): if (task == current) { asm("movl %%ds,%0" : "=r" (seg)); return seg; } return task->thread.ds; case offsetof(struct user_regs_struct, es): if (task == current) { asm("movl %%es,%0" : "=r" (seg)); return seg; } return task->thread.es; case offsetof(struct user_regs_struct, cs): case offsetof(struct user_regs_struct, ss): break; } return *pt_regs_access(task_pt_regs(task), offset); } 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: void Editor::changeSelectionAfterCommand( const SelectionInDOMTree& newSelection, FrameSelection::SetSelectionOptions options) { if (newSelection.isNone()) return; bool selectionDidNotChangeDOMPosition = newSelection == frame().selection().selectionInDOMTree(); frame().selection().setSelection(newSelection, options); if (selectionDidNotChangeDOMPosition) { client().respondToChangedSelection( m_frame, frame() .selection() .computeVisibleSelectionInDOMTreeDeprecated() .getSelectionType()); } } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID: 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 CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { SetState(STATE_NORMAL); ui::MouseEvent synthetic_event( ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); NotifyClick(synthetic_event); return true; } Commit Message: Custom buttons should only handle accelerators when focused. BUG=541415 Review URL: https://codereview.chromium.org/1437523005 Cr-Commit-Position: refs/heads/master@{#360130} CWE ID: CWE-254 Target: 1 Example 2: Code: static int find_sys_file(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name) { struct mspack_system *sys = self->system; struct mschmd_file result; /* already loaded */ if (*f_ptr) return MSPACK_ERR_OK; /* try using fast_find to find the file - return DATAFORMAT error if * it fails, or successfully doesn't find the file */ if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm, name, &result, (int)sizeof(result)) || !result.section) { return MSPACK_ERR_DATAFORMAT; } if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) { return MSPACK_ERR_NOMEMORY; } /* copy result */ *(*f_ptr) = result; (*f_ptr)->filename = (char *) name; /* link file into sysfiles list */ (*f_ptr)->next = sec->base.chm->sysfiles; sec->base.chm->sysfiles = *f_ptr; return MSPACK_ERR_OK; } Commit Message: Avoid returning CHM file entries that are "blank" because they have embedded null bytes 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 rose_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct rose_sock *rose = rose_sk(sk); struct sockaddr_rose *addr = (struct sockaddr_rose *)uaddr; struct net_device *dev; ax25_address *source; ax25_uid_assoc *user; int n; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr_len != sizeof(struct sockaddr_rose) && addr_len != sizeof(struct full_sockaddr_rose)) return -EINVAL; if (addr->srose_family != AF_ROSE) return -EINVAL; if (addr_len == sizeof(struct sockaddr_rose) && addr->srose_ndigis > 1) return -EINVAL; if ((unsigned int) addr->srose_ndigis > ROSE_MAX_DIGIS) return -EINVAL; if ((dev = rose_dev_get(&addr->srose_addr)) == NULL) { SOCK_DEBUG(sk, "ROSE: bind failed: invalid address\n"); return -EADDRNOTAVAIL; } source = &addr->srose_call; user = ax25_findbyuid(current_euid()); if (user) { rose->source_call = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE)) return -EACCES; rose->source_call = *source; } rose->source_addr = addr->srose_addr; rose->device = dev; rose->source_ndigis = addr->srose_ndigis; if (addr_len == sizeof(struct full_sockaddr_rose)) { struct full_sockaddr_rose *full_addr = (struct full_sockaddr_rose *)uaddr; for (n = 0 ; n < addr->srose_ndigis ; n++) rose->source_digis[n] = full_addr->srose_digis[n]; } else { if (rose->source_ndigis == 1) { rose->source_digis[0] = addr->srose_digi; } } rose_insert_socket(sk); sock_reset_flag(sk, SOCK_ZAPPED); SOCK_DEBUG(sk, "ROSE: socket is bound\n"); return 0; } Commit Message: rose: Add length checks to CALL_REQUEST parsing Define some constant offsets for CALL_REQUEST based on the description at <http://www.techfest.com/networking/wan/x25plp.htm> and the definition of ROSE as using 10-digit (5-byte) addresses. Use them consistently. Validate all implicit and explicit facilities lengths. Validate the address length byte rather than either trusting or assuming its value. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int getStrrtokenPos(char* str, int savedPos) { int result =-1; int i; for(i=savedPos-1; i>=0; i--) { if(isIDSeparator(*(str+i)) ){ /* delimiter found; check for singleton */ if(i>=2 && isIDSeparator(*(str+i-2)) ){ /* a singleton; so send the position of token before the singleton */ result = i-2; } else { result = i; } break; } } if(result < 1){ /* Just in case inavlid locale e.g. '-x-xyz' or '-sl_Latn' */ result =-1; } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125 Target: 1 Example 2: Code: static int tcm_loop_device_reset(struct scsi_cmnd *sc) { struct se_cmd *se_cmd = NULL; struct se_portal_group *se_tpg; struct se_session *se_sess; struct tcm_loop_cmd *tl_cmd = NULL; struct tcm_loop_hba *tl_hba; struct tcm_loop_nexus *tl_nexus; struct tcm_loop_tmr *tl_tmr = NULL; struct tcm_loop_tpg *tl_tpg; int ret = FAILED; /* * Locate the tcm_loop_hba_t pointer */ tl_hba = *(struct tcm_loop_hba **)shost_priv(sc->device->host); /* * Locate the tl_nexus and se_sess pointers */ tl_nexus = tl_hba->tl_nexus; if (!tl_nexus) { printk(KERN_ERR "Unable to perform device reset without" " active I_T Nexus\n"); return FAILED; } se_sess = tl_nexus->se_sess; /* * Locate the tl_tpg and se_tpg pointers from TargetID in sc->device->id */ tl_tpg = &tl_hba->tl_hba_tpgs[sc->device->id]; se_tpg = &tl_tpg->tl_se_tpg; tl_cmd = kmem_cache_zalloc(tcm_loop_cmd_cache, GFP_KERNEL); if (!tl_cmd) { printk(KERN_ERR "Unable to allocate memory for tl_cmd\n"); return FAILED; } tl_tmr = kzalloc(sizeof(struct tcm_loop_tmr), GFP_KERNEL); if (!tl_tmr) { printk(KERN_ERR "Unable to allocate memory for tl_tmr\n"); goto release; } init_waitqueue_head(&tl_tmr->tl_tmr_wait); se_cmd = &tl_cmd->tl_se_cmd; /* * Initialize struct se_cmd descriptor from target_core_mod infrastructure */ transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, 0, DMA_NONE, MSG_SIMPLE_TAG, &tl_cmd->tl_sense_buf[0]); /* * Allocate the LUN_RESET TMR */ se_cmd->se_tmr_req = core_tmr_alloc_req(se_cmd, tl_tmr, TMR_LUN_RESET); if (IS_ERR(se_cmd->se_tmr_req)) goto release; /* * Locate the underlying TCM struct se_lun from sc->device->lun */ if (transport_lookup_tmr_lun(se_cmd, sc->device->lun) < 0) goto release; /* * Queue the TMR to TCM Core and sleep waiting for tcm_loop_queue_tm_rsp() * to wake us up. */ transport_generic_handle_tmr(se_cmd); wait_event(tl_tmr->tl_tmr_wait, atomic_read(&tl_tmr->tmr_complete)); /* * The TMR LUN_RESET has completed, check the response status and * then release allocations. */ ret = (se_cmd->se_tmr_req->response == TMR_FUNCTION_COMPLETE) ? SUCCESS : FAILED; release: if (se_cmd) transport_generic_free_cmd(se_cmd, 1, 0); else kmem_cache_free(tcm_loop_cmd_cache, tl_cmd); kfree(tl_tmr); return ret; } Commit Message: loopback: off by one in tcm_loop_make_naa_tpg() This is an off by one 'tgpt' check in tcm_loop_make_naa_tpg() that could result in memory corruption. Signed-off-by: Dan Carpenter <[email protected]> Signed-off-by: Nicholas A. Bellinger <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 AppCacheUpdateJob::DiscardDuplicateResponses() { storage_->DoomResponses(manifest_url_, duplicate_response_ids_); } Commit Message: AppCache: fix a browser crashing bug that can happen during updates. BUG=558589 Review URL: https://codereview.chromium.org/1463463003 Cr-Commit-Position: refs/heads/master@{#360967} CWE ID: 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 SimplifiedBackwardsTextIterator::handleTextNode() { m_lastTextNode = m_node; int startOffset; int offsetInNode; RenderText* renderer = handleFirstLetter(startOffset, offsetInNode); if (!renderer) return true; String text = renderer->text(); if (!renderer->firstTextBox() && text.length() > 0) return true; m_positionEndOffset = m_offset; m_offset = startOffset + offsetInNode; m_positionNode = m_node; m_positionStartOffset = m_offset; ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length())); ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length())); ASSERT(m_positionStartOffset <= m_positionEndOffset); m_textLength = m_positionEndOffset - m_positionStartOffset; m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode); ASSERT(m_textCharacters >= text.characters()); ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length())); m_lastCharacter = text[m_positionEndOffset - 1]; return !m_shouldHandleFirstLetter; } Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure. BUG=156930,177197 [email protected] Review URL: https://codereview.chromium.org/15057010 git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 Target: 1 Example 2: Code: exsltDateDayOfWeekInMonth (const xmlChar *dateTime) { exsltDateValPtr dt; long ret; if (dateTime == NULL) { #ifdef WITH_TIME dt = exsltDateCurrent(); if (dt == NULL) #endif return xmlXPathNAN; } else { dt = exsltDateParse(dateTime); if (dt == NULL) return xmlXPathNAN; if ((dt->type != XS_DATETIME) && (dt->type != XS_DATE)) { exsltDateFreeDate(dt); return xmlXPathNAN; } } ret = ((dt->value.date.day -1) / 7) + 1; exsltDateFreeDate(dt); return (double) ret; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { int id = ctxt->input->id; SKIP(3); SKIP_BLANKS; if (CMP7(CUR_PTR, 'I', 'N', 'C', 'L', 'U', 'D', 'E')) { SKIP(7); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering INCLUDE Conditional Section\n"); } while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || (NXT(2) != '>'))) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving INCLUDE Conditional Section\n"); } } else if (CMP6(CUR_PTR, 'I', 'G', 'N', 'O', 'R', 'E')) { int state; xmlParserInputState instate; int depth = 0; SKIP(6); SKIP_BLANKS; if (RAW != '[') { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } NEXT; } if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Entering IGNORE Conditional Section\n"); } /* * Parse up to the end of the conditional section * But disable SAX event generating DTD building in the meantime */ state = ctxt->disableSAX; instate = ctxt->instate; if (ctxt->recovery == 0) ctxt->disableSAX = 1; ctxt->instate = XML_PARSER_IGNORE; while ((depth >= 0) && (RAW != 0)) { if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { depth++; SKIP(3); continue; } if ((RAW == ']') && (NXT(1) == ']') && (NXT(2) == '>')) { if (--depth >= 0) SKIP(3); continue; } NEXT; continue; } ctxt->disableSAX = state; ctxt->instate = instate; if (xmlParserDebugEntities) { if ((ctxt->input != NULL) && (ctxt->input->filename)) xmlGenericError(xmlGenericErrorContext, "%s(%d): ", ctxt->input->filename, ctxt->input->line); xmlGenericError(xmlGenericErrorContext, "Leaving IGNORE Conditional Section\n"); } } else { xmlFatalErr(ctxt, XML_ERR_CONDSEC_INVALID_KEYWORD, NULL); } if (RAW == 0) SHRINK; if (RAW == 0) { xmlFatalErr(ctxt, XML_ERR_CONDSEC_NOT_FINISHED, NULL); } else { if (ctxt->input->id != id) { xmlValidityError(ctxt, XML_ERR_ENTITY_BOUNDARY, "All markup of the conditional section is not in the same entity\n", NULL, NULL); } SKIP(3); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void InitNavigateParams(FrameHostMsg_DidCommitProvisionalLoad_Params* params, int nav_entry_id, bool did_create_new_entry, const GURL& url, ui::PageTransition transition) { params->nav_entry_id = nav_entry_id; params->url = url; params->referrer = Referrer(); params->transition = transition; params->redirects = std::vector<GURL>(); params->should_update_history = false; params->searchable_form_url = GURL(); params->searchable_form_encoding = std::string(); params->did_create_new_entry = did_create_new_entry; params->gesture = NavigationGestureUser; params->was_within_same_document = false; params->method = "GET"; params->page_state = PageState::CreateFromURL(url); } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <[email protected]> Reviewed-by: Charles Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254 Target: 1 Example 2: Code: free_certauth_handles(krb5_context context, certauth_handle *list) { int i; if (list == NULL) return; for (i = 0; list[i] != NULL; i++) { if (list[i]->vt.fini != NULL) list[i]->vt.fini(context, list[i]->moddata); free(list[i]); } free(list); } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 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: void pdf_summarize( FILE *fp, const pdf_t *pdf, const char *name, pdf_flag_t flags) { int i, j, page, n_versions, n_entries; FILE *dst, *out; char *dst_name, *c; dst = NULL; dst_name = NULL; if (name) { dst_name = malloc(strlen(name) * 2 + 16); sprintf(dst_name, "%s/%s", name, name); if ((c = strrchr(dst_name, '.')) && (strncmp(c, ".pdf", 4) == 0)) *c = '\0'; strcat(dst_name, ".summary"); if (!(dst = fopen(dst_name, "w"))) { ERR("Could not open file '%s' for writing\n", dst_name); return; } } /* Send output to file or stdout */ out = (dst) ? dst : stdout; /* Count versions */ n_versions = pdf->n_xrefs; if (n_versions && pdf->xrefs[0].is_linear) --n_versions; /* Ignore bad xref entry */ for (i=1; i<pdf->n_xrefs; ++i) if (pdf->xrefs[i].end == 0) --n_versions; /* If we have no valid versions but linear, count that */ if (!pdf->n_xrefs || (!n_versions && pdf->xrefs[0].is_linear)) n_versions = 1; /* Compare each object (if we dont have xref streams) */ n_entries = 0; for (i=0; !(const int)pdf->has_xref_streams && i<pdf->n_xrefs; i++) { if (flags & PDF_FLAG_QUIET) continue; for (j=0; j<pdf->xrefs[i].n_entries; j++) { ++n_entries; fprintf(out, "%s: --%c-- Version %d -- Object %d (%s)", pdf->name, pdf_get_object_status(pdf, i, j), pdf->xrefs[i].version, pdf->xrefs[i].entries[j].obj_id, get_type(fp, pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i])); /* TODO page = get_page(pdf->xrefs[i].entries[j].obj_id, &pdf->xrefs[i]); */ if (0 /*page*/) fprintf(out, " Page(%d)\n", page); else fprintf(out, "\n"); } } /* Trailing summary */ if (!(flags & PDF_FLAG_QUIET)) { /* Let the user know that we cannot we print a per-object summary. * If we have a 1.5 PDF using streams for xref, we have not objects * to display, so let the user know whats up. */ if (pdf->has_xref_streams || !n_entries) fprintf(out, "%s: This PDF contains potential cross reference streams.\n" "%s: An object summary is not available.\n", pdf->name, pdf->name); fprintf(out, "---------- %s ----------\n" "Versions: %d\n", pdf->name, n_versions); /* Count entries for summary */ if (!pdf->has_xref_streams) for (i=0; i<pdf->n_xrefs; i++) { if (pdf->xrefs[i].is_linear) continue; n_entries = pdf->xrefs[i].n_entries; /* If we are a linearized PDF, all versions are made from those * objects too. So count em' */ if (pdf->xrefs[0].is_linear) n_entries += pdf->xrefs[0].n_entries; if (pdf->xrefs[i].version && n_entries) fprintf(out, "Version %d -- %d objects\n", pdf->xrefs[i].version, n_entries); } } else /* Quiet output */ fprintf(out, "%s: %d\n", pdf->name, n_versions); if (dst) { fclose(dst); free(dst_name); } } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787 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: ssize_t socket_write(const socket_t *socket, const void *buf, size_t count) { assert(socket != NULL); assert(buf != NULL); return send(socket->fd, buf, count, MSG_DONTWAIT); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284 Target: 1 Example 2: Code: static struct sk_buff *alloc_tx(struct atm_vcc *vcc, unsigned int size) { struct sk_buff *skb; struct sock *sk = sk_atm(vcc); if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) { pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n", sk_wmem_alloc_get(sk), size, sk->sk_sndbuf); return NULL; } while (!(skb = alloc_skb(size, GFP_KERNEL))) schedule(); pr_debug("%d += %d\n", sk_wmem_alloc_get(sk), skb->truesize); atomic_add(skb->truesize, &sk->sk_wmem_alloc); return skb; } Commit Message: atm: update msg_namelen in vcc_recvmsg() The current code does not fill the msg_name member in case it is set. It also does not set 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. Fix that by simply setting msg_namelen to 0 as obviously nobody cared about vcc_recvmsg() not filling the msg_name in case it was set. 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: UINT CSoundFile::GetSongComments(LPSTR s, UINT len, UINT linesize) { LPCSTR p = m_lpszSongComments; if (!p) return 0; UINT i = 2, ln=0; if ((len) && (s)) s[0] = '\x0D'; if ((len > 1) && (s)) s[1] = '\x0A'; while ((*p) && (i+2 < len)) { BYTE c = (BYTE)*p++; if ((c == 0x0D) || ((c == ' ') && (ln >= linesize))) { if (s) { s[i++] = '\x0D'; s[i++] = '\x0A'; } else i+= 2; ln=0; } else if (c >= 0x20) { if (s) s[i++] = c; else i++; ln++; } } if (s) s[i] = 0; return i; } 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: static uint64_t ReadBits(BitReader* reader, int num_bits) { DCHECK_GE(reader->bits_available(), num_bits); DCHECK((num_bits > 0) && (num_bits <= 64)); uint64_t value; reader->ReadBits(num_bits, &value); return value; } Commit Message: Cleanup media BitReader ReadBits() calls Initialize temporary values, check return values. Small tweaks to solution proposed by [email protected]. Bug: 929962 Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735 Reviewed-on: https://chromium-review.googlesource.com/c/1481085 Commit-Queue: Chrome Cunningham <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#634889} CWE ID: CWE-200 Target: 1 Example 2: Code: void BrowserWindowGtk::UpdateLoadingAnimations(bool should_animate) { if (should_animate) { if (!loading_animation_timer_.IsRunning()) { loading_animation_timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this, &BrowserWindowGtk::LoadingAnimationCallback); } } else { if (loading_animation_timer_.IsRunning()) { loading_animation_timer_.Stop(); LoadingAnimationCallback(); } } } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int dev_addr_add_multiple(struct net_device *to_dev, struct net_device *from_dev, unsigned char addr_type) { int err; ASSERT_RTNL(); if (from_dev->addr_len != to_dev->addr_len) return -EINVAL; err = __hw_addr_add_multiple(&to_dev->dev_addrs, &from_dev->dev_addrs, to_dev->addr_len, addr_type); if (!err) call_netdevice_notifiers(NETDEV_CHANGEADDR, to_dev); return err; } 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 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 packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { net_warn_ratelimited("Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && (int)(req->tp_block_size - BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } Commit Message: packet: fix race condition in packet_set_ring When packet_set_ring creates a ring buffer it will initialize a struct timer_list if the packet version is TPACKET_V3. This value can then be raced by a different thread calling setsockopt to set the version to TPACKET_V1 before packet_set_ring has finished. This leads to a use-after-free on a function pointer in the struct timer_list when the socket is closed as the previously initialized timer will not be deleted. The bug is fixed by taking lock_sock(sk) in packet_setsockopt when changing the packet version while also taking the lock at the start of packet_set_ring. Fixes: f6fb8f100b80 ("af-packet: TPACKET_V3 flexible buffer implementation.") Signed-off-by: Philip Pettersson <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl) { DTLS_RECORD_LAYER *d; if ((d = OPENSSL_malloc(sizeof(*d))) == NULL) return (0); rl->d = d; d->unprocessed_rcds.q = pqueue_new(); d->processed_rcds.q = pqueue_new(); d->buffered_app_data.q = pqueue_new(); if (d->unprocessed_rcds.q == NULL || d->processed_rcds.q == NULL || d->buffered_app_data.q == NULL) { pqueue_free(d->unprocessed_rcds.q); pqueue_free(d->processed_rcds.q); pqueue_free(d->buffered_app_data.q); OPENSSL_free(d); rl->d = NULL; return (0); } return 1; } 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: struct file *get_empty_filp(void) { const struct cred *cred = current_cred(); static long old_max; struct file *f; int error; /* * Privileged users can go above max_files */ if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) { /* * percpu_counters are inaccurate. Do an expensive check before * we go and fail. */ if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files) goto over; } f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL); if (unlikely(!f)) return ERR_PTR(-ENOMEM); percpu_counter_inc(&nr_files); f->f_cred = get_cred(cred); error = security_file_alloc(f); if (unlikely(error)) { file_free(f); return ERR_PTR(error); } INIT_LIST_HEAD(&f->f_u.fu_list); atomic_long_set(&f->f_count, 1); rwlock_init(&f->f_owner.lock); spin_lock_init(&f->f_lock); eventpoll_init_file(f); /* f->f_version: 0 */ return f; over: /* Ran out of filps - report that */ if (get_nr_files() > old_max) { pr_info("VFS: file-max limit %lu reached\n", get_max_files()); old_max = get_nr_files(); } return ERR_PTR(-ENFILE); } 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:
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 * CAPSTONE_API cs_winkernel_malloc(size_t size) { NT_ASSERT(size); #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory CS_WINKERNEL_MEMBLOCK *block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, size + sizeof(CS_WINKERNEL_MEMBLOCK), CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; } Commit Message: provide a validity check to prevent against Integer overflow conditions (#870) * provide a validity check to prevent against Integer overflow conditions * fix some style issues. CWE ID: CWE-190 Target: 1 Example 2: Code: bool Editor::InsertText(const String& text, KeyboardEvent* triggering_event) { return GetFrame().GetEventHandler().HandleTextInputEvent(text, triggering_event); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} 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 InstallablePaymentAppCrawler::OnPaymentMethodManifestParsed( const GURL& method_manifest_url, const std::vector<GURL>& default_applications, const std::vector<url::Origin>& supported_origins, bool all_origins_supported) { number_of_payment_method_manifest_to_parse_--; if (web_contents() == nullptr) return; content::PermissionManager* permission_manager = web_contents()->GetBrowserContext()->GetPermissionManager(); if (permission_manager == nullptr) return; for (const auto& url : default_applications) { if (downloaded_web_app_manifests_.find(url) != downloaded_web_app_manifests_.end()) { continue; } if (permission_manager->GetPermissionStatus( content::PermissionType::PAYMENT_HANDLER, url.GetOrigin(), url.GetOrigin()) != blink::mojom::PermissionStatus::GRANTED) { continue; } number_of_web_app_manifest_to_download_++; downloaded_web_app_manifests_.insert(url); downloader_->DownloadWebAppManifest( url, base::BindOnce( &InstallablePaymentAppCrawler::OnPaymentWebAppManifestDownloaded, weak_ptr_factory_.GetWeakPtr(), method_manifest_url, url)); } FinishCrawlingPaymentAppsIfReady(); } Commit Message: [Payments] Restrict just-in-time payment handler to payment method domain and its subdomains Bug: 853937 Change-Id: I148b3d96950a9d90fa362e580e9593caa6b92a36 Reviewed-on: https://chromium-review.googlesource.com/1132116 Reviewed-by: Mathieu Perreault <[email protected]> Commit-Queue: Ganggui Tang <[email protected]> Cr-Commit-Position: refs/heads/master@{#573911} 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 OPJ_BOOL bmp_read_info_header(FILE* IN, OPJ_BITMAPINFOHEADER* header) { memset(header, 0, sizeof(*header)); /* INFO HEADER */ /* ------------- */ header->biSize = (OPJ_UINT32)getc(IN); header->biSize |= (OPJ_UINT32)getc(IN) << 8; header->biSize |= (OPJ_UINT32)getc(IN) << 16; header->biSize |= (OPJ_UINT32)getc(IN) << 24; switch (header->biSize) { case 12U: /* BITMAPCOREHEADER */ case 40U: /* BITMAPINFOHEADER */ case 52U: /* BITMAPV2INFOHEADER */ case 56U: /* BITMAPV3INFOHEADER */ case 108U: /* BITMAPV4HEADER */ case 124U: /* BITMAPV5HEADER */ break; default: fprintf(stderr, "Error, unknown BMP header size %d\n", header->biSize); return OPJ_FALSE; } header->biWidth = (OPJ_UINT32)getc(IN); header->biWidth |= (OPJ_UINT32)getc(IN) << 8; header->biWidth |= (OPJ_UINT32)getc(IN) << 16; header->biWidth |= (OPJ_UINT32)getc(IN) << 24; header->biHeight = (OPJ_UINT32)getc(IN); header->biHeight |= (OPJ_UINT32)getc(IN) << 8; header->biHeight |= (OPJ_UINT32)getc(IN) << 16; header->biHeight |= (OPJ_UINT32)getc(IN) << 24; header->biPlanes = (OPJ_UINT16)getc(IN); header->biPlanes |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); header->biBitCount = (OPJ_UINT16)getc(IN); header->biBitCount |= (OPJ_UINT16)((OPJ_UINT32)getc(IN) << 8); if (header->biSize >= 40U) { header->biCompression = (OPJ_UINT32)getc(IN); header->biCompression |= (OPJ_UINT32)getc(IN) << 8; header->biCompression |= (OPJ_UINT32)getc(IN) << 16; header->biCompression |= (OPJ_UINT32)getc(IN) << 24; header->biSizeImage = (OPJ_UINT32)getc(IN); header->biSizeImage |= (OPJ_UINT32)getc(IN) << 8; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 16; header->biSizeImage |= (OPJ_UINT32)getc(IN) << 24; header->biXpelsPerMeter = (OPJ_UINT32)getc(IN); header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biXpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biYpelsPerMeter = (OPJ_UINT32)getc(IN); header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 8; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 16; header->biYpelsPerMeter |= (OPJ_UINT32)getc(IN) << 24; header->biClrUsed = (OPJ_UINT32)getc(IN); header->biClrUsed |= (OPJ_UINT32)getc(IN) << 8; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 16; header->biClrUsed |= (OPJ_UINT32)getc(IN) << 24; header->biClrImportant = (OPJ_UINT32)getc(IN); header->biClrImportant |= (OPJ_UINT32)getc(IN) << 8; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 16; header->biClrImportant |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 56U) { header->biRedMask = (OPJ_UINT32)getc(IN); header->biRedMask |= (OPJ_UINT32)getc(IN) << 8; header->biRedMask |= (OPJ_UINT32)getc(IN) << 16; header->biRedMask |= (OPJ_UINT32)getc(IN) << 24; header->biGreenMask = (OPJ_UINT32)getc(IN); header->biGreenMask |= (OPJ_UINT32)getc(IN) << 8; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 16; header->biGreenMask |= (OPJ_UINT32)getc(IN) << 24; header->biBlueMask = (OPJ_UINT32)getc(IN); header->biBlueMask |= (OPJ_UINT32)getc(IN) << 8; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 16; header->biBlueMask |= (OPJ_UINT32)getc(IN) << 24; header->biAlphaMask = (OPJ_UINT32)getc(IN); header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 8; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 16; header->biAlphaMask |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 108U) { header->biColorSpaceType = (OPJ_UINT32)getc(IN); header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 8; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 16; header->biColorSpaceType |= (OPJ_UINT32)getc(IN) << 24; if (fread(&(header->biColorSpaceEP), 1U, sizeof(header->biColorSpaceEP), IN) != sizeof(header->biColorSpaceEP)) { fprintf(stderr, "Error, can't read BMP header\n"); return OPJ_FALSE; } header->biRedGamma = (OPJ_UINT32)getc(IN); header->biRedGamma |= (OPJ_UINT32)getc(IN) << 8; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 16; header->biRedGamma |= (OPJ_UINT32)getc(IN) << 24; header->biGreenGamma = (OPJ_UINT32)getc(IN); header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 8; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 16; header->biGreenGamma |= (OPJ_UINT32)getc(IN) << 24; header->biBlueGamma = (OPJ_UINT32)getc(IN); header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 8; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 16; header->biBlueGamma |= (OPJ_UINT32)getc(IN) << 24; } if (header->biSize >= 124U) { header->biIntent = (OPJ_UINT32)getc(IN); header->biIntent |= (OPJ_UINT32)getc(IN) << 8; header->biIntent |= (OPJ_UINT32)getc(IN) << 16; header->biIntent |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileData = (OPJ_UINT32)getc(IN); header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileData |= (OPJ_UINT32)getc(IN) << 24; header->biIccProfileSize = (OPJ_UINT32)getc(IN); header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 8; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 16; header->biIccProfileSize |= (OPJ_UINT32)getc(IN) << 24; header->biReserved = (OPJ_UINT32)getc(IN); header->biReserved |= (OPJ_UINT32)getc(IN) << 8; header->biReserved |= (OPJ_UINT32)getc(IN) << 16; header->biReserved |= (OPJ_UINT32)getc(IN) << 24; } return OPJ_TRUE; } Commit Message: bmp_read_info_header(): reject bmp files with biBitCount == 0 (#983) CWE ID: CWE-119 Target: 1 Example 2: Code: BrowserTestClipboardScope::~BrowserTestClipboardScope() { ui::Clipboard::DestroyClipboardForCurrentThread(); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} 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 jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: native_handle_t* native_handle_create(int numFds, int numInts) { native_handle_t* h = malloc( sizeof(native_handle_t) + sizeof(int)*(numFds+numInts)); if (h) { h->version = sizeof(native_handle_t); h->numFds = numFds; h->numInts = numInts; } return h; } Commit Message: Prevent integer overflow when allocating native_handle_t User specified values of numInts and numFds can overflow and cause malloc to allocate less than we expect, causing heap corruption in subsequent operations on the allocation. Bug: 19334482 Change-Id: I43c75f536ea4c08f14ca12ca6288660fd2d1ec55 CWE ID: CWE-189 Target: 1 Example 2: Code: void WebGLRenderingContextBase::VertexAttribDivisorANGLE(GLuint index, GLuint divisor) { if (isContextLost()) return; if (index >= max_vertex_attribs_) { SynthesizeGLError(GL_INVALID_VALUE, "vertexAttribDivisorANGLE", "index out of range"); return; } ContextGL()->VertexAttribDivisorANGLE(index, divisor); } 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: views::View* WebsiteSettingsPopupView::CreateConnectionTab() { views::View* pane = new views::View(); pane->SetLayoutManager( new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 1)); identity_info_content_ = new views::View(); pane->AddChildView(identity_info_content_); pane->AddChildView(new views::Separator(views::Separator::HORIZONTAL)); connection_info_content_ = new views::View(); pane->AddChildView(connection_info_content_); pane->AddChildView(new views::Separator(views::Separator::HORIZONTAL)); help_center_link_ = new views::Link( l10n_util::GetStringUTF16(IDS_PAGE_INFO_HELP_CENTER_LINK)); help_center_link_->set_listener(this); help_center_content_ = new views::View(); views::View* link_section = CreateSection(base::string16(), help_center_content_, help_center_link_); link_section->AddChildView(help_center_link_); pane->AddChildView(link_section); return pane; } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} 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: ipv6_dup_options(struct sock *sk, struct ipv6_txoptions *opt) { struct ipv6_txoptions *opt2; opt2 = sock_kmalloc(sk, opt->tot_len, GFP_ATOMIC); if (opt2) { long dif = (char *)opt2 - (char *)opt; memcpy(opt2, opt, opt->tot_len); if (opt2->hopopt) *((char **)&opt2->hopopt) += dif; if (opt2->dst0opt) *((char **)&opt2->dst0opt) += dif; if (opt2->dst1opt) *((char **)&opt2->dst1opt) += dif; if (opt2->srcrt) *((char **)&opt2->srcrt) += dif; } return opt2; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Target: 1 Example 2: Code: void mca_ccb_dl_open(tMCA_CCB* p_ccb, UNUSED_ATTR tMCA_CCB_EVT* p_data) { osi_free_and_reset((void**)&p_ccb->p_tx_req); osi_free_and_reset((void**)&p_ccb->p_rx_msg); p_ccb->status = MCA_CCB_STAT_NORM; } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ikev2_vid_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; const u_char *vid; int i, len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ikev2_pay_print(ndo, NPSTR(tpay), e.critical); ND_PRINT((ndo," len=%d vid=", ntohs(e.len) - 4)); vid = (const u_char *)(ext+1); len = ntohs(e.len) - 4; ND_TCHECK2(*vid, len); for(i=0; i<len; i++) { if(ND_ISPRINT(vid[i])) ND_PRINT((ndo, "%c", vid[i])); else ND_PRINT((ndo, ".")); } if (2 < ndo->ndo_vflag && 4 < len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY); key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; } Commit Message: Btrfs: fix hash overflow handling The handling for directory crc hash overflows was fairly obscure, split_leaf returns EOVERFLOW when we try to extend the item and that is supposed to bubble up to userland. For a while it did so, but along the way we added better handling of errors and forced the FS readonly if we hit IO errors during the directory insertion. Along the way, we started testing only for EEXIST and the EOVERFLOW case was dropped. The end result is that we may force the FS readonly if we catch a directory hash bucket overflow. This fixes a few problem spots. First I add tests for EOVERFLOW in the places where we can safely just return the error up the chain. btrfs_rename is harder though, because it tries to insert the new directory item only after it has already unlinked anything the rename was going to overwrite. Rather than adding very complex logic, I added a helper to test for the hash overflow case early while it is still safe to bail out. Snapshot and subvolume creation had a similar problem, so they are using the new helper now too. Signed-off-by: Chris Mason <[email protected]> Reported-by: Pascal Junod <[email protected]> CWE ID: CWE-310 Target: 1 Example 2: Code: static void FS_CheckPak0( void ) { searchpath_t *path; pack_t *curpack; qboolean founddemo = qfalse; unsigned int foundPak = 0; for( path = fs_searchpaths; path; path = path->next ) { const char* pakBasename = path->pack->pakBasename; if(!path->pack) continue; curpack = path->pack; if(!Q_stricmpn( curpack->pakGamename, "demomain", MAX_OSPATH ) && !Q_stricmpn( pakBasename, "pak0", MAX_OSPATH )) { if(curpack->checksum == DEMO_PAK0_CHECKSUM) founddemo = qtrue; } else if(!Q_stricmpn( curpack->pakGamename, BASEGAME, MAX_OSPATH ) && strlen(pakBasename) == 4 && !Q_stricmpn( pakBasename, "pak", 3 ) && pakBasename[3] >= '0' && pakBasename[3] <= '0' + NUM_ID_PAKS - 1) { if( curpack->checksum != pak_checksums[pakBasename[3]-'0'] ) { if(pakBasename[3] == '0') { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak0.pk3 is present but its checksum (%u)\n" "is not correct. Please re-copy pak0.pk3 from your\n" "legitimate RTCW CDROM.\n" "**************************************************\n\n\n", curpack->checksum ); Com_Error(ERR_FATAL, NULL); } /* else { Com_Printf("\n\n" "**************************************************\n" "WARNING: " BASEGAME "/pak%d.pk3 is present but its checksum (%u)\n" "is not correct. Please re-install the point release\n" "**************************************************\n\n\n", pakBasename[3]-'0', curpack->checksum ); } */ } foundPak |= 1<<(pakBasename[3]-'0'); } else { int index; for(index = 0; index < ARRAY_LEN(pak_checksums); index++) { if(curpack->checksum == pak_checksums[index]) { Com_Printf("\n\n" "**************************************************\n" "WARNING: %s is renamed pak file %s%cpak%d.pk3\n" "Running in standalone mode won't work\n" "Please rename, or remove this file\n" "**************************************************\n\n\n", curpack->pakFilename, BASEGAME, PATH_SEP, index); foundPak |= 0x80000000; } } } } if(!foundPak && Q_stricmp(com_basegame->string, BASEGAME)) { Cvar_Set("com_standalone", "1"); } else Cvar_Set("com_standalone", "0"); if(!com_standalone->integer) { if(!(foundPak & 0x01)) { if(founddemo) { Com_Printf( "\n\n" "**************************************************\n" "WARNING: It looks like you're using pak0.pk3\n" "from the demo. This may work fine, but it is not\n" "guaranteed or supported.\n" "**************************************************\n\n\n" ); foundPak |= 0x01; } } } if(!com_standalone->integer && (foundPak & 0x01) != 0x01) { char errorText[MAX_STRING_CHARS] = ""; if((foundPak & 0x01) != 0x01) { Q_strcat(errorText, sizeof(errorText), "\n\n\"pak0.pk3\" is missing. Please copy it\n" "from your legitimate RTCW CDROM.\n\n"); } Q_strcat(errorText, sizeof(errorText), va("Also check that your iortcw executable is in\n" "the correct place and that every file\n" "in the \"%s\" directory is present and readable.\n\n", BASEGAME)); Com_Error(ERR_FATAL, "%s", errorText); } if(!founddemo) FS_CheckMPPaks(); } 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: WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, content::WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; url_ = nav_entry->GetURL(); popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} 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 attach_child_main(void* data) { struct attach_clone_payload* payload = (struct attach_clone_payload*)data; int ipc_socket = payload->ipc_socket; int procfd = payload->procfd; lxc_attach_options_t* options = payload->options; struct lxc_proc_context_info* init_ctx = payload->init_ctx; #if HAVE_SYS_PERSONALITY_H long new_personality; #endif int ret; int status; int expected; long flags; int fd; uid_t new_uid; gid_t new_gid; /* wait for the initial thread to signal us that it's ready * for us to start initializing */ expected = 0; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive notification from initial process (0)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* A description of the purpose of this functionality is * provided in the lxc-attach(1) manual page. We have to * remount here and not in the parent process, otherwise * /proc may not properly reflect the new pid namespace. */ if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) { ret = lxc_attach_remount_sys_proc(); if (ret < 0) { shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* now perform additional attachments*/ #if HAVE_SYS_PERSONALITY_H if (options->personality < 0) new_personality = init_ctx->personality; else new_personality = options->personality; if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) { ret = personality(new_personality); if (ret < 0) { SYSERROR("could not ensure correct architecture"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } #endif if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) { ret = lxc_attach_drop_privs(init_ctx); if (ret < 0) { ERROR("could not drop privileges"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */ ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env); if (ret < 0) { ERROR("could not set initial environment for attached process"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* set user / group id */ new_uid = 0; new_gid = 0; /* ignore errors, we will fall back to root in that case * (/proc was not mounted etc.) */ if (options->namespaces & CLONE_NEWUSER) lxc_attach_get_init_uidgid(&new_uid, &new_gid); if (options->uid != (uid_t)-1) new_uid = options->uid; if (options->gid != (gid_t)-1) new_gid = options->gid; /* setup the control tty */ if (options->stdin_fd && isatty(options->stdin_fd)) { if (setsid() < 0) { SYSERROR("unable to setsid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } if (ioctl(options->stdin_fd, TIOCSCTTY, (char *)NULL) < 0) { SYSERROR("unable to TIOCSTTY"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } /* try to set the uid/gid combination */ if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) { if (setgid(new_gid) || setgroups(0, NULL)) { SYSERROR("switching to container gid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } } if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) { SYSERROR("switching to container uid"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* tell initial process it may now put us into the cgroups */ status = 1; ret = lxc_write_nointr(ipc_socket, &status, sizeof(status)); if (ret != sizeof(status)) { ERROR("error using IPC to notify initial process for initialization (1)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } /* wait for the initial thread to signal us that it has done * everything for us when it comes to cgroups etc. */ expected = 2; status = -1; ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected); if (ret <= 0) { ERROR("error using IPC to receive final notification from initial process (2)"); shutdown(ipc_socket, SHUT_RDWR); rexit(-1); } shutdown(ipc_socket, SHUT_RDWR); close(ipc_socket); if ((init_ctx->container && init_ctx->container->lxc_conf && init_ctx->container->lxc_conf->no_new_privs) || (options->attach_flags & LXC_ATTACH_NO_NEW_PRIVS)) { if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) { SYSERROR("PR_SET_NO_NEW_PRIVS could not be set. " "Process can use execve() gainable " "privileges."); rexit(-1); } INFO("PR_SET_NO_NEW_PRIVS is set. Process cannot use execve() " "gainable privileges."); } /* set new apparmor profile/selinux context */ if ((options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_LSM) && init_ctx->lsm_label) { int on_exec; on_exec = options->attach_flags & LXC_ATTACH_LSM_EXEC ? 1 : 0; if (lsm_set_label_at(procfd, on_exec, init_ctx->lsm_label) < 0) { rexit(-1); } } if (init_ctx->container && init_ctx->container->lxc_conf && init_ctx->container->lxc_conf->seccomp && (lxc_seccomp_load(init_ctx->container->lxc_conf) != 0)) { ERROR("Loading seccomp policy"); rexit(-1); } lxc_proc_put_context_info(init_ctx); /* The following is done after the communication socket is * shut down. That way, all errors that might (though * unlikely) occur up until this point will have their messages * printed to the original stderr (if logging is so configured) * and not the fd the user supplied, if any. */ /* fd handling for stdin, stdout and stderr; * ignore errors here, user may want to make sure * the fds are closed, for example */ if (options->stdin_fd >= 0 && options->stdin_fd != 0) dup2(options->stdin_fd, 0); if (options->stdout_fd >= 0 && options->stdout_fd != 1) dup2(options->stdout_fd, 1); if (options->stderr_fd >= 0 && options->stderr_fd != 2) dup2(options->stderr_fd, 2); /* close the old fds */ if (options->stdin_fd > 2) close(options->stdin_fd); if (options->stdout_fd > 2) close(options->stdout_fd); if (options->stderr_fd > 2) close(options->stderr_fd); /* try to remove CLOEXEC flag from stdin/stdout/stderr, * but also here, ignore errors */ for (fd = 0; fd <= 2; fd++) { flags = fcntl(fd, F_GETFL); if (flags < 0) continue; if (flags & FD_CLOEXEC) if (fcntl(fd, F_SETFL, flags & ~FD_CLOEXEC) < 0) SYSERROR("Unable to clear CLOEXEC from fd"); } /* we don't need proc anymore */ close(procfd); /* we're done, so we can now do whatever the user intended us to do */ rexit(payload->exec_function(payload->exec_payload)); } Commit Message: attach: do not send procfd to attached process So far, we opened a file descriptor refering to proc on the host inside the host namespace and handed that fd to the attached process in attach_child_main(). This was done to ensure that LSM labels were correctly setup. However, by exploiting a potential kernel bug, ptrace could be used to prevent the file descriptor from being closed which in turn could be used by an unprivileged container to gain access to the host namespace. Aside from this needing an upstream kernel fix, we should make sure that we don't pass the fd for proc itself to the attached process. However, we cannot completely prevent this, as the attached process needs to be able to change its apparmor profile by writing to /proc/self/attr/exec or /proc/self/attr/current. To minimize the attack surface, we only send the fd for /proc/self/attr/exec or /proc/self/attr/current to the attached process. To do this we introduce a little more IPC between the child and parent: * IPC mechanism: (X is receiver) * initial process intermediate attached * X <--- send pid of * attached proc, * then exit * send 0 ------------------------------------> X * [do initialization] * X <------------------------------------ send 1 * [add to cgroup, ...] * send 2 ------------------------------------> X * [set LXC_ATTACH_NO_NEW_PRIVS] * X <------------------------------------ send 3 * [open LSM label fd] * send 4 ------------------------------------> X * [set LSM label] * close socket close socket * run program The attached child tells the parent when it is ready to have its LSM labels set up. The parent then opens an approriate fd for the child PID to /proc/<pid>/attr/exec or /proc/<pid>/attr/current and sends it via SCM_RIGHTS to the child. The child can then set its LSM laben. Both sides then close the socket fds and the child execs the requested process. Signed-off-by: Christian Brauner <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { WARN(1, "Tx-ring is not supported.\n"); goto out; } rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (atomic_read(&rb->pending)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(req->tp_block_size & (PAGE_SIZE - 1))) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size/req->tp_frame_size; if (unlikely(rb->frames_per_block <= 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Transmit path is not supported. We checked * it above but just being paranoid */ if (!tx_ring) init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring); break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } lock_sock(sk); /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue); } release_sock(sk); if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: return err; } Commit Message: net: rework recvmsg handler msg_name and msg_namelen logic This patch now always passes msg->msg_namelen as 0. recvmsg handlers must set msg_namelen to the proper size <= sizeof(struct sockaddr_storage) to return msg_name to the user. This prevents numerous uninitialized memory leaks we had in the recvmsg handlers and makes it harder for new code to accidentally leak uninitialized memory. Optimize for the case recvfrom is called with NULL as address. We don't need to copy the address at all, so set it to NULL before invoking the recvmsg handler. We can do so, because all the recvmsg handlers must cope with the case a plain read() is called on them. read() also sets msg_name to NULL. Also document these changes in include/linux/net.h as suggested by David Miller. Changes since RFC: Set msg->msg_name = NULL if user specified a NULL in msg_name but had a non-null msg_namelen in verify_iovec/verify_compat_iovec. This doesn't affect sendto as it would bail out earlier while trying to copy-in the address. It also more naturally reflects the logic by the callers of verify_iovec. With this change in place I could remove " if (!uaddr || msg_sys->msg_namelen == 0) msg->msg_name = NULL ". This change does not alter the user visible error logic as we ignore msg_namelen as long as msg_name is NULL. Also remove two unnecessary curly brackets in ___sys_recvmsg and change comments to netdev style. Cc: David Miller <[email protected]> Suggested-by: Eric Dumazet <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: explicit MousePressedHandler(AutofillDialogViewDelegate* delegate) : delegate_(delegate) {} Commit Message: Clear out some minor TODOs. BUG=none Review URL: https://codereview.chromium.org/1047063002 Cr-Commit-Position: refs/heads/master@{#322959} 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: emit_string(const char *str, FILE *out) /* Print a string with spaces replaced by '_' and non-printing characters by * an octal escape. */ { for (; *str; ++str) if (isgraph(UCHAR_MAX & *str)) putc(*str, out); else if (isspace(UCHAR_MAX & *str)) putc('_', out); else fprintf(out, "\\%.3o", *str); } 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 TabAnimationDelegate::AnimationProgressed( const gfx::Animation* animation) { tab_->SetVisible(tab_strip_->ShouldTabBeVisible(tab_)); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <[email protected]> Reviewed-by: Taylor Bergquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xmlParsePEReference(xmlParserCtxtPtr ctxt) { const xmlChar *name; xmlEntityPtr entity = NULL; xmlParserInputPtr input; if (RAW != '%') return; NEXT; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_PEREF_NO_NAME, "PEReference: no name\n"); return; } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "PEReference: %s\n", name); if (RAW != ';') { xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); return; } NEXT; /* * Increate the number of entity references parsed */ ctxt->nbentities++; /* * Request the entity from SAX */ if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) entity = ctxt->sax->getParameterEntity(ctxt->userData, name); if (ctxt->instate == XML_PARSER_EOF) return; if (entity == NULL) { /* * [ WFC: Entity Declared ] * In a document without any DTD, a document with only an * internal DTD subset which contains no parameter entity * references, or a document with "standalone='yes'", ... * ... The declaration of a parameter entity must precede * any reference to it... */ if ((ctxt->standalone == 1) || ((ctxt->hasExternalSubset == 0) && (ctxt->hasPErefs == 0))) { xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name); } else { /* * [ VC: Entity Declared ] * In a document with an external subset or external * parameter entities with "standalone='no'", ... * ... The declaration of a parameter entity must * precede any reference to it... */ if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); } else xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "PEReference: %%%s; not found\n", name, NULL); ctxt->valid = 0; } xmlParserEntityCheck(ctxt, 0, NULL, 0); } else { /* * Internal checking in case the entity quest barfed */ if ((entity->etype != XML_INTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_PARAMETER_ENTITY)) { xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, "Internal: %%%s; is not a parameter entity\n", name, NULL); } else { xmlChar start[4]; xmlCharEncoding enc; if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ((ctxt->options & XML_PARSE_NOENT) == 0) && ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ((ctxt->options & XML_PARSE_DTDATTR) == 0) && (ctxt->replaceEntities == 0) && (ctxt->validate == 0)) return; input = xmlNewEntityInputStream(ctxt, entity); if (xmlPushInput(ctxt, input) < 0) return; if (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. * Note that, since we may have some non-UTF8 * encoding (like UTF16, bug 135229), the 'length' * is not known, but we can calculate based upon * the amount of data in the buffer. */ GROW if (ctxt->instate == XML_PARSER_EOF) return; if ((ctxt->input->end - ctxt->input->cur)>=4) { start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { xmlParseTextDecl(ctxt); } } } } ctxt->hasPErefs = 1; } Commit Message: Detect infinite recursion in parameter entities When expanding a parameter entity in a DTD, infinite recursion could lead to an infinite loop or memory exhaustion. Thanks to Wei Lei for the first of many reports. Fixes bug 759579. CWE ID: CWE-835 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 m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; struct vm_area_struct *vma = v; vma_stop(priv, vma); if (priv->task) put_task_struct(priv->task); } Commit Message: proc: fix oops on invalid /proc/<pid>/maps access When m_start returns an error, the seq_file logic will still call m_stop with that error entry, so we'd better make sure that we check it before using it as a vma. Introduced by commit ec6fd8a4355c ("report errors in /proc/*/*map* sanely"), which replaced NULL with various ERR_PTR() cases. (On ia64, you happen to get a unaligned fault instead of a page fault, since the address used is generally some random error code like -EPERM) Reported-by: Anca Emanuel <[email protected]> Reported-by: Tony Luck <[email protected]> Cc: Al Viro <[email protected]> Cc: Américo Wang <[email protected]> Cc: Stephen Wilson <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: bool UpdateAccessTimeOnDBThread(const GURL& origin, StorageType type, base::Time accessed_time, QuotaDatabase* database) { DCHECK(database); return database->SetOriginLastAccessTime(origin, type, accessed_time); } Commit Message: Wipe out QuotaThreadTask. This is a one of a series of refactoring patches for QuotaManager. http://codereview.chromium.org/10872054/ http://codereview.chromium.org/10917060/ BUG=139270 Review URL: https://chromiumcodereview.appspot.com/10919070 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@154987 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: ecc_check_secret_key (gcry_sexp_t keyparms) { gcry_err_code_t rc; gcry_sexp_t l1 = NULL; int flags = 0; char *curvename = NULL; gcry_mpi_t mpi_g = NULL; gcry_mpi_t mpi_q = NULL; ECC_secret_key sk; mpi_ec_t ec = NULL; memset (&sk, 0, sizeof sk); /* Look for flags. */ l1 = sexp_find_token (keyparms, "flags", 0); if (l1) { rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); if (rc) goto leave; } /* Extract the parameters. */ if ((flags & PUBKEY_FLAG_PARAM)) rc = sexp_extract_param (keyparms, NULL, "-p?a?b?g?n?h?/q?+d", &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, &sk.E.h, &mpi_q, &sk.d, NULL); else rc = sexp_extract_param (keyparms, NULL, "/q?+d", &mpi_q, &sk.d, NULL); if (rc) goto leave; /* Add missing parameters using the optional curve parameter. */ sexp_release (l1); l1 = sexp_find_token (keyparms, "curve", 5); if (l1) { curvename = sexp_nth_string (l1, 1); if (curvename) { rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); if (rc) goto leave; } } if (mpi_g) { if (!sk.E.G.x) point_init (&sk.E.G); rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); if (rc) goto leave; } /* Guess required fields if a curve parameter has not been given. FIXME: This is a crude hacks. We need to fix that. */ if (!curvename) { sk.E.model = ((flags & PUBKEY_FLAG_EDDSA) ? MPI_EC_EDWARDS : MPI_EC_WEIERSTRASS); sk.E.dialect = ((flags & PUBKEY_FLAG_EDDSA) ? ECC_DIALECT_ED25519 : ECC_DIALECT_STANDARD); if (!sk.E.h) sk.E.h = mpi_const (MPI_C_ONE); } if (DBG_CIPHER) { log_debug ("ecc_testkey inf: %s/%s\n", _gcry_ecc_model2str (sk.E.model), _gcry_ecc_dialect2str (sk.E.dialect)); if (sk.E.name) log_debug ("ecc_testkey nam: %s\n", sk.E.name); log_printmpi ("ecc_testkey p", sk.E.p); log_printmpi ("ecc_testkey a", sk.E.a); log_printmpi ("ecc_testkey b", sk.E.b); log_printpnt ("ecc_testkey g", &sk.E.G, NULL); log_printmpi ("ecc_testkey n", sk.E.n); log_printmpi ("ecc_testkey h", sk.E.h); log_printmpi ("ecc_testkey q", mpi_q); if (!fips_mode ()) log_printmpi ("ecc_testkey d", sk.d); } if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) { rc = GPG_ERR_NO_OBJ; goto leave; } ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, sk.E.p, sk.E.a, sk.E.b); if (mpi_q) { point_init (&sk.Q); if (ec->dialect == ECC_DIALECT_ED25519) rc = _gcry_ecc_eddsa_decodepoint (mpi_q, ec, &sk.Q, NULL, NULL); else if (ec->model == MPI_EC_MONTGOMERY) rc = _gcry_ecc_mont_decodepoint (mpi_q, ec, &sk.Q); else rc = _gcry_ecc_os2ec (&sk.Q, mpi_q); if (rc) goto leave; } else { /* The secret key test requires Q. */ rc = GPG_ERR_NO_OBJ; goto leave; } if (check_secret_key (&sk, ec, flags)) rc = GPG_ERR_BAD_SECKEY; leave: _gcry_mpi_ec_free (ec); _gcry_mpi_release (sk.E.p); _gcry_mpi_release (sk.E.a); _gcry_mpi_release (sk.E.b); _gcry_mpi_release (mpi_g); point_free (&sk.E.G); _gcry_mpi_release (sk.E.n); _gcry_mpi_release (sk.E.h); _gcry_mpi_release (mpi_q); point_free (&sk.Q); _gcry_mpi_release (sk.d); xfree (curvename); sexp_release (l1); if (DBG_CIPHER) log_debug ("ecc_testkey => %s\n", gpg_strerror (rc)); return rc; } Commit Message: 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: status_t OMXNodeInstance::allocateSecureBuffer( OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer, void **buffer_data, sp<NativeHandle> *native_handle) { if (buffer == NULL || buffer_data == NULL || native_handle == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); BufferMeta *buffer_meta = new BufferMeta(size, portIndex); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, size); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size)); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); if (mSecureBufferType[portIndex] == kSecureBufferTypeNativeHandle) { *buffer_data = NULL; *native_handle = NativeHandle::create( (native_handle_t *)header->pBuffer, false /* ownsHandle */); } else { *buffer_data = header->pBuffer; *native_handle = NULL; } addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateSecureBuffer, NEW_BUFFER_FMT( *buffer, portIndex, "%zu@%p:%p", size, *buffer_data, *native_handle == NULL ? NULL : (*native_handle)->handle())); return OK; } Commit Message: OMXNodeInstance: sanity check portIndex. Bug: 31385713 Change-Id: Ib91d00eb5cc8c51c84d37f5d36d6b7ca594d201f (cherry picked from commit f80a1f5075a7c6e1982d37c68bfed7c9a611bb20) CWE ID: CWE-264 Target: 1 Example 2: Code: void EnableAllActions() { actions_.insert(MediaSessionAction::kPlay); actions_.insert(MediaSessionAction::kPause); actions_.insert(MediaSessionAction::kPreviousTrack); actions_.insert(MediaSessionAction::kNextTrack); actions_.insert(MediaSessionAction::kSeekBackward); actions_.insert(MediaSessionAction::kSeekForward); actions_.insert(MediaSessionAction::kStop); NotifyUpdatedActions(); } Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks This CL rearranges the different components of the CrOS lock screen media controls based on the newest mocks. This involves resizing most of the child views and their spacings. The artwork was also resized and re-positioned. Additionally, the close button was moved from the main view to the header row child view. Artist and title data about the current session will eventually be placed to the right of the artwork, but right now this space is empty. See the bug for before and after pictures. Bug: 991647 Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554 Reviewed-by: Xiyuan Xia <[email protected]> Reviewed-by: Becca Hughes <[email protected]> Commit-Queue: Mia Bergeron <[email protected]> Cr-Commit-Position: refs/heads/master@{#686253} CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: launchTests(testDescPtr tst) { int res = 0, err = 0; size_t i; char *result; char *error; int mem; if (tst == NULL) return(-1); if (tst->in != NULL) { glob_t globbuf; globbuf.gl_offs = 0; glob(tst->in, GLOB_DOOFFS, NULL, &globbuf); for (i = 0;i < globbuf.gl_pathc;i++) { if (!checkTestFile(globbuf.gl_pathv[i])) continue; if (tst->suffix != NULL) { result = resultFilename(globbuf.gl_pathv[i], tst->out, tst->suffix); if (result == NULL) { fprintf(stderr, "Out of memory !\n"); fatalError(); } } else { result = NULL; } if (tst->err != NULL) { error = resultFilename(globbuf.gl_pathv[i], tst->out, tst->err); if (error == NULL) { fprintf(stderr, "Out of memory !\n"); fatalError(); } } else { error = NULL; } if ((result) &&(!checkTestFile(result)) && !update_results) { fprintf(stderr, "Missing result file %s\n", result); } else if ((error) &&(!checkTestFile(error)) && !update_results) { fprintf(stderr, "Missing error file %s\n", error); } else { mem = xmlMemUsed(); extraMemoryFromResolver = 0; testErrorsSize = 0; testErrors[0] = 0; res = tst->func(globbuf.gl_pathv[i], result, error, tst->options | XML_PARSE_COMPACT); xmlResetLastError(); if (res != 0) { fprintf(stderr, "File %s generated an error\n", globbuf.gl_pathv[i]); nb_errors++; err++; } else if (xmlMemUsed() != mem) { if ((xmlMemUsed() != mem) && (extraMemoryFromResolver == 0)) { fprintf(stderr, "File %s leaked %d bytes\n", globbuf.gl_pathv[i], xmlMemUsed() - mem); nb_leaks++; err++; } } testErrorsSize = 0; } if (result) free(result); if (error) free(error); } globfree(&globbuf); } else { testErrorsSize = 0; testErrors[0] = 0; extraMemoryFromResolver = 0; res = tst->func(NULL, NULL, NULL, tst->options); if (res != 0) { nb_errors++; err++; } } return(err); } Commit Message: Fix handling of parameter-entity references There were two bugs where parameter-entity references could lead to an unexpected change of the input buffer in xmlParseNameComplex and xmlDictLookup being called with an invalid pointer. Percent sign in DTD Names ========================= The NEXTL macro used to call xmlParserHandlePEReference. When parsing "complex" names inside the DTD, this could result in entity expansion which created a new input buffer. The fix is to simply remove the call to xmlParserHandlePEReference from the NEXTL macro. This is safe because no users of the macro require expansion of parameter entities. - xmlParseNameComplex - xmlParseNCNameComplex - xmlParseNmtoken The percent sign is not allowed in names, which are grammatical tokens. - xmlParseEntityValue Parameter-entity references in entity values are expanded but this happens in a separate step in this function. - xmlParseSystemLiteral Parameter-entity references are ignored in the system literal. - xmlParseAttValueComplex - xmlParseCharDataComplex - xmlParseCommentComplex - xmlParsePI - xmlParseCDSect Parameter-entity references are ignored outside the DTD. - xmlLoadEntityContent This function is only called from xmlStringLenDecodeEntities and entities are replaced in a separate step immediately after the function call. This bug could also be triggered with an internal subset and double entity expansion. This fixes bug 766956 initially reported by Wei Lei and independently by Chromium's ClusterFuzz, Hanno Böck, and Marco Grassi. Thanks to everyone involved. xmlParseNameComplex with XML_PARSE_OLD10 ======================================== When parsing Names inside an expanded parameter entity with the XML_PARSE_OLD10 option, xmlParseNameComplex would call xmlGROW via the GROW macro if the input buffer was exhausted. At the end of the parameter entity's replacement text, this function would then call xmlPopInput which invalidated the input buffer. There should be no need to invoke GROW in this situation because the buffer is grown periodically every XML_PARSER_CHUNK_SIZE characters and, at least for UTF-8, in xmlCurrentChar. This also matches the code path executed when XML_PARSE_OLD10 is not set. This fixes bugs 781205 (CVE-2017-9049) and 781361 (CVE-2017-9050). Thanks to Marcel Böhme and Thuan Pham for the report. Additional hardening ==================== A separate check was added in xmlParseNameComplex to validate the buffer size. CWE ID: CWE-119 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val) { ulonglong tmp; if (jas_iccgetuint(in, 4, &tmp)) return -1; *val = tmp; return 0; } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190 Target: 1 Example 2: Code: nfs3svc_encode_readlinkres(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readlinkres *resp) { p = encode_post_op_attr(rqstp, p, &resp->fh); if (resp->status == 0) { *p++ = htonl(resp->len); xdr_ressize_check(rqstp, p); rqstp->rq_res.page_len = resp->len; if (resp->len & 3) { /* need to pad the tail */ rqstp->rq_res.tail[0].iov_base = p; *p = 0; rqstp->rq_res.tail[0].iov_len = 4 - (resp->len&3); } return 1; } else return xdr_ressize_check(rqstp, p); } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 sk_sp<SkImage> flipSkImageVertically(SkImage* input, AlphaDisposition alphaOp) { size_t width = static_cast<size_t>(input->width()); size_t height = static_cast<size_t>(input->height()); SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(), (alphaOp == PremultiplyAlpha) ? kPremul_SkAlphaType : kUnpremul_SkAlphaType); size_t imageRowBytes = width * info.bytesPerPixel(); RefPtr<Uint8Array> imagePixels = copySkImageData(input, info); if (!imagePixels) return nullptr; for (size_t i = 0; i < height / 2; i++) { size_t topFirstElement = i * imageRowBytes; size_t topLastElement = (i + 1) * imageRowBytes; size_t bottomFirstElement = (height - 1 - i) * imageRowBytes; std::swap_ranges(imagePixels->data() + topFirstElement, imagePixels->data() + topLastElement, imagePixels->data() + bottomFirstElement); } return newSkImageFromRaster(info, std::move(imagePixels), imageRowBytes); } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} 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: unsigned long Tracks::GetTracksCount() const { const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries; assert(result >= 0); return static_cast<unsigned long>(result); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: bool FrameLoader::ShouldPerformFragmentNavigation(bool is_form_submission, const String& http_method, FrameLoadType load_type, const KURL& url) { return DeprecatedEqualIgnoringCase(http_method, HTTPNames::GET) && !IsReloadLoadType(load_type) && load_type != kFrameLoadTypeBackForward && url.HasFragmentIdentifier() && EqualIgnoringFragmentIdentifier(frame_->GetDocument()->Url(), url) && !frame_->GetDocument()->IsFrameSet(); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PassRefPtr<DocumentFragment> XSLTProcessor::transformToFragment(Node* sourceNode, Document* outputDoc) { String resultMIMEType; String resultString; String resultEncoding; if (outputDoc->isHTMLDocument()) resultMIMEType = "text/html"; if (!transformToString(sourceNode, resultMIMEType, resultString, resultEncoding)) return 0; return createFragmentFromSource(resultString, resultMIMEType, outputDoc); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264 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 set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } Commit Message: floppy: fix div-by-zero in setup_format_params This fixes a divide by zero error in the setup_format_params function of the floppy driver. Two consecutive ioctls can trigger the bug: The first one should set the drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK to become zero. Next, the floppy format operation should be called. A floppy disk is not required to be inserted. An unprivileged user could trigger the bug if the device is accessible. The patch checks F_SECT_PER_TRACK for a non-zero value in the set_geometry function. The proper check should involve a reasonable upper limit for the .sect and .rate fields, but it could change the UAPI. The patch also checks F_SECT_PER_TRACK in the setup_format_params, and cancels the formatting operation in case of zero. The bug was found by syzkaller. Signed-off-by: Denis Efremov <[email protected]> Tested-by: Willy Tarreau <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-369 Target: 1 Example 2: Code: void RunMojoCallbacks() { if (generate_stream_cb) { std::move(generate_stream_cb) .Run(MEDIA_DEVICE_FAILED_DUE_TO_SHUTDOWN, std::string(), MediaStreamDevices(), MediaStreamDevices()); } if (open_device_cb) { std::move(open_device_cb) .Run(false /* success */, std::string(), MediaStreamDevice()); } } Commit Message: Fix MediaObserver notifications in MediaStreamManager. This CL fixes the stream type used to notify MediaObserver about cancelled MediaStream requests. Before this CL, NUM_MEDIA_TYPES was used as stream type to indicate that all stream types should be cancelled. However, the MediaObserver end does not interpret NUM_MEDIA_TYPES this way and the request to update the UI is ignored. This CL sends a separate notification for each stream type so that the UI actually gets updated for all stream types in use. Bug: 816033 Change-Id: Ib7d3b3046d1dd0976627f8ab38abf086eacc9405 Reviewed-on: https://chromium-review.googlesource.com/939630 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Raymes Khoury <[email protected]> Cr-Commit-Position: refs/heads/master@{#540122} CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 zlib_compress_final(struct crypto_pcomp *tfm, struct comp_request *req) { int ret; struct zlib_ctx *dctx = crypto_tfm_ctx(crypto_pcomp_tfm(tfm)); struct z_stream_s *stream = &dctx->comp_stream; pr_debug("avail_in %u, avail_out %u\n", req->avail_in, req->avail_out); stream->next_in = req->next_in; stream->avail_in = req->avail_in; stream->next_out = req->next_out; stream->avail_out = req->avail_out; ret = zlib_deflate(stream, Z_FINISH); if (ret != Z_STREAM_END) { pr_debug("zlib_deflate failed %d\n", ret); return -EINVAL; } ret = req->avail_out - stream->avail_out; pr_debug("avail_in %lu, avail_out %lu (consumed %lu, produced %u)\n", stream->avail_in, stream->avail_out, req->avail_in - stream->avail_in, ret); req->next_in = stream->next_in; req->avail_in = stream->avail_in; req->next_out = stream->next_out; req->avail_out = stream->avail_out; return ret; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length) { int plenbytes; char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")]; if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 && is_ipv4_mapped_address(&prefix[1])) { struct in_addr addr; u_int plen; plen = prefix[0]-96; if (32 < plen) return -1; max_length -= 1; memset(&addr, 0, sizeof(addr)); plenbytes = (plen + 7) / 8; if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN) return -3; memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes); if (plen % 8) { ((u_char *)&addr)[plenbytes - 1] &= ((0xff00 >> (plen % 8)) & 0xff); } snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen); plenbytes += 1 + IPV4_MAPPED_HEADING_LEN; } else { plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf)); } ND_PRINT((ndo, "%s", buf)); return plenbytes; } Commit Message: (for 4.9.3) CVE-2018-16228/HNCP: make buffer access safer print_prefix() has a buffer and does not initialize it. It may call decode_prefix6(), which also does not initialize the buffer on invalid input. When that happens, make sure to return from print_prefix() before trying to print the [still uninitialized] buffer. This fixes a buffer over-read discovered by Wang Junjie of 360 ESG Codesafe Team. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: mrb_func_basic_p(mrb_state *mrb, mrb_value obj, mrb_sym mid, mrb_func_t func) { mrb_method_t m = mrb_method_search(mrb, mrb_class(mrb, obj), mid); struct RProc *p; if (MRB_METHOD_UNDEF_P(m)) return FALSE; if (MRB_METHOD_FUNC_P(m)) return MRB_METHOD_FUNC(m) == func; p = MRB_METHOD_PROC(m); if (MRB_PROC_CFUNC_P(p) && (MRB_PROC_CFUNC(p) == func)) return TRUE; return FALSE; } Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036 Copying all flags from the original object may overwrite the clone's flags e.g. the embedded flag. 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 addrconf_ifdown(struct net_device *dev, int how) { struct net *net = dev_net(dev); struct inet6_dev *idev; struct inet6_ifaddr *ifa; int state, i; ASSERT_RTNL(); rt6_ifdown(net, dev); neigh_ifdown(&nd_tbl, dev); idev = __in6_dev_get(dev); if (idev == NULL) return -ENODEV; /* * Step 1: remove reference to ipv6 device from parent device. * Do not dev_put! */ if (how) { idev->dead = 1; /* protected by rtnl_lock */ RCU_INIT_POINTER(dev->ip6_ptr, NULL); /* Step 1.5: remove snmp6 entry */ snmp6_unregister_dev(idev); } /* Step 2: clear hash table */ for (i = 0; i < IN6_ADDR_HSIZE; i++) { struct hlist_head *h = &inet6_addr_lst[i]; spin_lock_bh(&addrconf_hash_lock); restart: hlist_for_each_entry_rcu(ifa, h, addr_lst) { if (ifa->idev == idev) { hlist_del_init_rcu(&ifa->addr_lst); addrconf_del_dad_work(ifa); goto restart; } } spin_unlock_bh(&addrconf_hash_lock); } write_lock_bh(&idev->lock); addrconf_del_rs_timer(idev); /* Step 2: clear flags for stateless addrconf */ if (!how) idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY); if (how && del_timer(&idev->regen_timer)) in6_dev_put(idev); /* Step 3: clear tempaddr list */ while (!list_empty(&idev->tempaddr_list)) { ifa = list_first_entry(&idev->tempaddr_list, struct inet6_ifaddr, tmp_list); list_del(&ifa->tmp_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->lock); if (ifa->ifpub) { in6_ifa_put(ifa->ifpub); ifa->ifpub = NULL; } spin_unlock_bh(&ifa->lock); in6_ifa_put(ifa); write_lock_bh(&idev->lock); } while (!list_empty(&idev->addr_list)) { ifa = list_first_entry(&idev->addr_list, struct inet6_ifaddr, if_list); addrconf_del_dad_work(ifa); list_del(&ifa->if_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->state_lock); state = ifa->state; ifa->state = INET6_IFADDR_STATE_DEAD; spin_unlock_bh(&ifa->state_lock); if (state != INET6_IFADDR_STATE_DEAD) { __ipv6_ifa_notify(RTM_DELADDR, ifa); inet6addr_notifier_call_chain(NETDEV_DOWN, ifa); } in6_ifa_put(ifa); write_lock_bh(&idev->lock); } write_unlock_bh(&idev->lock); /* Step 5: Discard anycast and multicast list */ if (how) { ipv6_ac_destroy_dev(idev); ipv6_mc_destroy_dev(idev); } else { ipv6_mc_down(idev); } idev->tstamp = jiffies; /* Last: Shot the device (if unregistered) */ if (how) { addrconf_sysctl_unregister(idev); neigh_parms_release(&nd_tbl, idev->nd_parms); neigh_ifdown(&nd_tbl, dev); in6_dev_put(idev); } return 0; } Commit Message: ipv6: addrconf: validate new MTU before applying it Currently we don't check if the new MTU is valid or not and this allows one to configure a smaller than minimum allowed by RFCs or even bigger than interface own MTU, which is a problem as it may lead to packet drops. If you have a daemon like NetworkManager running, this may be exploited by remote attackers by forging RA packets with an invalid MTU, possibly leading to a DoS. (NetworkManager currently only validates for values too small, but not for too big ones.) The fix is just to make sure the new value is valid. That is, between IPV6_MIN_MTU and interface's MTU. Note that similar check is already performed at ndisc_router_discovery(), for when kernel itself parses the RA. Signed-off-by: Marcelo Ricardo Leitner <[email protected]> Signed-off-by: Sabrina Dubroca <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void usage_exit() { fprintf(stderr, "Usage: %s <codec> <width> <height> <infile> <outfile> " "<keyframe-interval> [<error-resilient>]\nSee comments in " "simple_encoder.c for more information.\n", exec_name); exit(EXIT_FAILURE); } 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 WebMediaPlayerImpl::ExitedFullscreen() { overlay_info_.is_fullscreen = false; if (!always_enable_overlays_ && overlay_enabled_) DisableOverlay(); if (!decoder_requires_restart_for_overlay_) MaybeSendOverlayInfoToDecoder(); } 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: unsigned int ReferenceSAD(unsigned int max_sad, int block_idx = 0) { unsigned int sad = 0; const uint8_t* const reference = GetReference(block_idx); for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { sad += abs(source_data_[h * source_stride_ + w] - reference[h * reference_stride_ + w]); } if (sad > max_sad) { break; } } return sad; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int yr_execute_code( YR_RULES* rules, YR_SCAN_CONTEXT* context, int timeout, time_t start_time) { int64_t mem[MEM_SIZE]; int32_t sp = 0; uint8_t* ip = rules->code_start; YR_VALUE args[MAX_FUNCTION_ARGS]; YR_VALUE *stack; YR_VALUE r1; YR_VALUE r2; YR_VALUE r3; #ifdef PROFILING_ENABLED YR_RULE* current_rule = NULL; #endif YR_RULE* rule; YR_MATCH* match; YR_OBJECT_FUNCTION* function; char* identifier; char* args_fmt; int i; int found; int count; int result = ERROR_SUCCESS; int stop = FALSE; int cycle = 0; int tidx = context->tidx; int stack_size; #ifdef PROFILING_ENABLED clock_t start = clock(); #endif yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); if (stack == NULL) return ERROR_INSUFFICIENT_MEMORY; while(!stop) { switch(*ip) { case OP_HALT: assert(sp == 0); // When HALT is reached the stack should be empty. stop = TRUE; break; case OP_PUSH: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); push(r1); break; case OP_POP: pop(r1); break; case OP_CLEAR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i] = 0; break; case OP_ADD_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (!is_undef(r2)) mem[r1.i] += r2.i; break; case OP_INCR_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); mem[r1.i]++; break; case OP_PUSH_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r1.i = mem[r1.i]; push(r1); break; case OP_POP_M: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); mem[r1.i] = r2.i; break; case OP_SWAPUNDEF: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); pop(r2); if (is_undef(r2)) { r1.i = mem[r1.i]; push(r1); } else { push(r2); } break; case OP_JNUNDEF: pop(r1); push(r1); ip = jmp_if(!is_undef(r1), ip); break; case OP_JLE: pop(r2); pop(r1); push(r1); push(r2); ip = jmp_if(r1.i <= r2.i, ip); break; case OP_JTRUE: pop(r1); push(r1); ip = jmp_if(!is_undef(r1) && r1.i, ip); break; case OP_JFALSE: pop(r1); push(r1); ip = jmp_if(is_undef(r1) || !r1.i, ip); break; case OP_AND: pop(r2); pop(r1); if (is_undef(r1) || is_undef(r2)) r1.i = 0; else r1.i = r1.i && r2.i; push(r1); break; case OP_OR: pop(r2); pop(r1); if (is_undef(r1)) { push(r2); } else if (is_undef(r2)) { push(r1); } else { r1.i = r1.i || r2.i; push(r1); } break; case OP_NOT: pop(r1); if (is_undef(r1)) r1.i = UNDEFINED; else r1.i= !r1.i; push(r1); break; case OP_MOD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i % r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_SHR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >> r2.i; push(r1); break; case OP_SHL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i << r2.i; push(r1); break; case OP_BITWISE_NOT: pop(r1); ensure_defined(r1); r1.i = ~r1.i; push(r1); break; case OP_BITWISE_AND: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i & r2.i; push(r1); break; case OP_BITWISE_OR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i | r2.i; push(r1); break; case OP_BITWISE_XOR: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i ^ r2.i; push(r1); break; case OP_PUSH_RULE: rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; push(r1); break; case OP_INIT_RULE: #ifdef PROFILING_ENABLED current_rule = *(YR_RULE**)(ip + 1); #endif ip += sizeof(uint64_t); break; case OP_MATCH_RULE: pop(r1); rule = *(YR_RULE**)(ip + 1); ip += sizeof(uint64_t); if (!is_undef(r1) && r1.i) rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; else if (RULE_IS_GLOBAL(rule)) rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; #ifdef PROFILING_ENABLED rule->clock_ticks += clock() - start; start = clock(); #endif break; case OP_OBJ_LOAD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); r1.o = (YR_OBJECT*) yr_hash_table_lookup( context->objects_table, identifier, NULL); assert(r1.o != NULL); push(r1); break; case OP_OBJ_FIELD: identifier = *(char**)(ip + 1); ip += sizeof(uint64_t); pop(r1); ensure_defined(r1); r1.o = yr_object_lookup_field(r1.o, identifier); assert(r1.o != NULL); push(r1); break; case OP_OBJ_VALUE: pop(r1); ensure_defined(r1); switch(r1.o->type) { case OBJECT_TYPE_INTEGER: r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; break; case OBJECT_TYPE_FLOAT: if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) r1.i = UNDEFINED; else r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; break; case OBJECT_TYPE_STRING: if (((YR_OBJECT_STRING*) r1.o)->value == NULL) r1.i = UNDEFINED; else r1.p = ((YR_OBJECT_STRING*) r1.o)->value; break; default: assert(FALSE); } push(r1); break; case OP_INDEX_ARRAY: pop(r1); // index pop(r2); // array ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_ARRAY); r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_LOOKUP_DICT: pop(r1); // key pop(r2); // dictionary ensure_defined(r1); ensure_defined(r2); assert(r2.o->type == OBJECT_TYPE_DICTIONARY); r1.o = yr_object_dict_get_item( r2.o, 0, r1.ss->c_string); if (r1.o == NULL) r1.i = UNDEFINED; push(r1); break; case OP_CALL: args_fmt = *(char**)(ip + 1); ip += sizeof(uint64_t); i = (int) strlen(args_fmt); count = 0; while (i > 0) { pop(r1); if (is_undef(r1)) // count the number of undefined args count++; args[i - 1] = r1; i--; } pop(r2); ensure_defined(r2); if (count > 0) { r1.i = UNDEFINED; push(r1); break; } function = (YR_OBJECT_FUNCTION*) r2.o; result = ERROR_INTERNAL_FATAL_ERROR; for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) { if (function->prototypes[i].arguments_fmt == NULL) break; if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) { result = function->prototypes[i].code(args, context, function); break; } } assert(i < MAX_OVERLOADED_FUNCTIONS); if (result == ERROR_SUCCESS) { r1.o = function->return_obj; push(r1); } else { stop = TRUE; } break; case OP_FOUND: pop(r1); r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; push(r1); break; case OP_FOUND_AT: pop(r2); pop(r1); if (is_undef(r1)) { r1.i = 0; push(r1); break; } match = r2.s->matches[tidx].head; r3.i = FALSE; while (match != NULL) { if (r1.i == match->base + match->offset) { r3.i = TRUE; break; } if (r1.i < match->base + match->offset) break; match = match->next; } push(r3); break; case OP_FOUND_IN: pop(r3); pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); match = r3.s->matches[tidx].head; r3.i = FALSE; while (match != NULL && !r3.i) { if (match->base + match->offset >= r1.i && match->base + match->offset <= r2.i) { r3.i = TRUE; } if (match->base + match->offset > r2.i) break; match = match->next; } push(r3); break; case OP_COUNT: pop(r1); r1.i = r1.s->matches[tidx].count; push(r1); break; case OP_OFFSET: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->base + match->offset; i++; match = match->next; } push(r3); break; case OP_LENGTH: pop(r2); pop(r1); ensure_defined(r1); match = r2.s->matches[tidx].head; i = 1; r3.i = UNDEFINED; while (match != NULL && r3.i == UNDEFINED) { if (r1.i == i) r3.i = match->match_length; i++; match = match->next; } push(r3); break; case OP_OF: found = 0; count = 0; pop(r1); while (!is_undef(r1)) { if (r1.s->matches[tidx].tail != NULL) found++; count++; pop(r1); } pop(r2); if (is_undef(r2)) r1.i = found >= count ? 1 : 0; else r1.i = found >= r2.i ? 1 : 0; push(r1); break; case OP_FILESIZE: r1.i = context->file_size; push(r1); break; case OP_ENTRYPOINT: r1.i = context->entry_point; push(r1); break; case OP_INT8: pop(r1); r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16: pop(r1); r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32: pop(r1); r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8: pop(r1); r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16: pop(r1); r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32: pop(r1); r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT8BE: pop(r1); r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT16BE: pop(r1); r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_INT32BE: pop(r1); r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT8BE: pop(r1); r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT16BE: pop(r1); r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_UINT32BE: pop(r1); r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); push(r1); break; case OP_CONTAINS: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); r1.i = memmem(r1.ss->c_string, r1.ss->length, r2.ss->c_string, r2.ss->length) != NULL; push(r1); break; case OP_IMPORT: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); result = yr_modules_load((char*) r1.p, context); if (result != ERROR_SUCCESS) stop = TRUE; break; case OP_MATCHES: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r1.ss->length == 0) { r1.i = FALSE; push(r1); break; } r1.i = yr_re_exec( (uint8_t*) r2.re->code, (uint8_t*) r1.ss->c_string, r1.ss->length, r2.re->flags | RE_FLAGS_SCAN, NULL, NULL) >= 0; push(r1); break; case OP_INT_TO_DBL: r1.i = *(uint64_t*)(ip + 1); ip += sizeof(uint64_t); r2 = stack[sp - r1.i]; if (is_undef(r2)) stack[sp - r1.i].i = UNDEFINED; else stack[sp - r1.i].d = (double) r2.i; break; case OP_STR_TO_BOOL: pop(r1); ensure_defined(r1); r1.i = r1.ss->length > 0; push(r1); break; case OP_INT_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i == r2.i; push(r1); break; case OP_INT_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i != r2.i; push(r1); break; case OP_INT_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i < r2.i; push(r1); break; case OP_INT_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i > r2.i; push(r1); break; case OP_INT_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i <= r2.i; push(r1); break; case OP_INT_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i >= r2.i; push(r1); break; case OP_INT_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i + r2.i; push(r1); break; case OP_INT_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i - r2.i; push(r1); break; case OP_INT_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.i * r2.i; push(r1); break; case OP_INT_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); if (r2.i != 0) r1.i = r1.i / r2.i; else r1.i = UNDEFINED; push(r1); break; case OP_INT_MINUS: pop(r1); ensure_defined(r1); r1.i = -r1.i; push(r1); break; case OP_DBL_LT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d < r2.d; push(r1); break; case OP_DBL_GT: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d > r2.d; push(r1); break; case OP_DBL_LE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d <= r2.d; push(r1); break; case OP_DBL_GE: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d >= r2.d; push(r1); break; case OP_DBL_EQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d == r2.d; push(r1); break; case OP_DBL_NEQ: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.i = r1.d != r2.d; push(r1); break; case OP_DBL_ADD: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d + r2.d; push(r1); break; case OP_DBL_SUB: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d - r2.d; push(r1); break; case OP_DBL_MUL: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d * r2.d; push(r1); break; case OP_DBL_DIV: pop(r2); pop(r1); ensure_defined(r2); ensure_defined(r1); r1.d = r1.d / r2.d; push(r1); break; case OP_DBL_MINUS: pop(r1); ensure_defined(r1); r1.d = -r1.d; push(r1); break; case OP_STR_EQ: case OP_STR_NEQ: case OP_STR_LT: case OP_STR_LE: case OP_STR_GT: case OP_STR_GE: pop(r2); pop(r1); ensure_defined(r1); ensure_defined(r2); switch(*ip) { case OP_STR_EQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); break; case OP_STR_NEQ: r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); break; case OP_STR_LT: r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); break; case OP_STR_LE: r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); break; case OP_STR_GT: r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); break; case OP_STR_GE: r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); break; } push(r1); break; default: assert(FALSE); } if (timeout > 0) // timeout == 0 means no timeout { if (++cycle == 10) { if (difftime(time(NULL), start_time) > timeout) { #ifdef PROFILING_ENABLED assert(current_rule != NULL); current_rule->clock_ticks += clock() - start; #endif result = ERROR_SCAN_TIMEOUT; stop = TRUE; } cycle = 0; } } ip++; } yr_modules_unload_all(context); yr_free(stack); return result; } Commit Message: Fix issue #646 (#648) * Fix issue #646 and some edge cases with wide regexps using \b and \B * Rename function IS_WORD_CHAR to _yr_re_is_word_char CWE ID: CWE-125 Target: 1 Example 2: Code: static int eligible_child(struct wait_opts *wo, struct task_struct *p) { if (!eligible_pid(wo, p)) return 0; /* Wait for all children (clone and not) if __WALL is set; * otherwise, wait for clone children *only* if __WCLONE is * set; otherwise, wait for non-clone children *only*. (Note: * A "clone" child here is one that reports to its parent * using a signal other than SIGCHLD.) */ if (((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE)) && !(wo->wo_flags & __WALL)) return 0; return 1; } Commit Message: block: Fix io_context leak after failure of clone with CLONE_IO With CLONE_IO, parent's io_context->nr_tasks is incremented, but never decremented whenever copy_process() fails afterwards, which prevents exit_io_context() from calling IO schedulers exit functions. Give a task_struct to exit_io_context(), and call exit_io_context() instead of put_io_context() in copy_process() cleanup path. Signed-off-by: Louis Rilling <[email protected]> Signed-off-by: Jens Axboe <[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 jboolean Region_isComplex(JNIEnv* env, jobject region) { bool result = GetSkRegion(env, region)->isComplex(); return boolTojboolean(result); } Commit Message: Check that the parcel contained the expected amount of region data. DO NOT MERGE bug:20883006 Change-Id: Ib47a8ec8696dbc37e958b8dbceb43fcbabf6605b 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: bool AXLayoutObject::isSelected() const { if (!getLayoutObject() || !getNode()) return false; const AtomicString& ariaSelected = getAttribute(aria_selectedAttr); if (equalIgnoringCase(ariaSelected, "true")) return true; AXObject* focusedObject = axObjectCache().focusedObject(); if (ariaRoleAttribute() == ListBoxOptionRole && focusedObject && focusedObject->activeDescendant() == this) { return true; } if (isTabItem() && isTabItemSelected()) return true; return false; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254 Target: 1 Example 2: Code: static int req_err(lua_State *L) { return req_log_at(L, APLOG_ERR); } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 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: raptor_libxml_sax_init(raptor_sax2* sax2) { xmlSAXHandler *sax = &sax2->sax; sax->internalSubset = raptor_libxml_internalSubset; sax->isStandalone = raptor_libxml_isStandalone; sax->hasInternalSubset = raptor_libxml_hasInternalSubset; sax->hasExternalSubset = raptor_libxml_hasExternalSubset; sax->resolveEntity = raptor_libxml_resolveEntity; sax->getEntity = raptor_libxml_getEntity; sax->getParameterEntity = raptor_libxml_getParameterEntity; sax->entityDecl = raptor_libxml_entityDecl; sax->attributeDecl = NULL; /* attributeDecl */ sax->elementDecl = NULL; /* elementDecl */ sax->notationDecl = NULL; /* notationDecl */ sax->unparsedEntityDecl = raptor_libxml_unparsedEntityDecl; sax->setDocumentLocator = raptor_libxml_set_document_locator; sax->startDocument = raptor_libxml_startDocument; sax->endDocument = raptor_libxml_endDocument; sax->startElement= raptor_sax2_start_element; sax->endElement= raptor_sax2_end_element; sax->reference = NULL; /* reference */ sax->characters= raptor_sax2_characters; sax->cdataBlock= raptor_sax2_cdata; /* like <![CDATA[...]> */ sax->ignorableWhitespace= raptor_sax2_cdata; sax->processingInstruction = NULL; /* processingInstruction */ sax->comment = raptor_sax2_comment; /* comment */ sax->warning = (warningSAXFunc)raptor_libxml_warning; sax->error = (errorSAXFunc)raptor_libxml_error; sax->fatalError = (fatalErrorSAXFunc)raptor_libxml_fatal_error; sax->serror = (xmlStructuredErrorFunc)raptor_libxml_xmlStructuredError_handler_parsing; #ifdef RAPTOR_LIBXML_XMLSAXHANDLER_EXTERNALSUBSET sax->externalSubset = raptor_libxml_externalSubset; #endif #ifdef RAPTOR_LIBXML_XMLSAXHANDLER_INITIALIZED sax->initialized = 1; #endif } 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:
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 __u8 *cp_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { unsigned long quirks = (unsigned long)hid_get_drvdata(hdev); unsigned int i; if (!(quirks & CP_RDESC_SWAPPED_MIN_MAX)) return rdesc; for (i = 0; i < *rsize - 4; i++) if (rdesc[i] == 0x29 && rdesc[i + 2] == 0x19) { rdesc[i] = 0x19; rdesc[i + 2] = 0x29; swap(rdesc[i + 3], rdesc[i + 1]); } return rdesc; } Commit Message: HID: hid-cypress: validate length of report Make sure we have enough of a report structure to validate before looking at it. Reported-by: Benoit Camredon <[email protected]> Tested-by: Benoit Camredon <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: Target: 1 Example 2: Code: PHP_FUNCTION(pg_consume_input) { zval *pgsql_link; int id = -1; PGconn *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { return; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, pgsql_link, id, "PostgreSQL link", le_link, le_plink); RETURN_BOOL(PQconsumeInput(pgsql)); } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: tTcpIpPacketParsingResult ParaNdis_CheckSumVerify( tCompletePhysicalAddress *pDataPages, ULONG ulDataLength, ULONG ulStartOffset, ULONG flags, LPCSTR caller) { IPHeader *pIpHeader = (IPHeader *) RtlOffsetToPointer(pDataPages[0].Virtual, ulStartOffset); tTcpIpPacketParsingResult res = QualifyIpPacket(pIpHeader, ulDataLength); if (res.ipStatus == ppresNotIP || res.ipCheckSum == ppresIPTooShort) return res; if (res.ipStatus == ppresIPV4) { if (flags & pcrIpChecksum) res = VerifyIpChecksum(&pIpHeader->v4, res, (flags & pcrFixIPChecksum) != 0); if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV4Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV4Checksum)); } } else /* UDP */ { if (flags & pcrUdpV4Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV4Checksum)); } } } } else if (res.ipStatus == ppresIPV6) { if(res.xxpStatus == ppresXxpKnown) { if (res.TcpUdp == ppresIsTCP) /* TCP */ { if(flags & pcrTcpV6Checksum) { res = VerifyTcpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixTcpV6Checksum)); } } else /* UDP */ { if (flags & pcrUdpV6Checksum) { res = VerifyUdpChecksum(pDataPages, ulDataLength, ulStartOffset, res, flags & (pcrFixPHChecksum | pcrFixUdpV6Checksum)); } } } } PrintOutParsingResult(res, 1, caller); return res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int lua_websocket_read(lua_State *L) { apr_socket_t *sock; apr_status_t rv; int n = 0; apr_size_t len = 1; apr_size_t plen = 0; unsigned short payload_short = 0; apr_uint64_t payload_long = 0; unsigned char *mask_bytes; char byte; int plaintext; request_rec *r = ap_lua_check_request_rec(L, 1); plaintext = ap_lua_ssl_is_https(r->connection) ? 0 : 1; mask_bytes = apr_pcalloc(r->pool, 4); sock = ap_get_conn_socket(r->connection); /* Get opcode and FIN bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { unsigned char ubyte, fin, opcode, mask, payload; ubyte = (unsigned char)byte; /* fin bit is the first bit */ fin = ubyte >> (CHAR_BIT - 1); /* opcode is the last four bits (there's 3 reserved bits we don't care about) */ opcode = ubyte & 0xf; /* Get the payload length and mask bit */ if (plaintext) { rv = apr_socket_recv(sock, &byte, &len); } else { rv = lua_websocket_readbytes(r->connection, &byte, 1); } if (rv == APR_SUCCESS) { ubyte = (unsigned char)byte; /* Mask is the first bit */ mask = ubyte >> (CHAR_BIT - 1); /* Payload is the last 7 bits */ payload = ubyte & 0x7f; plen = payload; /* Extended payload? */ if (payload == 126) { len = 2; if (plaintext) { /* XXX: apr_socket_recv does not receive len bits, only up to len bits! */ rv = apr_socket_recv(sock, (char*) &payload_short, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_short, 2); } payload_short = ntohs(payload_short); if (rv == APR_SUCCESS) { plen = payload_short; } else { return 0; } } /* Super duper extended payload? */ if (payload == 127) { len = 8; if (plaintext) { rv = apr_socket_recv(sock, (char*) &payload_long, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) &payload_long, 8); } if (rv == APR_SUCCESS) { plen = ap_ntoh64(&payload_long); } else { return 0; } } ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Websocket: Reading %" APR_SIZE_T_FMT " (%s) bytes, masking is %s. %s", plen, (payload >= 126) ? "extra payload" : "no extra payload", mask ? "on" : "off", fin ? "This is a final frame" : "more to follow"); if (mask) { len = 4; if (plaintext) { rv = apr_socket_recv(sock, (char*) mask_bytes, &len); } else { rv = lua_websocket_readbytes(r->connection, (char*) mask_bytes, 4); } if (rv != APR_SUCCESS) { return 0; } } if (plen < (HUGE_STRING_LEN*1024) && plen > 0) { apr_size_t remaining = plen; apr_size_t received; apr_off_t at = 0; char *buffer = apr_palloc(r->pool, plen+1); buffer[plen] = 0; if (plaintext) { while (remaining > 0) { received = remaining; rv = apr_socket_recv(sock, buffer+at, &received); if (received > 0 ) { remaining -= received; at += received; } } ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: Frame contained %" APR_OFF_T_FMT " bytes, pushed to Lua stack", at); } else { rv = lua_websocket_readbytes(r->connection, buffer, remaining); ap_log_rerror(APLOG_MARK, APLOG_TRACE1, 0, r, "Websocket: SSL Frame contained %" APR_SIZE_T_FMT " bytes, "\ "pushed to Lua stack", remaining); } if (mask) { for (n = 0; n < plen; n++) { buffer[n] ^= mask_bytes[n%4]; } } lua_pushlstring(L, buffer, (size_t) plen); /* push to stack */ lua_pushboolean(L, fin); /* push FIN bit to stack as boolean */ return 2; } /* Decide if we need to react to the opcode or not */ if (opcode == 0x09) { /* ping */ char frame[2]; plen = 2; frame[0] = 0x8A; frame[1] = 0; apr_socket_send(sock, frame, &plen); /* Pong! */ lua_websocket_read(L); /* read the next frame instead */ } } } return 0; } Commit Message: *) SECURITY: CVE-2015-0228 (cve.mitre.org) mod_lua: A maliciously crafted websockets PING after a script calls r:wsupgrade() can cause a child process crash. [Edward Lu <Chaosed0 gmail.com>] Discovered by Guido Vranken <guidovranken gmail.com> Submitted by: Edward Lu Committed by: covener git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1657261 13f79535-47bb-0310-9956-ffa450edef68 CWE ID: CWE-20 Target: 1 Example 2: Code: void RenderFrameHostImpl::BindMediaInterfaceFactoryRequest( media::mojom::InterfaceFactoryRequest request) { DCHECK(!media_interface_proxy_); media_interface_proxy_.reset(new MediaInterfaceProxy( this, std::move(request), base::Bind(&RenderFrameHostImpl::OnMediaInterfaceFactoryConnectionError, base::Unretained(this)))); } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static struct file *find_readable_file_locked(struct nfs4_file *f) { struct file *ret; lockdep_assert_held(&f->fi_lock); ret = __nfs4_get_fd(f, O_RDONLY); if (!ret) ret = __nfs4_get_fd(f, O_RDWR); return ret; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int parse_token(char **name, char **value, char **cp) { char *end; if (!name || !value || !cp) return -BLKID_ERR_PARAM; if (!(*value = strchr(*cp, '='))) return 0; **value = '\0'; *name = strip_line(*cp); *value = skip_over_blank(*value + 1); if (**value == '"') { end = strchr(*value + 1, '"'); if (!end) { DBG(READ, ul_debug("unbalanced quotes at: %s", *value)); *cp = *value; return -BLKID_ERR_CACHE; } (*value)++; *end = '\0'; end++; } else { end = skip_over_word(*value); if (*end) { *end = '\0'; end++; } } *cp = end; return 1; } Commit Message: libblkid: care about unsafe chars in cache The high-level libblkid API uses /run/blkid/blkid.tab cache to store probing results. The cache format is <device NAME="value" ...>devname</device> and unfortunately the cache code does not escape quotation marks: # mkfs.ext4 -L 'AAA"BBB' # cat /run/blkid/blkid.tab ... <device ... LABEL="AAA"BBB" ...>/dev/sdb1</device> such string is later incorrectly parsed and blkid(8) returns nonsenses. And for use-cases like # eval $(blkid -o export /dev/sdb1) it's also insecure. Note that mount, udevd and blkid -p are based on low-level libblkid API, it bypass the cache and directly read data from the devices. The current udevd upstream does not depend on blkid(8) output at all, it's directly linked with the library and all unsafe chars are encoded by \x<hex> notation. # mkfs.ext4 -L 'X"`/tmp/foo` "' /dev/sdb1 # udevadm info --export-db | grep LABEL ... E: ID_FS_LABEL=X__/tmp/foo___ E: ID_FS_LABEL_ENC=X\x22\x60\x2ftmp\x2ffoo\x60\x20\x22 Signed-off-by: Karel Zak <[email protected]> CWE ID: CWE-77 Target: 1 Example 2: Code: static TRBCCode xhci_configure_slot(XHCIState *xhci, unsigned int slotid, uint64_t pictx, bool dc) { dma_addr_t ictx, octx; uint32_t ictl_ctx[2]; uint32_t slot_ctx[4]; uint32_t islot_ctx[4]; uint32_t ep_ctx[5]; int i; TRBCCode res; trace_usb_xhci_slot_configure(slotid); assert(slotid >= 1 && slotid <= xhci->numslots); ictx = xhci_mask64(pictx); octx = xhci->slots[slotid-1].ctx; DPRINTF("xhci: input context at "DMA_ADDR_FMT"\n", ictx); DPRINTF("xhci: output context at "DMA_ADDR_FMT"\n", octx); if (dc) { for (i = 2; i <= 31; i++) { if (xhci->slots[slotid-1].eps[i-1]) { xhci_disable_ep(xhci, slotid, i); } } xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx)); slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT); slot_ctx[3] |= SLOT_ADDRESSED << SLOT_STATE_SHIFT; DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n", slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]); xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx)); return CC_SUCCESS; } xhci_dma_read_u32s(xhci, ictx, ictl_ctx, sizeof(ictl_ctx)); if ((ictl_ctx[0] & 0x3) != 0x0 || (ictl_ctx[1] & 0x3) != 0x1) { DPRINTF("xhci: invalid input context control %08x %08x\n", ictl_ctx[0], ictl_ctx[1]); return CC_TRB_ERROR; } xhci_dma_read_u32s(xhci, ictx+32, islot_ctx, sizeof(islot_ctx)); xhci_dma_read_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx)); if (SLOT_STATE(slot_ctx[3]) < SLOT_ADDRESSED) { DPRINTF("xhci: invalid slot state %08x\n", slot_ctx[3]); return CC_CONTEXT_STATE_ERROR; } xhci_free_device_streams(xhci, slotid, ictl_ctx[0] | ictl_ctx[1]); for (i = 2; i <= 31; i++) { if (ictl_ctx[0] & (1<<i)) { xhci_disable_ep(xhci, slotid, i); } if (ictl_ctx[1] & (1<<i)) { xhci_dma_read_u32s(xhci, ictx+32+(32*i), ep_ctx, sizeof(ep_ctx)); DPRINTF("xhci: input ep%d.%d context: %08x %08x %08x %08x %08x\n", i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2], ep_ctx[3], ep_ctx[4]); xhci_disable_ep(xhci, slotid, i); res = xhci_enable_ep(xhci, slotid, i, octx+(32*i), ep_ctx); if (res != CC_SUCCESS) { return res; } DPRINTF("xhci: output ep%d.%d context: %08x %08x %08x %08x %08x\n", i/2, i%2, ep_ctx[0], ep_ctx[1], ep_ctx[2], ep_ctx[3], ep_ctx[4]); xhci_dma_write_u32s(xhci, octx+(32*i), ep_ctx, sizeof(ep_ctx)); } } res = xhci_alloc_device_streams(xhci, slotid, ictl_ctx[1]); if (res != CC_SUCCESS) { for (i = 2; i <= 31; i++) { if (ictl_ctx[1] & (1 << i)) { xhci_disable_ep(xhci, slotid, i); } } return res; } slot_ctx[3] &= ~(SLOT_STATE_MASK << SLOT_STATE_SHIFT); slot_ctx[3] |= SLOT_CONFIGURED << SLOT_STATE_SHIFT; slot_ctx[0] &= ~(SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT); slot_ctx[0] |= islot_ctx[0] & (SLOT_CONTEXT_ENTRIES_MASK << SLOT_CONTEXT_ENTRIES_SHIFT); DPRINTF("xhci: output slot context: %08x %08x %08x %08x\n", slot_ctx[0], slot_ctx[1], slot_ctx[2], slot_ctx[3]); xhci_dma_write_u32s(xhci, octx, slot_ctx, sizeof(slot_ctx)); return CC_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: static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; if (WARN_ON(ret < match32->match_size)) return -EINVAL; growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; WARN_ON(type == EBT_COMPAT_TARGET && size_left); match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; } Commit Message: netfilter: ebtables: CONFIG_COMPAT: don't trust userland offsets We need to make sure the offsets are not out of range of the total size. Also check that they are in ascending order. The WARN_ON triggered by syzkaller (it sets panic_on_warn) is changed to also bail out, no point in continuing parsing. Briefly tested with simple ruleset of -A INPUT --limit 1/s' --log plus jump to custom chains using 32bit ebtables binary. Reported-by: <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-787 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int module_load( YR_SCAN_CONTEXT* context, YR_OBJECT* module_object, void* module_data, size_t module_data_size) { set_integer(1, module_object, "constants.one"); set_integer(2, module_object, "constants.two"); set_string("foo", module_object, "constants.foo"); set_string("", module_object, "constants.empty"); set_integer(1, module_object, "struct_array[1].i"); set_integer(0, module_object, "integer_array[%i]", 0); set_integer(1, module_object, "integer_array[%i]", 1); set_integer(2, module_object, "integer_array[%i]", 2); set_string("foo", module_object, "string_array[%i]", 0); set_string("bar", module_object, "string_array[%i]", 1); set_string("baz", module_object, "string_array[%i]", 2); set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); set_string("foo", module_object, "string_dict[%s]", "foo"); set_string("bar", module_object, "string_dict[\"bar\"]"); set_string("foo", module_object, "struct_dict[%s].s", "foo"); set_integer(1, module_object, "struct_dict[%s].i", "foo"); return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119 Target: 1 Example 2: Code: PaymentsRequestVisualTest() {} Commit Message: [Payments] Prohibit opening payments UI in background tab. Before this patch, calling PaymentRequest.show() would bring the background window to the foreground, which allows a page to open a pop-under. This patch adds a check for the browser window being active (in foreground) in PaymentRequest.show(). If the window is not active (in background), then PaymentRequest.show() promise is rejected with "AbortError: User cancelled request." No UI is shown in that case. After this patch, calling PaymentRequest.show() does not bring the background window to the foreground, thus preventing opening a pop-under. Bug: 768230 Change-Id: I2b90f9086ceca5ed7b7bdf8045e44d7e99d566d0 Reviewed-on: https://chromium-review.googlesource.com/681843 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#504406} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool CrossesExtensionProcessBoundary( const ExtensionSet& extensions, const GURL& old_url, const GURL& new_url, bool should_consider_workaround) { const extensions::Extension* old_url_extension = GetNonBookmarkAppExtension( extensions, old_url); const extensions::Extension* new_url_extension = GetNonBookmarkAppExtension( extensions, new_url); if (should_consider_workaround) { bool old_url_is_hosted_app = old_url_extension && !old_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(old_url_extension); bool new_url_is_normal_or_hosted = !new_url_extension || (!new_url_extension->web_extent().is_empty() && !AppIsolationInfo::HasIsolatedStorage(new_url_extension)); bool either_is_web_store = (old_url_extension && old_url_extension->id() == extensions::kWebStoreAppId) || (new_url_extension && new_url_extension->id() == extensions::kWebStoreAppId); if (old_url_is_hosted_app && new_url_is_normal_or_hosted && !either_is_web_store) return false; } return old_url_extension != new_url_extension; } 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: static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, struct idpair *idmap) { if (!(rold->live & REG_LIVE_READ)) /* explored state didn't use this */ return true; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) return true; if (rold->type == NOT_INIT) /* explored state can't have used this */ return true; if (rcur->type == NOT_INIT) return false; switch (rold->type) { case SCALAR_VALUE: if (rcur->type == SCALAR_VALUE) { /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); } else { /* if we knew anything about the old value, we're not * equal, because we can't know anything about the * scalar value of the pointer in the new value. */ return rold->umin_value == 0 && rold->umax_value == U64_MAX && rold->smin_value == S64_MIN && rold->smax_value == S64_MAX && tnum_is_unknown(rold->var_off); } case PTR_TO_MAP_VALUE: /* If the new min/max/var_off satisfy the old ones and * everything else matches, we are OK. * We don't care about the 'id' value, because nothing * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) */ return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_MAP_VALUE_OR_NULL: /* a PTR_TO_MAP_VALUE could be safe to use as a * PTR_TO_MAP_VALUE_OR_NULL into the same map. * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- * checked, doing so could have affected others with the same * id, and we can't check for that because we lost the id when * we converted to a PTR_TO_MAP_VALUE. */ if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) return false; if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) return false; /* Check our ids match any regs they're supposed to */ return check_ids(rold->id, rcur->id, idmap); case PTR_TO_PACKET_META: case PTR_TO_PACKET: if (rcur->type != rold->type) return false; /* We must have at least as much range as the old ptr * did, so that any accesses which were safe before are * still safe. This is true even if old range < old off, * since someone could have accessed through (ptr - k), or * even done ptr -= k in a register, to get a safe access. */ if (rold->range > rcur->range) return false; /* If the offsets don't match, we can't trust our alignment; * nor can we be sure that we won't fall out of range. */ if (rold->off != rcur->off) return false; /* id relations must be preserved */ if (rold->id && !check_ids(rold->id, rcur->id, idmap)) return false; /* new val must satisfy old val knowledge */ return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); case PTR_TO_CTX: case CONST_PTR_TO_MAP: case PTR_TO_STACK: case PTR_TO_PACKET_END: /* Only valid matches are exact, which memcmp() above * would have accepted */ default: /* Don't know what's going on, just say it's not safe */ return false; } /* Shouldn't get here; if we do, say it's not safe */ WARN_ON_ONCE(1); return false; } Commit Message: bpf: don't prune branches when a scalar is replaced with a pointer This could be made safe by passing through a reference to env and checking for env->allow_ptr_leaks, but it would only work one way and is probably not worth the hassle - not doing it will not directly lead to program rejection. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst, bool can_sleep) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); int err; dst = ip6_sk_dst_check(sk, dst, fl6); err = ip6_dst_lookup_tail(sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; if (can_sleep) fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP; return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } Commit Message: ipv6: udp packets following an UFO enqueued packet need also be handled by UFO In the following scenario the socket is corked: If the first UDP packet is larger then the mtu we try to append it to the write queue via ip6_ufo_append_data. A following packet, which is smaller than the mtu would be appended to the already queued up gso-skb via plain ip6_append_data. This causes random memory corruptions. In ip6_ufo_append_data we also have to be careful to not queue up the same skb multiple times. So setup the gso frame only when no first skb is available. This also fixes a shortcoming where we add the current packet's length to cork->length but return early because of a packet > mtu with dontfrag set (instead of sutracting it again). Found with trinity. Cc: YOSHIFUJI Hideaki <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Reported-by: Dmitry Vyukov <[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: LONG ValidateSignature(HWND hDlg, const char* path) { LONG r; WINTRUST_DATA trust_data = { 0 }; WINTRUST_FILE_INFO trust_file = { 0 }; GUID guid_generic_verify = // WINTRUST_ACTION_GENERIC_VERIFY_V2 { 0xaac56b, 0xcd44, 0x11d0,{ 0x8c, 0xc2, 0x0, 0xc0, 0x4f, 0xc2, 0x95, 0xee } }; char *signature_name; size_t i, len; signature_name = GetSignatureName(path); if (signature_name == NULL) { uprintf("PKI: Could not get signature name"); MessageBoxExU(hDlg, lmprintf(MSG_284), lmprintf(MSG_283), MB_OK | MB_ICONERROR | MB_IS_RTL, selected_langid); return TRUST_E_NOSIGNATURE; } for (i = 0; i < ARRAYSIZE(cert_name); i++) { len = strlen(cert_name[i]); if (strncmp(signature_name, cert_name[i], len) == 0) { if ((len >= strlen(signature_name)) || isspace(signature_name[len])) break; } } if (i >= ARRAYSIZE(cert_name)) { uprintf("PKI: Signature '%s' is unexpected...", signature_name); if (MessageBoxExU(hDlg, lmprintf(MSG_285, signature_name), lmprintf(MSG_283), MB_YESNO | MB_ICONWARNING | MB_IS_RTL, selected_langid) != IDYES) return TRUST_E_EXPLICIT_DISTRUST; } trust_file.cbStruct = sizeof(trust_file); trust_file.pcwszFilePath = utf8_to_wchar(path); if (trust_file.pcwszFilePath == NULL) { uprintf("PKI: Unable to convert '%s' to UTF16", path); return ERROR_SEVERITY_ERROR | FAC(FACILITY_CERT) | ERROR_NOT_ENOUGH_MEMORY; } trust_data.cbStruct = sizeof(trust_data); trust_data.dwUIChoice = WTD_UI_ALL; trust_data.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN; trust_data.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN | 0x400; trust_data.dwUnionChoice = WTD_CHOICE_FILE; trust_data.pFile = &trust_file; r = WinVerifyTrust(NULL, &guid_generic_verify, &trust_data); safe_free(trust_file.pcwszFilePath); return r; } Commit Message: [pki] fix https://www.kb.cert.org/vuls/id/403768 * This commit effectively fixes https://www.kb.cert.org/vuls/id/403768 (CVE-2017-13083) as it is described per its revision 11, which is the latest revision at the time of this commit, by disabling Windows prompts, enacted during signature validation, that allow the user to bypass the intended signature verification checks. * It needs to be pointed out that the vulnerability ("allow(ing) the use of a self-signed certificate"), which relies on the end-user actively ignoring a Windows prompt that tells them that the update failed the signature validation whilst also advising against running it, is being fully addressed, even as the update protocol remains HTTP. * It also need to be pointed out that the extended delay (48 hours) between the time the vulnerability was reported and the moment it is fixed in our codebase has to do with the fact that the reporter chose to deviate from standard security practices by not disclosing the details of the vulnerability with us, be it publicly or privately, before creating the cert.org report. The only advance notification we received was a generic note about the use of HTTP vs HTTPS, which, as have established, is not immediately relevant to addressing the reported vulnerability. * Closes #1009 * Note: The other vulnerability scenario described towards the end of #1009, which doesn't have to do with the "lack of CA checking", will be addressed separately. CWE ID: CWE-494 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 EnterpriseEnrollmentScreen::OnPolicyStateChanged( policy::CloudPolicySubsystem::PolicySubsystemState state, policy::CloudPolicySubsystem::ErrorDetails error_details) { if (is_showing_) { switch (state) { case policy::CloudPolicySubsystem::UNENROLLED: return; case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN: case policy::CloudPolicySubsystem::LOCAL_ERROR: actor_->ShowFatalEnrollmentError(); break; case policy::CloudPolicySubsystem::UNMANAGED: actor_->ShowAccountError(); break; case policy::CloudPolicySubsystem::NETWORK_ERROR: actor_->ShowNetworkEnrollmentError(); break; case policy::CloudPolicySubsystem::TOKEN_FETCHED: WriteInstallAttributesData(); return; case policy::CloudPolicySubsystem::SUCCESS: registrar_.reset(); UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentOK, policy::kMetricEnrollmentSize); actor_->ShowConfirmationScreen(); return; } if (state == policy::CloudPolicySubsystem::UNMANAGED) { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentNotSupported, policy::kMetricEnrollmentSize); } else { UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment, policy::kMetricEnrollmentPolicyFailed, policy::kMetricEnrollmentSize); } LOG(WARNING) << "Policy subsystem error during enrollment: " << state << " details: " << error_details; } registrar_.reset(); g_browser_process->browser_policy_connector()->DeviceStopAutoRetry(); } 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: 1 Example 2: Code: void pin_insert(struct fs_pin *pin, struct vfsmount *m) { pin_insert_group(pin, m, &m->mnt_sb->s_pins); } Commit Message: fs_pin: Allow for the possibility that m_list or s_list go unused. This is needed to support lazily umounting locked mounts. Because the entire unmounted subtree needs to stay together until there are no users with references to any part of the subtree. To support this guarantee that the fs_pin m_list and s_list nodes are initialized by initializing them in init_fs_pin allowing for the possibility that pin_insert_group does not touch them. Further use hlist_del_init in pin_remove so that there is a hlist_unhashed test before the list we attempt to update the previous list item. Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 BnCrypto::readVector(const Parcel &data, Vector<uint8_t> &vector) const { uint32_t size = data.readInt32(); vector.insertAt((size_t)0, size); data.read(vector.editArray(), size); } Commit Message: Fix information disclosure in mediadrmserver Test:POC provided in bug Bug:79218474 Change-Id: Iba12c07a5e615f8ed234b01ac53e3559ba9ac12e (cherry picked from commit c1bf68a8d1321d7cdf7da6933f0b89b171d251c6) 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: Chapters::Chapters( Segment* pSegment, long long payload_start, long long payload_size, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(payload_start), m_size(payload_size), m_element_start(element_start), m_element_size(element_size), m_editions(NULL), m_editions_size(0), m_editions_count(0) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: void RenderFrameImpl::DecodeDataURL(const CommonNavigationParams& common_params, const CommitNavigationParams& commit_params, std::string* mime_type, std::string* charset, std::string* data, GURL* base_url) { GURL data_url = common_params.url; #if defined(OS_ANDROID) if (!commit_params.data_url_as_string.empty()) { #if DCHECK_IS_ON() { std::string mime_type_tmp, charset_tmp, data_tmp; DCHECK(net::DataURL::Parse(data_url, &mime_type_tmp, &charset_tmp, &data_tmp)); DCHECK(data_tmp.empty()); } #endif data_url = GURL(commit_params.data_url_as_string); if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme)) { data_url = common_params.url; } } #endif if (net::DataURL::Parse(data_url, mime_type, charset, data)) { *base_url = common_params.base_url_for_data_url.is_empty() ? common_params.url : common_params.base_url_for_data_url; } else { CHECK(false) << "Invalid URL passed: " << common_params.url.possibly_invalid_spec(); } } 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: xsltNumberFormat(xsltTransformContextPtr ctxt, xsltNumberDataPtr data, xmlNodePtr node) { xmlBufferPtr output = NULL; int amount, i; double number; xsltFormat tokens; int tempformat = 0; if ((data->format == NULL) && (data->has_format != 0)) { data->format = xsltEvalAttrValueTemplate(ctxt, data->node, (const xmlChar *) "format", XSLT_NAMESPACE); tempformat = 1; } if (data->format == NULL) { return; } output = xmlBufferCreate(); if (output == NULL) goto XSLT_NUMBER_FORMAT_END; xsltNumberFormatTokenize(data->format, &tokens); /* * Evaluate the XPath expression to find the value(s) */ if (data->value) { amount = xsltNumberFormatGetValue(ctxt->xpathCtxt, node, data->value, &number); if (amount == 1) { xsltNumberFormatInsertNumbers(data, &number, 1, &tokens, output); } } else if (data->level) { if (xmlStrEqual(data->level, (const xmlChar *) "single")) { amount = xsltNumberFormatGetMultipleLevel(ctxt, node, data->countPat, data->fromPat, &number, 1, data->doc, data->node); if (amount == 1) { xsltNumberFormatInsertNumbers(data, &number, 1, &tokens, output); } } else if (xmlStrEqual(data->level, (const xmlChar *) "multiple")) { double numarray[1024]; int max = sizeof(numarray)/sizeof(numarray[0]); amount = xsltNumberFormatGetMultipleLevel(ctxt, node, data->countPat, data->fromPat, numarray, max, data->doc, data->node); if (amount > 0) { xsltNumberFormatInsertNumbers(data, numarray, amount, &tokens, output); } } else if (xmlStrEqual(data->level, (const xmlChar *) "any")) { amount = xsltNumberFormatGetAnyLevel(ctxt, node, data->countPat, data->fromPat, &number, data->doc, data->node); if (amount > 0) { xsltNumberFormatInsertNumbers(data, &number, 1, &tokens, output); } } } /* Insert number as text node */ xsltCopyTextString(ctxt, ctxt->insert, xmlBufferContent(output), 0); if (tokens.start != NULL) xmlFree(tokens.start); if (tokens.end != NULL) xmlFree(tokens.end); for (i = 0;i < tokens.nTokens;i++) { if (tokens.tokens[i].separator != NULL) xmlFree(tokens.tokens[i].separator); } XSLT_NUMBER_FORMAT_END: if (tempformat == 1) { /* The format need to be recomputed each time */ data->format = NULL; } if (output != NULL) xmlBufferFree(output); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static unsigned char mincore_page(struct address_space *mapping, pgoff_t pgoff) { unsigned char present = 0; struct page *page; /* * When tmpfs swaps out a page from a file, any process mapping that * file will not get a swp_entry_t in its pte, but rather it is like * any other file mapping (ie. marked !present and faulted in with * tmpfs's .fault). So swapped out tmpfs mappings are tested here. */ #ifdef CONFIG_SWAP if (shmem_mapping(mapping)) { page = find_get_entry(mapping, pgoff); /* * shmem/tmpfs may return swap: account for swapcache * page too. */ if (xa_is_value(page)) { swp_entry_t swp = radix_to_swp_entry(page); page = find_get_page(swap_address_space(swp), swp_offset(swp)); } } else page = find_get_page(mapping, pgoff); #else page = find_get_page(mapping, pgoff); #endif if (page) { present = PageUptodate(page); put_page(page); } return present; } Commit Message: Change mincore() to count "mapped" pages rather than "cached" pages The semantics of what "in core" means for the mincore() system call are somewhat unclear, but Linux has always (since 2.3.52, which is when mincore() was initially done) treated it as "page is available in page cache" rather than "page is mapped in the mapping". The problem with that traditional semantic is that it exposes a lot of system cache state that it really probably shouldn't, and that users shouldn't really even care about. So let's try to avoid that information leak by simply changing the semantics to be that mincore() counts actual mapped pages, not pages that might be cheaply mapped if they were faulted (note the "might be" part of the old semantics: being in the cache doesn't actually guarantee that you can access them without IO anyway, since things like network filesystems may have to revalidate the cache before use). In many ways the old semantics were somewhat insane even aside from the information leak issue. From the very beginning (and that beginning is a long time ago: 2.3.52 was released in March 2000, I think), the code had a comment saying Later we can get more picky about what "in core" means precisely. and this is that "later". Admittedly it is much later than is really comfortable. NOTE! This is a real semantic change, and it is for example known to change the output of "fincore", since that program literally does a mmmap without populating it, and then doing "mincore()" on that mapping that doesn't actually have any pages in it. I'm hoping that nobody actually has any workflow that cares, and the info leak is real. We may have to do something different if it turns out that people have valid reasons to want the old semantics, and if we can limit the information leak sanely. Cc: Kevin Easton <[email protected]> Cc: Jiri Kosina <[email protected]> Cc: Masatake YAMATO <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Greg KH <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Michal Hocko <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: dbus_send_state_signal(vrrp_t *vrrp) { gchar *object_path; GVariant *args; /* the interface will go through the initial state changes before * the main loop can be started and global_connection initialised */ if (global_connection == NULL) return; object_path = dbus_object_create_path_instance(IF_NAME(IF_BASE_IFP(vrrp->ifp)), vrrp->vrid, vrrp->family); args = g_variant_new("(u)", vrrp->state); dbus_emit_signal(global_connection, object_path, DBUS_VRRP_INSTANCE_INTERFACE, "VrrpStatusChange", args); g_free(object_path); } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 ImageInputType::isImage() const { return true; } Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree. Once the fallback shadow tree was created, it was never recreated even if ensurePrimaryContent was called. Such situation happens by updating |src| attribute. BUG=589838 Review URL: https://codereview.chromium.org/1732753004 Cr-Commit-Position: refs/heads/master@{#377804} CWE ID: CWE-361 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 ImageLoader::updateFromElement() { Document* document = m_element->document(); if (!document->renderer()) return; AtomicString attr = m_element->imageSourceURL(); if (attr == m_failedLoadURL) return; CachedResourceHandle<CachedImage> newImage = 0; if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) { CachedResourceRequest request(ResourceRequest(document->completeURL(sourceURI(attr)))); request.setInitiator(element()); String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr); if (!crossOriginMode.isNull()) { StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials; updateRequestForAccessControl(request.mutableResourceRequest(), document->securityOrigin(), allowCredentials); } if (m_loadManually) { bool autoLoadOtherImages = document->cachedResourceLoader()->autoLoadImages(); document->cachedResourceLoader()->setAutoLoadImages(false); newImage = new CachedImage(request.resourceRequest()); newImage->setLoading(true); newImage->setOwningCachedResourceLoader(document->cachedResourceLoader()); document->cachedResourceLoader()->m_documentResources.set(newImage->url(), newImage.get()); document->cachedResourceLoader()->setAutoLoadImages(autoLoadOtherImages); } else newImage = document->cachedResourceLoader()->requestImage(request); if (!newImage && !pageIsBeingDismissed(document)) { m_failedLoadURL = attr; m_hasPendingErrorEvent = true; errorEventSender().dispatchEventSoon(this); } else clearFailedLoadURL(); } else if (!attr.isNull()) { m_element->dispatchEvent(Event::create(eventNames().errorEvent, false, false)); } CachedImage* oldImage = m_image.get(); if (newImage != oldImage) { if (m_hasPendingBeforeLoadEvent) { beforeLoadEventSender().cancelEvent(this); m_hasPendingBeforeLoadEvent = false; } if (m_hasPendingLoadEvent) { loadEventSender().cancelEvent(this); m_hasPendingLoadEvent = false; } if (m_hasPendingErrorEvent && newImage) { errorEventSender().cancelEvent(this); m_hasPendingErrorEvent = false; } m_image = newImage; m_hasPendingBeforeLoadEvent = !m_element->document()->isImageDocument() && newImage; m_hasPendingLoadEvent = newImage; m_imageComplete = !newImage; if (newImage) { if (!m_element->document()->isImageDocument()) { if (!m_element->document()->hasListenerType(Document::BEFORELOAD_LISTENER)) dispatchPendingBeforeLoadEvent(); else beforeLoadEventSender().dispatchEventSoon(this); } else updateRenderer(); newImage->addClient(this); } if (oldImage) oldImage->removeClient(this); } if (RenderImageResource* imageResource = renderImageResource()) imageResource->resetAnimation(); updatedHasPendingEvent(); } Commit Message: Error event was fired synchronously blowing away the input element from underneath. Remove the FIXME and fire it asynchronously using errorEventSender(). BUG=240124 Review URL: https://chromiumcodereview.appspot.com/14741011 git-svn-id: svn://svn.chromium.org/blink/trunk@150232 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-416 Target: 1 Example 2: Code: DEFINE_RUN_ONCE_STATIC(ossl_init_zlib) { /* Do nothing - we need to know about this for the later cleanup */ zlib_inited = 1; return 1; } Commit Message: CWE ID: CWE-330 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, PacketQueue *pq) { SCEnter(); DEBUG_ASSERT_FLOW_LOCKED(p->flow); SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt); /* assign the thread id to the flow */ if (unlikely(p->flow->thread_id == 0)) { p->flow->thread_id = (FlowThreadId)tv->id; #ifdef DEBUG } else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) { SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id); #endif } TcpSession *ssn = (TcpSession *)p->flow->protoctx; /* track TCP flags */ if (ssn != NULL) { ssn->tcp_packet_flags |= p->tcph->th_flags; if (PKT_IS_TOSERVER(p)) ssn->client.tcp_flags |= p->tcph->th_flags; else if (PKT_IS_TOCLIENT(p)) ssn->server.tcp_flags |= p->tcph->th_flags; /* check if we need to unset the ASYNC flag */ if (ssn->flags & STREAMTCP_FLAG_ASYNC && ssn->client.tcp_flags != 0 && ssn->server.tcp_flags != 0) { SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn); ssn->flags &= ~STREAMTCP_FLAG_ASYNC; } } /* update counters */ if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) { StatsIncr(tv, stt->counter_tcp_synack); } else if (p->tcph->th_flags & (TH_SYN)) { StatsIncr(tv, stt->counter_tcp_syn); } if (p->tcph->th_flags & (TH_RST)) { StatsIncr(tv, stt->counter_tcp_rst); } /* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */ if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) { StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK); } /* If we are on IPS mode, and got a drop action triggered from * the IP only module, or from a reassembled msg and/or from an * applayer detection, then drop the rest of the packets of the * same stream and avoid inspecting it any further */ if (StreamTcpCheckFlowDrops(p) == 1) { SCLogDebug("This flow/stream triggered a drop rule"); FlowSetNoPacketInspectionFlag(p->flow); DecodeSetNoPacketInspectionFlag(p); StreamTcpDisableAppLayer(p->flow); PACKET_DROP(p); /* return the segments to the pool */ StreamTcpSessionPktFree(p); SCReturnInt(0); } if (ssn == NULL || ssn->state == TCP_NONE) { if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) { goto error; } if (ssn != NULL) SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto); } else { /* special case for PKT_PSEUDO_STREAM_END packets: * bypass the state handling and various packet checks, * we care about reassembly here. */ if (p->flags & PKT_PSEUDO_STREAM_END) { if (PKT_IS_TOCLIENT(p)) { ssn->client.last_ack = TCP_GET_ACK(p); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq); } else { ssn->server.last_ack = TCP_GET_ACK(p); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq); } /* straight to 'skip' as we already handled reassembly */ goto skip; } /* check if the packet is in right direction, when we missed the SYN packet and picked up midstream session. */ if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) StreamTcpPacketSwitchDir(ssn, p); if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) { goto skip; } if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) { StreamTcpClearKeepAliveFlag(ssn, p); goto skip; } StreamTcpClearKeepAliveFlag(ssn, p); /* if packet is not a valid window update, check if it is perhaps * a bad window update that we should ignore (and alert on) */ if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0) if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0) if (StreamTcpPacketIsBadWindowUpdate(ssn,p)) goto skip; switch (ssn->state) { case TCP_SYN_SENT: if(StreamTcpPacketStateSynSent(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_SYN_RECV: if(StreamTcpPacketStateSynRecv(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_ESTABLISHED: if(StreamTcpPacketStateEstablished(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_FIN_WAIT1: if(StreamTcpPacketStateFinWait1(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_FIN_WAIT2: if(StreamTcpPacketStateFinWait2(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_CLOSING: if(StreamTcpPacketStateClosing(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_CLOSE_WAIT: if(StreamTcpPacketStateCloseWait(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_LAST_ACK: if(StreamTcpPacketStateLastAck(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_TIME_WAIT: if(StreamTcpPacketStateTimeWait(tv, p, stt, ssn, &stt->pseudo_queue)) { goto error; } break; case TCP_CLOSED: /* TCP session memory is not returned to pool until timeout. */ SCLogDebug("packet received on closed state"); break; default: SCLogDebug("packet received on default state"); break; } skip: if (ssn->state >= TCP_ESTABLISHED) { p->flags |= PKT_STREAM_EST; } } /* deal with a pseudo packet that is created upon receiving a RST * segment. To be sure we process both sides of the connection, we * inject a fake packet into the system, forcing reassembly of the * opposing direction. * There should be only one, but to be sure we do a while loop. */ if (ssn != NULL) { while (stt->pseudo_queue.len > 0) { SCLogDebug("processing pseudo packet / stream end"); Packet *np = PacketDequeue(&stt->pseudo_queue); if (np != NULL) { /* process the opposing direction of the original packet */ if (PKT_IS_TOSERVER(np)) { SCLogDebug("pseudo packet is to server"); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, np, NULL); } else { SCLogDebug("pseudo packet is to client"); StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, np, NULL); } /* enqueue this packet so we inspect it in detect etc */ PacketEnqueue(pq, np); } SCLogDebug("processing pseudo packet / stream end done"); } /* recalc the csum on the packet if it was modified */ if (p->flags & PKT_STREAM_MODIFIED) { ReCalculateChecksum(p); } /* check for conditions that may make us not want to log this packet */ /* streams that hit depth */ if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) { /* we can call bypass callback, if enabled */ if (StreamTcpBypassEnabled()) { PacketBypassCallback(p); } } if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) || (ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED)) { p->flags |= PKT_STREAM_NOPCAPLOG; } /* encrypted packets */ if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) || (PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY))) { p->flags |= PKT_STREAM_NOPCAPLOG; } if (ssn->flags & STREAMTCP_FLAG_BYPASS) { /* we can call bypass callback, if enabled */ if (StreamTcpBypassEnabled()) { PacketBypassCallback(p); } /* if stream is dead and we have no detect engine at all, bypass. */ } else if (g_detect_disabled && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) && StreamTcpBypassEnabled()) { SCLogDebug("bypass as stream is dead and we have no rules"); PacketBypassCallback(p); } } SCReturnInt(0); error: /* make sure we don't leave packets in our pseudo queue */ while (stt->pseudo_queue.len > 0) { Packet *np = PacketDequeue(&stt->pseudo_queue); if (np != NULL) { PacketEnqueue(pq, np); } } /* recalc the csum on the packet if it was modified */ if (p->flags & PKT_STREAM_MODIFIED) { ReCalculateChecksum(p); } if (StreamTcpInlineDropInvalid()) { /* disable payload inspection as we're dropping this packet * anyway. Doesn't disable all detection, so we can still * match on the stream event that was set. */ DecodeSetNoPayloadInspectionFlag(p); PACKET_DROP(p); } SCReturnInt(-1); } Commit Message: stream: support RST getting lost/ignored In case of a valid RST on a SYN, the state is switched to 'TCP_CLOSED'. However, the target of the RST may not have received it, or may not have accepted it. Also, the RST may have been injected, so the supposed sender may not actually be aware of the RST that was sent in it's name. In this case the previous behavior was to switch the state to CLOSED and accept no further TCP updates or stream reassembly. This patch changes this. It still switches the state to CLOSED, as this is by far the most likely to be correct. However, it will reconsider the state if the receiver continues to talk. To do this on each state change the previous state will be recorded in TcpSession::pstate. If a non-RST packet is received after a RST, this TcpSession::pstate is used to try to continue the conversation. If the (supposed) sender of the RST is also continueing the conversation as normal, it's highly likely it didn't send the RST. In this case a stream event is generated. Ticket: #2501 Reported-By: Kirill Shipulin 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: exsltFuncFunctionFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlXPathObjectPtr oldResult, ret; exsltFuncData *data; exsltFuncFunctionData *func; xmlNodePtr paramNode, oldInsert, fake; int oldBase; xsltStackElemPtr params = NULL, param; xsltTransformContextPtr tctxt = xsltXPathGetTransformContext(ctxt); int i, notSet; struct objChain { struct objChain *next; xmlXPathObjectPtr obj; }; struct objChain *savedObjChain = NULL, *savedObj; /* * retrieve func:function template */ data = (exsltFuncData *) xsltGetExtData (tctxt, EXSLT_FUNCTIONS_NAMESPACE); oldResult = data->result; data->result = NULL; func = (exsltFuncFunctionData*) xmlHashLookup2 (data->funcs, ctxt->context->functionURI, ctxt->context->function); /* * params handling */ if (nargs > func->nargs) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: called with too many arguments\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_INVALID_ARITY; return; } if (func->content != NULL) { paramNode = func->content->prev; } else paramNode = NULL; if ((paramNode == NULL) && (func->nargs != 0)) { xsltGenericError(xsltGenericErrorContext, "exsltFuncFunctionFunction: nargs != 0 and " "param == NULL\n"); return; } if (tctxt->funcLevel > MAX_FUNC_RECURSION) { xsltGenericError(xsltGenericErrorContext, "{%s}%s: detected a recursion\n", ctxt->context->functionURI, ctxt->context->function); ctxt->error = XPATH_MEMORY_ERROR; return; } tctxt->funcLevel++; /* * We have a problem with the evaluation of function parameters. * The original library code did not evaluate XPath expressions until * the last moment. After version 1.1.17 of the libxslt, the logic * of other parts of the library was changed, and the evaluation of * XPath expressions within parameters now takes place as soon as the * parameter is parsed/evaluated (xsltParseStylesheetCallerParam). * This means that the parameters need to be evaluated in lexical * order (since a variable is "in scope" as soon as it is declared). * However, on entry to this routine, the values (from the caller) are * in reverse order (held on the XPath context variable stack). To * accomplish what is required, I have added code to pop the XPath * objects off of the stack at the beginning and save them, then use * them (in the reverse order) as the params are evaluated. This * requires an xmlMalloc/xmlFree for each param set by the caller, * which is not very nice. There is probably a much better solution * (like change other code to delay the evaluation). */ /* * In order to give the function params and variables a new 'scope' * we change varsBase in the context. */ oldBase = tctxt->varsBase; tctxt->varsBase = tctxt->varsNr; /* If there are any parameters */ if (paramNode != NULL) { /* Fetch the stored argument values from the caller */ for (i = 0; i < nargs; i++) { savedObj = xmlMalloc(sizeof(struct objChain)); savedObj->next = savedObjChain; savedObj->obj = valuePop(ctxt); savedObjChain = savedObj; } /* * Prepare to process params in reverse order. First, go to * the beginning of the param chain. */ for (i = 1; i <= func->nargs; i++) { if (paramNode->prev == NULL) break; paramNode = paramNode->prev; } /* * i has total # params found, nargs is number which are present * as arguments from the caller * Calculate the number of un-set parameters */ notSet = func->nargs - nargs; for (; i > 0; i--) { param = xsltParseStylesheetCallerParam (tctxt, paramNode); if (i > notSet) { /* if parameter value set */ param->computed = 1; if (param->value != NULL) xmlXPathFreeObject(param->value); savedObj = savedObjChain; /* get next val from chain */ param->value = savedObj->obj; savedObjChain = savedObjChain->next; xmlFree(savedObj); } xsltLocalVariablePush(tctxt, param, -1); param->next = params; params = param; paramNode = paramNode->next; } } /* * actual processing */ fake = xmlNewDocNode(tctxt->output, NULL, (const xmlChar *)"fake", NULL); oldInsert = tctxt->insert; tctxt->insert = fake; xsltApplyOneTemplate (tctxt, xmlXPathGetContextNode(ctxt), func->content, NULL, NULL); xsltLocalVariablePop(tctxt, tctxt->varsBase, -2); tctxt->insert = oldInsert; tctxt->varsBase = oldBase; /* restore original scope */ if (params != NULL) xsltFreeStackElemList(params); if (data->error != 0) goto error; if (data->result != NULL) { ret = data->result; } else ret = xmlXPathNewCString(""); data->result = oldResult; /* * It is an error if the instantiation of the template results in * the generation of result nodes. */ if (fake->children != NULL) { #ifdef LIBXML_DEBUG_ENABLED xmlDebugDumpNode (stderr, fake, 1); #endif xsltGenericError(xsltGenericErrorContext, "{%s}%s: cannot write to result tree while " "executing a function\n", ctxt->context->functionURI, ctxt->context->function); xmlFreeNode(fake); goto error; } xmlFreeNode(fake); valuePush(ctxt, ret); error: /* * IMPORTANT: This enables previously tree fragments marked as * being results of a function, to be garbage-collected after * the calling process exits. */ xsltExtensionInstructionResultFinalize(tctxt); tctxt->funcLevel--; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119 Target: 1 Example 2: Code: void PepperPlatformVideoCapture::StopCapture() { DCHECK(thread_checker_.CalledOnValidThread()); if (stop_capture_cb_.is_null()) return; stop_capture_cb_.Run(); stop_capture_cb_.Reset(); } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} 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 nfs4_handle_exception(struct nfs_server *server, int errorcode, struct nfs4_exception *exception) { struct nfs_client *clp = server->nfs_client; struct nfs4_state *state = exception->state; struct inode *inode = exception->inode; int ret = errorcode; exception->retry = 0; switch(errorcode) { case 0: return 0; case -NFS4ERR_OPENMODE: if (inode && nfs4_have_delegation(inode, FMODE_READ)) { nfs4_inode_return_delegation(inode); exception->retry = 1; return 0; } if (state == NULL) break; nfs4_schedule_stateid_recovery(server, state); goto wait_on_recovery; case -NFS4ERR_DELEG_REVOKED: case -NFS4ERR_ADMIN_REVOKED: case -NFS4ERR_BAD_STATEID: if (state == NULL) break; nfs_remove_bad_delegation(state->inode); nfs4_schedule_stateid_recovery(server, state); goto wait_on_recovery; case -NFS4ERR_EXPIRED: if (state != NULL) nfs4_schedule_stateid_recovery(server, state); case -NFS4ERR_STALE_STATEID: case -NFS4ERR_STALE_CLIENTID: nfs4_schedule_lease_recovery(clp); goto wait_on_recovery; #if defined(CONFIG_NFS_V4_1) case -NFS4ERR_BADSESSION: case -NFS4ERR_BADSLOT: case -NFS4ERR_BAD_HIGH_SLOT: case -NFS4ERR_CONN_NOT_BOUND_TO_SESSION: case -NFS4ERR_DEADSESSION: case -NFS4ERR_SEQ_FALSE_RETRY: case -NFS4ERR_SEQ_MISORDERED: dprintk("%s ERROR: %d Reset session\n", __func__, errorcode); nfs4_schedule_session_recovery(clp->cl_session, errorcode); goto wait_on_recovery; #endif /* defined(CONFIG_NFS_V4_1) */ case -NFS4ERR_FILE_OPEN: if (exception->timeout > HZ) { /* We have retried a decent amount, time to * fail */ ret = -EBUSY; break; } case -NFS4ERR_GRACE: case -NFS4ERR_DELAY: case -EKEYEXPIRED: ret = nfs4_delay(server->client, &exception->timeout); if (ret != 0) break; case -NFS4ERR_RETRY_UNCACHED_REP: case -NFS4ERR_OLD_STATEID: exception->retry = 1; break; case -NFS4ERR_BADOWNER: /* The following works around a Linux server bug! */ case -NFS4ERR_BADNAME: if (server->caps & NFS_CAP_UIDGID_NOMAP) { server->caps &= ~NFS_CAP_UIDGID_NOMAP; exception->retry = 1; printk(KERN_WARNING "NFS: v4 server %s " "does not accept raw " "uid/gids. " "Reenabling the idmapper.\n", server->nfs_client->cl_hostname); } } /* We failed to handle the error */ return nfs4_map_errors(ret); wait_on_recovery: ret = nfs4_wait_clnt_recover(clp); if (ret == 0) exception->retry = 1; return ret; } Commit Message: NFSv4: Check for buffer length in __nfs4_get_acl_uncached Commit 1f1ea6c "NFSv4: Fix buffer overflow checking in __nfs4_get_acl_uncached" accidently dropped the checking for too small result buffer length. If someone uses getxattr on "system.nfs4_acl" on an NFSv4 mount supporting ACLs, the ACL has not been cached and the buffer suplied is too short, we still copy the complete ACL, resulting in kernel and user space memory corruption. Signed-off-by: Sven Wegener <[email protected]> Cc: [email protected] Signed-off-by: Trond Myklebust <[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 Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ image->storage_class=PseudoClass; if (image->columns == 0) image->columns=2592; if (image->rows == 0) image->rows=3508; image->depth=8; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=HuffmanDecodeImage(image); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: void llc_sk_free(struct sock *sk) { struct llc_sock *llc = llc_sk(sk); llc->state = LLC_CONN_OUT_OF_SVC; /* Stop all (possibly) running timers */ llc_conn_ac_stop_all_timers(sk, NULL); #ifdef DEBUG_LLC_CONN_ALLOC printk(KERN_INFO "%s: unackq=%d, txq=%d\n", __func__, skb_queue_len(&llc->pdu_unack_q), skb_queue_len(&sk->sk_write_queue)); #endif skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); skb_queue_purge(&llc->pdu_unack_q); #ifdef LLC_REFCNT_DEBUG if (atomic_read(&sk->sk_refcnt) != 1) { printk(KERN_DEBUG "Destruction of LLC sock %p delayed in %s, cnt=%d\n", sk, __func__, atomic_read(&sk->sk_refcnt)); printk(KERN_DEBUG "%d LLC sockets are still alive\n", atomic_read(&llc_sock_nr)); } else { atomic_dec(&llc_sock_nr); printk(KERN_DEBUG "LLC socket %p released in %s, %d are still alive\n", sk, __func__, atomic_read(&llc_sock_nr)); } #endif sock_put(sk); } Commit Message: net/llc: avoid BUG_ON() in skb_orphan() It seems nobody used LLC since linux-3.12. Fortunately fuzzers like syzkaller still know how to run this code, otherwise it would be no fun. Setting skb->sk without skb->destructor leads to all kinds of bugs, we now prefer to be very strict about it. Ideally here we would use skb_set_owner() but this helper does not exist yet, only CAN seems to have a private helper for that. Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()") Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Andrey Konovalov <[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: BluetoothAdapterChromeOS::~BluetoothAdapterChromeOS() { DBusThreadManager::Get()->GetBluetoothAdapterClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothDeviceClient()->RemoveObserver(this); DBusThreadManager::Get()->GetBluetoothInputClient()->RemoveObserver(this); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int snd_ctl_elem_add(struct snd_ctl_file *file, struct snd_ctl_elem_info *info, int replace) { struct snd_card *card = file->card; struct snd_kcontrol kctl, *_kctl; unsigned int access; long private_size; struct user_element *ue; int idx, err; if (!replace && card->user_ctl_count >= MAX_USER_CONTROLS) return -ENOMEM; if (info->count < 1) return -EINVAL; access = info->access == 0 ? SNDRV_CTL_ELEM_ACCESS_READWRITE : (info->access & (SNDRV_CTL_ELEM_ACCESS_READWRITE| SNDRV_CTL_ELEM_ACCESS_INACTIVE| SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE)); info->id.numid = 0; memset(&kctl, 0, sizeof(kctl)); down_write(&card->controls_rwsem); _kctl = snd_ctl_find_id(card, &info->id); err = 0; if (_kctl) { if (replace) err = snd_ctl_remove(card, _kctl); else err = -EBUSY; } else { if (replace) err = -ENOENT; } up_write(&card->controls_rwsem); if (err < 0) return err; memcpy(&kctl.id, &info->id, sizeof(info->id)); kctl.count = info->owner ? info->owner : 1; access |= SNDRV_CTL_ELEM_ACCESS_USER; if (info->type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) kctl.info = snd_ctl_elem_user_enum_info; else kctl.info = snd_ctl_elem_user_info; if (access & SNDRV_CTL_ELEM_ACCESS_READ) kctl.get = snd_ctl_elem_user_get; if (access & SNDRV_CTL_ELEM_ACCESS_WRITE) kctl.put = snd_ctl_elem_user_put; if (access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE) { kctl.tlv.c = snd_ctl_elem_user_tlv; access |= SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK; } switch (info->type) { case SNDRV_CTL_ELEM_TYPE_BOOLEAN: case SNDRV_CTL_ELEM_TYPE_INTEGER: private_size = sizeof(long); if (info->count > 128) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_INTEGER64: private_size = sizeof(long long); if (info->count > 64) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_ENUMERATED: private_size = sizeof(unsigned int); if (info->count > 128 || info->value.enumerated.items == 0) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_BYTES: private_size = sizeof(unsigned char); if (info->count > 512) return -EINVAL; break; case SNDRV_CTL_ELEM_TYPE_IEC958: private_size = sizeof(struct snd_aes_iec958); if (info->count != 1) return -EINVAL; break; default: return -EINVAL; } private_size *= info->count; ue = kzalloc(sizeof(struct user_element) + private_size, GFP_KERNEL); if (ue == NULL) return -ENOMEM; ue->info = *info; ue->info.access = 0; ue->elem_data = (char *)ue + sizeof(*ue); ue->elem_data_size = private_size; if (ue->info.type == SNDRV_CTL_ELEM_TYPE_ENUMERATED) { err = snd_ctl_elem_init_enum_names(ue); if (err < 0) { kfree(ue); return err; } } kctl.private_free = snd_ctl_elem_user_free; _kctl = snd_ctl_new(&kctl, access); if (_kctl == NULL) { kfree(ue->priv_data); kfree(ue); return -ENOMEM; } _kctl->private_data = ue; for (idx = 0; idx < _kctl->count; idx++) _kctl->vd[idx].owner = file; err = snd_ctl_add(card, _kctl); if (err < 0) return err; down_write(&card->controls_rwsem); card->user_ctl_count++; up_write(&card->controls_rwsem); return 0; } Commit Message: ALSA: control: Protect user controls against concurrent access The user-control put and get handlers as well as the tlv do not protect against concurrent access from multiple threads. Since the state of the control is not updated atomically it is possible that either two write operations or a write and a read operation race against each other. Both can lead to arbitrary memory disclosure. This patch introduces a new lock that protects user-controls from concurrent access. Since applications typically access controls sequentially than in parallel a single lock per card should be fine. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: fix_glyph_scaling(ASS_Renderer *priv, GlyphInfo *glyph) { double ft_size; if (priv->settings.hinting == ASS_HINTING_NONE) { ft_size = 256.0; } else { ft_size = glyph->scale_y * glyph->font_size; } glyph->scale_x = glyph->scale_x * glyph->font_size / ft_size; glyph->scale_y = glyph->scale_y * glyph->font_size / ft_size; glyph->font_size = ft_size; } Commit Message: Fix line wrapping mode 0/3 bugs This fixes two separate bugs: a) Don't move a linebreak into the first symbol. This results in a empty line at the front, which does not help to equalize line lengths at all. b) When moving a linebreak into a symbol that already is a break, the number of lines must be decremented. Otherwise, uninitialized memory is possibly used for later layout operations. Found by fuzzer test case id:000085,sig:11,src:003377+003350,op:splice,rep:8. 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 WebPreferences::Apply(WebView* web_view) const { WebSettings* settings = web_view->settings(); ApplyFontsFromMap(standard_font_family_map, setStandardFontFamilyWrapper, settings); ApplyFontsFromMap(fixed_font_family_map, setFixedFontFamilyWrapper, settings); ApplyFontsFromMap(serif_font_family_map, setSerifFontFamilyWrapper, settings); ApplyFontsFromMap(sans_serif_font_family_map, setSansSerifFontFamilyWrapper, settings); ApplyFontsFromMap(cursive_font_family_map, setCursiveFontFamilyWrapper, settings); ApplyFontsFromMap(fantasy_font_family_map, setFantasyFontFamilyWrapper, settings); ApplyFontsFromMap(pictograph_font_family_map, setPictographFontFamilyWrapper, settings); settings->setDefaultFontSize(default_font_size); settings->setDefaultFixedFontSize(default_fixed_font_size); settings->setMinimumFontSize(minimum_font_size); settings->setMinimumLogicalFontSize(minimum_logical_font_size); settings->setDefaultTextEncodingName(ASCIIToUTF16(default_encoding)); settings->setApplyDefaultDeviceScaleFactorInCompositor( apply_default_device_scale_factor_in_compositor); settings->setApplyPageScaleFactorInCompositor( apply_page_scale_factor_in_compositor); settings->setPerTilePaintingEnabled(per_tile_painting_enabled); settings->setAcceleratedAnimationEnabled(accelerated_animation_enabled); settings->setJavaScriptEnabled(javascript_enabled); settings->setWebSecurityEnabled(web_security_enabled); settings->setJavaScriptCanOpenWindowsAutomatically( javascript_can_open_windows_automatically); settings->setLoadsImagesAutomatically(loads_images_automatically); settings->setImagesEnabled(images_enabled); settings->setPluginsEnabled(plugins_enabled); settings->setDOMPasteAllowed(dom_paste_enabled); settings->setDeveloperExtrasEnabled(developer_extras_enabled); settings->setNeedsSiteSpecificQuirks(site_specific_quirks_enabled); settings->setShrinksStandaloneImagesToFit(shrinks_standalone_images_to_fit); settings->setUsesEncodingDetector(uses_universal_detector); settings->setTextAreasAreResizable(text_areas_are_resizable); settings->setAllowScriptsToCloseWindows(allow_scripts_to_close_windows); if (user_style_sheet_enabled) settings->setUserStyleSheetLocation(user_style_sheet_location); else settings->setUserStyleSheetLocation(WebURL()); settings->setAuthorAndUserStylesEnabled(author_and_user_styles_enabled); settings->setUsesPageCache(uses_page_cache); settings->setPageCacheSupportsPlugins(page_cache_supports_plugins); settings->setDownloadableBinaryFontsEnabled(remote_fonts_enabled); settings->setJavaScriptCanAccessClipboard(javascript_can_access_clipboard); settings->setXSSAuditorEnabled(xss_auditor_enabled); settings->setDNSPrefetchingEnabled(dns_prefetching_enabled); settings->setLocalStorageEnabled(local_storage_enabled); settings->setSyncXHRInDocumentsEnabled(sync_xhr_in_documents_enabled); WebRuntimeFeatures::enableDatabase(databases_enabled); settings->setOfflineWebApplicationCacheEnabled(application_cache_enabled); settings->setCaretBrowsingEnabled(caret_browsing_enabled); settings->setHyperlinkAuditingEnabled(hyperlink_auditing_enabled); settings->setCookieEnabled(cookie_enabled); settings->setEditableLinkBehaviorNeverLive(); settings->setFrameFlatteningEnabled(frame_flattening_enabled); settings->setFontRenderingModeNormal(); settings->setJavaEnabled(java_enabled); settings->setAllowUniversalAccessFromFileURLs( allow_universal_access_from_file_urls); settings->setAllowFileAccessFromFileURLs(allow_file_access_from_file_urls); settings->setTextDirectionSubmenuInclusionBehaviorNeverIncluded(); settings->setWebAudioEnabled(webaudio_enabled); settings->setExperimentalWebGLEnabled(experimental_webgl_enabled); settings->setOpenGLMultisamplingEnabled(gl_multisampling_enabled); settings->setPrivilegedWebGLExtensionsEnabled( privileged_webgl_extensions_enabled); settings->setWebGLErrorsToConsoleEnabled(webgl_errors_to_console_enabled); settings->setShowDebugBorders(show_composited_layer_borders); settings->setShowFPSCounter(show_fps_counter); settings->setAcceleratedCompositingForOverflowScrollEnabled( accelerated_compositing_for_overflow_scroll_enabled); settings->setAcceleratedCompositingForScrollableFramesEnabled( accelerated_compositing_for_scrollable_frames_enabled); settings->setCompositedScrollingForFramesEnabled( composited_scrolling_for_frames_enabled); settings->setShowPlatformLayerTree(show_composited_layer_tree); settings->setShowPaintRects(show_paint_rects); settings->setRenderVSyncEnabled(render_vsync_enabled); settings->setAcceleratedCompositingEnabled(accelerated_compositing_enabled); settings->setAcceleratedCompositingForFixedPositionEnabled( fixed_position_compositing_enabled); settings->setAccelerated2dCanvasEnabled(accelerated_2d_canvas_enabled); settings->setDeferred2dCanvasEnabled(deferred_2d_canvas_enabled); settings->setAntialiased2dCanvasEnabled(!antialiased_2d_canvas_disabled); settings->setAcceleratedPaintingEnabled(accelerated_painting_enabled); settings->setAcceleratedFiltersEnabled(accelerated_filters_enabled); settings->setGestureTapHighlightEnabled(gesture_tap_highlight_enabled); settings->setAcceleratedCompositingFor3DTransformsEnabled( accelerated_compositing_for_3d_transforms_enabled); settings->setAcceleratedCompositingForVideoEnabled( accelerated_compositing_for_video_enabled); settings->setAcceleratedCompositingForAnimationEnabled( accelerated_compositing_for_animation_enabled); settings->setAcceleratedCompositingForPluginsEnabled( accelerated_compositing_for_plugins_enabled); settings->setAcceleratedCompositingForCanvasEnabled( experimental_webgl_enabled || accelerated_2d_canvas_enabled); settings->setMemoryInfoEnabled(memory_info_enabled); settings->setAsynchronousSpellCheckingEnabled( asynchronous_spell_checking_enabled); settings->setUnifiedTextCheckerEnabled(unified_textchecker_enabled); for (WebInspectorPreferences::const_iterator it = inspector_settings.begin(); it != inspector_settings.end(); ++it) web_view->setInspectorSetting(WebString::fromUTF8(it->first), WebString::fromUTF8(it->second)); web_view->setTabsToLinks(tabs_to_links); settings->setInteractiveFormValidationEnabled(true); settings->setFullScreenEnabled(fullscreen_enabled); settings->setAllowDisplayOfInsecureContent(allow_displaying_insecure_content); settings->setAllowRunningOfInsecureContent(allow_running_insecure_content); settings->setPasswordEchoEnabled(password_echo_enabled); settings->setShouldPrintBackgrounds(should_print_backgrounds); settings->setEnableScrollAnimator(enable_scroll_animator); settings->setVisualWordMovementEnabled(visual_word_movement_enabled); settings->setCSSStickyPositionEnabled(css_sticky_position_enabled); settings->setExperimentalCSSCustomFilterEnabled(css_shaders_enabled); settings->setExperimentalCSSVariablesEnabled(css_variables_enabled); settings->setExperimentalCSSGridLayoutEnabled(css_grid_layout_enabled); WebRuntimeFeatures::enableTouch(touch_enabled); settings->setDeviceSupportsTouch(device_supports_touch); settings->setDeviceSupportsMouse(device_supports_mouse); settings->setEnableTouchAdjustment(touch_adjustment_enabled); settings->setDefaultTileSize( WebSize(default_tile_width, default_tile_height)); settings->setMaxUntiledLayerSize( WebSize(max_untiled_layer_width, max_untiled_layer_height)); settings->setFixedPositionCreatesStackingContext( fixed_position_creates_stacking_context); settings->setDeferredImageDecodingEnabled(deferred_image_decoding_enabled); settings->setShouldRespectImageOrientation(should_respect_image_orientation); settings->setEditingBehavior( static_cast<WebSettings::EditingBehavior>(editing_behavior)); settings->setSupportsMultipleWindows(supports_multiple_windows); settings->setViewportEnabled(viewport_enabled); #if defined(OS_ANDROID) settings->setAllowCustomScrollbarInMainFrame(false); settings->setTextAutosizingEnabled(text_autosizing_enabled); settings->setTextAutosizingFontScaleFactor(font_scale_factor); web_view->setIgnoreViewportTagMaximumScale(force_enable_zoom); settings->setAutoZoomFocusedNodeToLegibleScale(true); settings->setDoubleTapToZoomEnabled(true); settings->setMediaPlaybackRequiresUserGesture( user_gesture_required_for_media_playback); #endif WebNetworkStateNotifier::setOnLine(is_online); } Commit Message: Copy-paste preserves <embed> tags containing active content. BUG=112325 Enable webkit preference for Chromium to disallow unsafe plugin pasting. Review URL: https://chromiumcodereview.appspot.com/11884025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176856 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: void SecureProxyChecker::CheckIfSecureProxyIsAllowed( SecureProxyCheckerCallback fetcher_callback) { net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation( "data_reduction_proxy_secure_proxy_check", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server. Proceeds " "with using a secure connection to the proxy only if the " "response is not blocked or modified by an intermediary." trigger: "A request can be sent whenever the browser is determining how " "to configure its connection to the data reduction proxy. This " "happens on startup and network changes." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop " "it is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = params::GetSecureProxyCheckURL(); resource_request->load_flags = net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY; resource_request->allow_credentials = false; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE | network::SimpleURLLoader::RETRY_ON_5XX); url_loader_->SetOnRedirectCallback(base::BindRepeating( &SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this))); fetcher_callback_ = fetcher_callback; secure_proxy_check_start_time_ = base::Time::Now(); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&SecureProxyChecker::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416 Target: 1 Example 2: Code: static int __init crc32c_intel_mod_init(void) { if (!x86_match_cpu(crc32c_cpu_id)) return -ENODEV; #ifdef CONFIG_X86_64 if (cpu_has_pclmulqdq) { alg.update = crc32c_pcl_intel_update; alg.finup = crc32c_pcl_intel_finup; alg.digest = crc32c_pcl_intel_digest; set_pcl_breakeven_point(); } #endif return crypto_register_shash(&alg); } 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: void RenderWidgetHostViewAura::RunCompositingDidCommitCallbacks( ui::Compositor* compositor) { for (std::vector< base::Callback<void(ui::Compositor*)> >::const_iterator it = on_compositing_did_commit_callbacks_.begin(); it != on_compositing_did_commit_callbacks_.end(); ++it) { it->Run(compositor); } on_compositing_did_commit_callbacks_.clear(); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void Verify_StoreExistingGroup() { EXPECT_TRUE(delegate()->stored_group_success_); EXPECT_EQ(group_.get(), delegate()->stored_group_.get()); EXPECT_EQ(cache2_.get(), group_->newest_complete_cache()); EXPECT_TRUE(cache2_->is_complete()); AppCacheDatabase::GroupRecord group_record; AppCacheDatabase::CacheRecord cache_record; EXPECT_TRUE(database()->FindGroup(1, &group_record)); EXPECT_TRUE(database()->FindCache(2, &cache_record)); EXPECT_FALSE(database()->FindCache(1, &cache_record)); EXPECT_EQ(kDefaultEntrySize + 100, storage()->usage_map_[kOrigin]); EXPECT_EQ(1, mock_quota_manager_proxy_->notify_storage_modified_count_); EXPECT_EQ(kOrigin, mock_quota_manager_proxy_->last_origin_); EXPECT_EQ(100, 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: static int __init dccp_v6_init(void) { int err = proto_register(&dccp_v6_prot, 1); if (err != 0) goto out; err = inet6_add_protocol(&dccp_v6_protocol, IPPROTO_DCCP); if (err != 0) goto out_unregister_proto; inet6_register_protosw(&dccp_v6_protosw); err = register_pernet_subsys(&dccp_v6_ops); if (err != 0) goto out_destroy_ctl_sock; out: return err; out_destroy_ctl_sock: inet6_del_protocol(&dccp_v6_protocol, IPPROTO_DCCP); inet6_unregister_protosw(&dccp_v6_protosw); out_unregister_proto: proto_unregister(&dccp_v6_prot); goto out; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 dprintf_formatf( void *data, /* untouched by format(), just sent to the stream() function in the second argument */ /* function pointer called for each output character */ int (*stream)(int, FILE *), const char *format, /* %-formatted string */ va_list ap_save) /* list of parameters */ { /* Base-36 digits for numbers. */ const char *digits = lower_digits; /* Pointer into the format string. */ char *f; /* Number of characters written. */ int done = 0; long param; /* current parameter to read */ long param_num=0; /* parameter counter */ va_stack_t vto[MAX_PARAMETERS]; char *endpos[MAX_PARAMETERS]; char **end; char work[BUFFSIZE]; va_stack_t *p; /* 'workend' points to the final buffer byte position, but with an extra byte as margin to avoid the (false?) warning Coverity gives us otherwise */ char *workend = &work[sizeof(work) - 2]; /* Do the actual %-code parsing */ if(dprintf_Pass1(format, vto, endpos, ap_save)) return -1; end = &endpos[0]; /* the initial end-position from the list dprintf_Pass1() created for us */ f = (char *)format; while(*f != '\0') { /* Format spec modifiers. */ int is_alt; /* Width of a field. */ long width; /* Precision of a field. */ long prec; /* Decimal integer is negative. */ int is_neg; /* Base of a number to be written. */ long base; /* Integral values to be written. */ mp_uintmax_t num; /* Used to convert negative in positive. */ mp_intmax_t signed_num; char *w; if(*f != '%') { /* This isn't a format spec, so write everything out until the next one OR end of string is reached. */ do { OUTCHAR(*f); } while(*++f && ('%' != *f)); continue; } ++f; /* Check for "%%". Note that although the ANSI standard lists '%' as a conversion specifier, it says "The complete format specification shall be `%%'," so we can avoid all the width and precision processing. */ if(*f == '%') { ++f; OUTCHAR('%'); continue; } /* If this is a positional parameter, the position must follow immediately after the %, thus create a %<num>$ sequence */ param=dprintf_DollarString(f, &f); if(!param) param = param_num; else --param; param_num++; /* increase this always to allow "%2$s %1$s %s" and then the third %s will pick the 3rd argument */ p = &vto[param]; /* pick up the specified width */ if(p->flags & FLAGS_WIDTHPARAM) { width = (long)vto[p->width].data.num.as_signed; param_num++; /* since the width is extracted from a parameter, we must skip that to get to the next one properly */ if(width < 0) { /* "A negative field width is taken as a '-' flag followed by a positive field width." */ width = -width; p->flags |= FLAGS_LEFT; p->flags &= ~FLAGS_PAD_NIL; } } else width = p->width; /* pick up the specified precision */ if(p->flags & FLAGS_PRECPARAM) { prec = (long)vto[p->precision].data.num.as_signed; param_num++; /* since the precision is extracted from a parameter, we must skip that to get to the next one properly */ if(prec < 0) /* "A negative precision is taken as if the precision were omitted." */ prec = -1; } else if(p->flags & FLAGS_PREC) prec = p->precision; else prec = -1; is_alt = (p->flags & FLAGS_ALT) ? 1 : 0; switch(p->type) { case FORMAT_INT: num = p->data.num.as_unsigned; if(p->flags & FLAGS_CHAR) { /* Character. */ if(!(p->flags & FLAGS_LEFT)) while(--width > 0) OUTCHAR(' '); OUTCHAR((char) num); if(p->flags & FLAGS_LEFT) while(--width > 0) OUTCHAR(' '); break; } if(p->flags & FLAGS_OCTAL) { /* Octal unsigned integer. */ base = 8; goto unsigned_number; } else if(p->flags & FLAGS_HEX) { /* Hexadecimal unsigned integer. */ digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits; base = 16; goto unsigned_number; } else if(p->flags & FLAGS_UNSIGNED) { /* Decimal unsigned integer. */ base = 10; goto unsigned_number; } /* Decimal integer. */ base = 10; is_neg = (p->data.num.as_signed < (mp_intmax_t)0) ? 1 : 0; if(is_neg) { /* signed_num might fail to hold absolute negative minimum by 1 */ signed_num = p->data.num.as_signed + (mp_intmax_t)1; signed_num = -signed_num; num = (mp_uintmax_t)signed_num; num += (mp_uintmax_t)1; } goto number; unsigned_number: /* Unsigned number of base BASE. */ is_neg = 0; number: /* Number of base BASE. */ /* Supply a default precision if none was given. */ if(prec == -1) prec = 1; /* Put the number in WORK. */ w = workend; while(num > 0) { *w-- = digits[num % base]; num /= base; } width -= (long)(workend - w); prec -= (long)(workend - w); if(is_alt && base == 8 && prec <= 0) { *w-- = '0'; --width; } if(prec > 0) { width -= prec; while(prec-- > 0) *w-- = '0'; } if(is_alt && base == 16) width -= 2; if(is_neg || (p->flags & FLAGS_SHOWSIGN) || (p->flags & FLAGS_SPACE)) --width; if(!(p->flags & FLAGS_LEFT) && !(p->flags & FLAGS_PAD_NIL)) while(width-- > 0) OUTCHAR(' '); if(is_neg) OUTCHAR('-'); else if(p->flags & FLAGS_SHOWSIGN) OUTCHAR('+'); else if(p->flags & FLAGS_SPACE) OUTCHAR(' '); if(is_alt && base == 16) { OUTCHAR('0'); if(p->flags & FLAGS_UPPER) OUTCHAR('X'); else OUTCHAR('x'); } if(!(p->flags & FLAGS_LEFT) && (p->flags & FLAGS_PAD_NIL)) while(width-- > 0) OUTCHAR('0'); /* Write the number. */ while(++w <= workend) { OUTCHAR(*w); } if(p->flags & FLAGS_LEFT) while(width-- > 0) OUTCHAR(' '); break; case FORMAT_STRING: /* String. */ { static const char null[] = "(nil)"; const char *str; size_t len; str = (char *) p->data.str; if(str == NULL) { /* Write null[] if there's space. */ if(prec == -1 || prec >= (long) sizeof(null) - 1) { str = null; len = sizeof(null) - 1; /* Disable quotes around (nil) */ p->flags &= (~FLAGS_ALT); } else { str = ""; len = 0; } } else if(prec != -1) len = (size_t)prec; else len = strlen(str); width -= (len > LONG_MAX) ? LONG_MAX : (long)len; if(p->flags & FLAGS_ALT) OUTCHAR('"'); if(!(p->flags&FLAGS_LEFT)) while(width-- > 0) OUTCHAR(' '); while((len-- > 0) && *str) OUTCHAR(*str++); if(p->flags&FLAGS_LEFT) while(width-- > 0) OUTCHAR(' '); if(p->flags & FLAGS_ALT) OUTCHAR('"'); } break; case FORMAT_PTR: /* Generic pointer. */ { void *ptr; ptr = (void *) p->data.ptr; if(ptr != NULL) { /* If the pointer is not NULL, write it as a %#x spec. */ base = 16; digits = (p->flags & FLAGS_UPPER)? upper_digits : lower_digits; is_alt = 1; num = (size_t) ptr; is_neg = 0; goto number; } else { /* Write "(nil)" for a nil pointer. */ static const char strnil[] = "(nil)"; const char *point; width -= (long)(sizeof(strnil) - 1); if(p->flags & FLAGS_LEFT) while(width-- > 0) OUTCHAR(' '); for(point = strnil; *point != '\0'; ++point) OUTCHAR(*point); if(! (p->flags & FLAGS_LEFT)) while(width-- > 0) OUTCHAR(' '); } } break; case FORMAT_DOUBLE: { char formatbuf[32]="%"; char *fptr = &formatbuf[1]; size_t left = sizeof(formatbuf)-strlen(formatbuf); int len; width = -1; if(p->flags & FLAGS_WIDTH) width = p->width; else if(p->flags & FLAGS_WIDTHPARAM) width = (long)vto[p->width].data.num.as_signed; prec = -1; if(p->flags & FLAGS_PREC) prec = p->precision; else if(p->flags & FLAGS_PRECPARAM) prec = (long)vto[p->precision].data.num.as_signed; if(p->flags & FLAGS_LEFT) *fptr++ = '-'; if(p->flags & FLAGS_SHOWSIGN) *fptr++ = '+'; if(p->flags & FLAGS_SPACE) *fptr++ = ' '; if(p->flags & FLAGS_ALT) *fptr++ = '#'; *fptr = 0; if(width >= 0) { /* RECURSIVE USAGE */ len = curl_msnprintf(fptr, left, "%ld", width); fptr += len; left -= len; } if(prec >= 0) { /* RECURSIVE USAGE */ len = curl_msnprintf(fptr, left, ".%ld", prec); fptr += len; } if(p->flags & FLAGS_LONG) *fptr++ = 'l'; if(p->flags & FLAGS_FLOATE) *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'E':'e'); else if(p->flags & FLAGS_FLOATG) *fptr++ = (char)((p->flags & FLAGS_UPPER) ? 'G' : 'g'); else *fptr++ = 'f'; *fptr = 0; /* and a final zero termination */ /* NOTE NOTE NOTE!! Not all sprintf implementations return number of output characters */ (sprintf)(work, formatbuf, p->data.dnum); for(fptr=work; *fptr; fptr++) OUTCHAR(*fptr); } break; case FORMAT_INTPTR: /* Answer the count of characters written. */ #ifdef HAVE_LONG_LONG_TYPE if(p->flags & FLAGS_LONGLONG) *(LONG_LONG_TYPE *) p->data.ptr = (LONG_LONG_TYPE)done; else #endif if(p->flags & FLAGS_LONG) *(long *) p->data.ptr = (long)done; else if(!(p->flags & FLAGS_SHORT)) *(int *) p->data.ptr = (int)done; else *(short *) p->data.ptr = (short)done; break; default: break; } f = *end++; /* goto end of %-code */ } return done; } Commit Message: printf: fix floating point buffer overflow issues ... and add a bunch of floating point printf tests 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 inline bool unconditional(const struct ipt_ip *ip) { static const struct ipt_ip uncond; return memcmp(ip, &uncond, sizeof(uncond)) == 0; #undef FWINV } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int ecryptfs_dir_release(struct inode *inode, struct file *file) { fput(ecryptfs_file_to_lower(file)); kmem_cache_free(ecryptfs_file_info_cache, ecryptfs_file_to_private(file)); return 0; } Commit Message: ecryptfs: don't allow mmap when the lower fs doesn't support it There are legitimate reasons to disallow mmap on certain files, notably in sysfs or procfs. We shouldn't emulate mmap support on file systems that don't offer support natively. CVE-2016-1583 Signed-off-by: Jeff Mahoney <[email protected]> Cc: [email protected] [tyhicks: clean up f_op check by using ecryptfs_file_to_lower()] Signed-off-by: Tyler Hicks <[email protected]> CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __ip6_datagram_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *daddr, *final_p, final; struct dst_entry *dst; struct flowi6 fl6; struct ip6_flowlabel *flowlabel = NULL; struct ipv6_txoptions *opt; int addr_type; int err; if (usin->sin6_family == AF_INET) { if (__ipv6_only_sock(sk)) return -EAFNOSUPPORT; err = __ip4_datagram_connect(sk, uaddr, addr_len); goto ipv4_connected; } if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (usin->sin6_family != AF_INET6) return -EAFNOSUPPORT; memset(&fl6, 0, sizeof(fl6)); if (np->sndflow) { fl6.flowlabel = usin->sin6_flowinfo&IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (!flowlabel) return -EINVAL; } } addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type == IPV6_ADDR_ANY) { /* * connect to self */ usin->sin6_addr.s6_addr[15] = 0x01; } daddr = &usin->sin6_addr; if (addr_type == IPV6_ADDR_MAPPED) { struct sockaddr_in sin; if (__ipv6_only_sock(sk)) { err = -ENETUNREACH; goto out; } sin.sin_family = AF_INET; sin.sin_addr.s_addr = daddr->s6_addr32[3]; sin.sin_port = usin->sin6_port; err = __ip4_datagram_connect(sk, (struct sockaddr *) &sin, sizeof(sin)); ipv4_connected: if (err) goto out; ipv6_addr_set_v4mapped(inet->inet_daddr, &sk->sk_v6_daddr); if (ipv6_addr_any(&np->saddr) || ipv6_mapped_addr_any(&np->saddr)) ipv6_addr_set_v4mapped(inet->inet_saddr, &np->saddr); if (ipv6_addr_any(&sk->sk_v6_rcv_saddr) || ipv6_mapped_addr_any(&sk->sk_v6_rcv_saddr)) { ipv6_addr_set_v4mapped(inet->inet_rcv_saddr, &sk->sk_v6_rcv_saddr); if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } goto out; } if (__ipv6_addr_needs_scope_id(addr_type)) { if (addr_len >= sizeof(struct sockaddr_in6) && usin->sin6_scope_id) { if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != usin->sin6_scope_id) { err = -EINVAL; goto out; } sk->sk_bound_dev_if = usin->sin6_scope_id; } if (!sk->sk_bound_dev_if && (addr_type & IPV6_ADDR_MULTICAST)) sk->sk_bound_dev_if = np->mcast_oif; /* Connect to link-local address requires an interface */ if (!sk->sk_bound_dev_if) { err = -EINVAL; goto out; } } sk->sk_v6_daddr = *daddr; np->flow_label = fl6.flowlabel; inet->inet_dport = usin->sin6_port; /* * Check for a route to destination an obtain the * destination cache for it. */ fl6.flowi6_proto = sk->sk_protocol; fl6.daddr = sk->sk_v6_daddr; fl6.saddr = np->saddr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = sk->sk_mark; fl6.fl6_dport = inet->inet_dport; fl6.fl6_sport = inet->inet_sport; if (!fl6.flowi6_oif && (addr_type&IPV6_ADDR_MULTICAST)) fl6.flowi6_oif = np->mcast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); opt = flowlabel ? flowlabel->opt : np->opt; final_p = fl6_update_dst(&fl6, opt, &final); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); err = 0; if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } /* source address lookup done in ip6_dst_lookup */ if (ipv6_addr_any(&np->saddr)) np->saddr = fl6.saddr; if (ipv6_addr_any(&sk->sk_v6_rcv_saddr)) { sk->sk_v6_rcv_saddr = fl6.saddr; inet->inet_rcv_saddr = LOOPBACK4_IPV6; if (sk->sk_prot->rehash) sk->sk_prot->rehash(sk); } ip6_dst_store(sk, dst, ipv6_addr_equal(&fl6.daddr, &sk->sk_v6_daddr) ? &sk->sk_v6_daddr : NULL, #ifdef CONFIG_IPV6_SUBTREES ipv6_addr_equal(&fl6.saddr, &np->saddr) ? &np->saddr : #endif NULL); sk->sk_state = TCP_ESTABLISHED; sk_set_txhash(sk); out: fl6_sock_release(flowlabel); return err; } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int gather_pte_stats(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct numa_maps *md; spinlock_t *ptl; pte_t *orig_pte; pte_t *pte; md = walk->private; spin_lock(&walk->mm->page_table_lock); if (pmd_trans_huge(*pmd)) { if (pmd_trans_splitting(*pmd)) { spin_unlock(&walk->mm->page_table_lock); wait_split_huge_page(md->vma->anon_vma, pmd); } else { pte_t huge_pte = *(pte_t *)pmd; struct page *page; page = can_gather_numa_stats(huge_pte, md->vma, addr); if (page) gather_stats(page, md, pte_dirty(huge_pte), HPAGE_PMD_SIZE/PAGE_SIZE); spin_unlock(&walk->mm->page_table_lock); return 0; } } else { spin_unlock(&walk->mm->page_table_lock); } orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); do { struct page *page = can_gather_numa_stats(*pte, md->vma, addr); if (!page) continue; gather_stats(page, md, pte_dirty(*pte), 1); } while (pte++, addr += PAGE_SIZE, addr != end); pte_unmap_unlock(orig_pte, ptl); return 0; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&current->mm->mmap_sem) ... madvise_vma switch (behavior) case MADV_DONTNEED: madvise_dontneed zap_page_range unmap_vmas unmap_page_range zap_pud_range zap_pmd_range // // Assume that this huge page has never been accessed. // I.e. content of the PMD entry is zero (not mapped). // if (pmd_trans_huge(*pmd)) { // We don't get here due to the above assumption. } // // Assume that Thread B incurred a page fault and .---------> // sneaks in here as shown below. | // | if (pmd_none_or_clear_bad(pmd)) | { | if (unlikely(pmd_bad(*pmd))) | pmd_clear_bad | { | pmd_ERROR | // Log "bad pmd ..." message here. | pmd_clear | // Clear the page's PMD entry. | // Thread B incremented the map count | // in page_add_new_anon_rmap(), but | // now the page is no longer mapped | // by a PMD entry (-> inconsistency). | } | } | v - Thread B is handling a page fault on virtual address "B(fault)" shown in the picture. ... do_page_fault __do_page_fault // Acquire the semaphore in shared mode. down_read_trylock(&mm->mmap_sem) ... handle_mm_fault if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) // We get here due to the above assumption (PMD entry is zero). do_huge_pmd_anonymous_page alloc_hugepage_vma // Allocate a new transparent huge page here. ... __do_huge_pmd_anonymous_page ... spin_lock(&mm->page_table_lock) ... page_add_new_anon_rmap // Here we increment the page's map count (starts at -1). atomic_set(&page->_mapcount, 0) set_pmd_at // Here we set the page's PMD entry which will be cleared // when Thread A calls pmd_clear_bad(). ... spin_unlock(&mm->page_table_lock) The mmap_sem does not prevent the race because both threads are acquiring it in shared mode (down_read). Thread B holds the page_table_lock while the page's map count and PMD table entry are updated. However, Thread A does not synchronize on that lock. ====== end quote ======= [[email protected]: checkpatch fixes] Reported-by: Ulrich Obergfell <[email protected]> Signed-off-by: Andrea Arcangeli <[email protected]> Acked-by: Johannes Weiner <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Dave Jones <[email protected]> Acked-by: Larry Woodman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: Mark Salter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static int sha1_neon_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct sha1_state *sctx = shash_desc_ctx(desc); unsigned int partial = sctx->count % SHA1_BLOCK_SIZE; int res; /* Handle the fast case right here */ if (partial + len < SHA1_BLOCK_SIZE) { sctx->count += len; memcpy(sctx->buffer + partial, data, len); return 0; } if (!may_use_simd()) { res = sha1_update_arm(desc, data, len); } else { kernel_neon_begin(); res = __sha1_neon_update(desc, data, len, partial); kernel_neon_end(); } return res; } 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: void HTMLFormControlElement::setFormEnctype(const AtomicString& value) { setAttribute(formenctypeAttr, value); } Commit Message: Add HTMLFormControlElement::supportsAutofocus to fix a FIXME comment. This virtual function should return true if the form control can hanlde 'autofocucs' attribute if it is specified. Note: HTMLInputElement::supportsAutofocus reuses InputType::isInteractiveContent because interactiveness is required for autofocus capability. BUG=none TEST=none; no behavior changes. Review URL: https://codereview.chromium.org/143343003 git-svn-id: svn://svn.chromium.org/blink/trunk@165432 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119 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: _client_protocol_timeout (GsmXSMPClient *client) { g_debug ("GsmXSMPClient: client_protocol_timeout for client '%s' in ICE status %d", client->priv->description, IceConnectionStatus (client->priv->ice_connection)); gsm_client_set_status (GSM_CLIENT (client), GSM_CLIENT_FAILED); gsm_client_disconnected (GSM_CLIENT (client)); return FALSE; } Commit Message: [gsm] Delay the creation of the GsmXSMPClient until it really exists We used to create the GsmXSMPClient before the XSMP connection is really accepted. This can lead to some issues, though. An example is: https://bugzilla.gnome.org/show_bug.cgi?id=598211#c19. Quoting: "What is happening is that a new client (probably metacity in your case) is opening an ICE connection in the GSM_MANAGER_PHASE_END_SESSION phase, which causes a new GsmXSMPClient to be added to the client store. The GSM_MANAGER_PHASE_EXIT phase then begins before the client has had a chance to establish a xsmp connection, which means that client->priv->conn will not be initialized at the point that xsmp_stop is called on the new unregistered client." The fix is to create the GsmXSMPClient object when there's a real XSMP connection. This implies moving the timeout that makes sure we don't have an empty client to the XSMP server. https://bugzilla.gnome.org/show_bug.cgi?id=598211 CWE ID: CWE-835 Target: 1 Example 2: Code: void WebContentsAddedObserver::WebContentsCreated(WebContents* web_contents) { DCHECK(!web_contents_); web_contents_ = web_contents; child_observer_.reset(new RenderViewCreatedObserver(web_contents)); if (runner_.get()) runner_->QuitClosure().Run(); } Commit Message: Apply ExtensionNavigationThrottle filesystem/blob checks to all frames. BUG=836858 Change-Id: I34333a72501129fd40b5a9aa6378c9f35f1e7fc2 Reviewed-on: https://chromium-review.googlesource.com/1028511 Reviewed-by: Devlin <[email protected]> Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Nick Carter <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#553867} 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: GLvoid StubGLLinkProgram(GLuint program) { glLinkProgram(program); } Commit Message: Add chromium_code: 1 to surface.gyp and gl.gyp to pick up -Werror. It looks like this was dropped accidentally in http://codereview.chromium.org/6718027 (surface.gyp) and http://codereview.chromium.org/6722026 (gl.gyp) Remove now-redudant code that's implied by chromium_code: 1. Fix the warnings that have crept in since chromium_code: 1 was removed. BUG=none TEST=none Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=91598 Review URL: http://codereview.chromium.org/7227009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91813 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 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: XGetFeedbackControl( register Display *dpy, XDevice *dev, int *num_feedbacks) { XFeedbackState *Feedback = NULL; XFeedbackState *Sav = NULL; xFeedbackState *f = NULL; xFeedbackState *sav = NULL; xGetFeedbackControlReq *req; xGetFeedbackControlReply rep; XExtDisplayInfo *info = XInput_find_display(dpy); LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1) return NULL; GetReq(GetFeedbackControl, req); req->reqType = info->codes->major_opcode; req->ReqType = X_GetFeedbackControl; req->deviceid = dev->device_id; if (!_XReply(dpy, (xReply *) & rep, 0, xFalse)) goto out; if (rep.length > 0) { unsigned long nbytes; size_t size = 0; int i; *num_feedbacks = rep.num_feedbacks; if (rep.length < (INT_MAX >> 2)) { nbytes = rep.length << 2; f = Xmalloc(nbytes); } if (!f) { _XEatDataWords(dpy, rep.length); goto out; goto out; } sav = f; _XRead(dpy, (char *)f, nbytes); for (i = 0; i < *num_feedbacks; i++) { if (f->length > nbytes) goto out; nbytes -= f->length; break; case PtrFeedbackClass: size += sizeof(XPtrFeedbackState); break; case IntegerFeedbackClass: size += sizeof(XIntegerFeedbackState); break; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; case StringFeedbackClass: { xStringFeedbackState *strf = (xStringFeedbackState *) f; size += sizeof(XStringFeedbackState) + (strf->num_syms_supported * sizeof(KeySym)); } size += sizeof(XBellFeedbackState); break; default: size += f->length; break; } if (size > INT_MAX) goto out; f = (xFeedbackState *) ((char *)f + f->length); } Feedback = Xmalloc(size); if (!Feedback) goto out; Sav = Feedback; f = sav; for (i = 0; i < *num_feedbacks; i++) { switch (f->class) { case KbdFeedbackClass: { xKbdFeedbackState *k; XKbdFeedbackState *K; k = (xKbdFeedbackState *) f; K = (XKbdFeedbackState *) Feedback; K->class = k->class; K->length = sizeof(XKbdFeedbackState); K->id = k->id; K->click = k->click; K->percent = k->percent; K->pitch = k->pitch; K->duration = k->duration; K->led_mask = k->led_mask; K->global_auto_repeat = k->global_auto_repeat; memcpy((char *)&K->auto_repeats[0], (char *)&k->auto_repeats[0], 32); break; } case PtrFeedbackClass: { xPtrFeedbackState *p; XPtrFeedbackState *P; p = (xPtrFeedbackState *) f; P = (XPtrFeedbackState *) Feedback; P->class = p->class; P->length = sizeof(XPtrFeedbackState); P->id = p->id; P->accelNum = p->accelNum; P->accelDenom = p->accelDenom; P->threshold = p->threshold; break; } case IntegerFeedbackClass: { xIntegerFeedbackState *ifs; XIntegerFeedbackState *I; ifs = (xIntegerFeedbackState *) f; I = (XIntegerFeedbackState *) Feedback; I->class = ifs->class; I->length = sizeof(XIntegerFeedbackState); I->id = ifs->id; I->resolution = ifs->resolution; I->minVal = ifs->min_value; I->maxVal = ifs->max_value; break; } case StringFeedbackClass: { xStringFeedbackState *s; XStringFeedbackState *S; s = (xStringFeedbackState *) f; S = (XStringFeedbackState *) Feedback; S->class = s->class; S->length = sizeof(XStringFeedbackState) + (s->num_syms_supported * sizeof(KeySym)); S->id = s->id; S->max_symbols = s->max_symbols; S->num_syms_supported = s->num_syms_supported; S->syms_supported = (KeySym *) (S + 1); memcpy((char *)S->syms_supported, (char *)(s + 1), (S->num_syms_supported * sizeof(KeySym))); break; } case LedFeedbackClass: { xLedFeedbackState *l; XLedFeedbackState *L; l = (xLedFeedbackState *) f; L = (XLedFeedbackState *) Feedback; L->class = l->class; L->length = sizeof(XLedFeedbackState); L->id = l->id; L->led_values = l->led_values; L->led_mask = l->led_mask; break; } case BellFeedbackClass: { xBellFeedbackState *b; XBellFeedbackState *B; b = (xBellFeedbackState *) f; B = (XBellFeedbackState *) Feedback; B->class = b->class; B->length = sizeof(XBellFeedbackState); B->id = b->id; B->percent = b->percent; B->pitch = b->pitch; B->duration = b->duration; break; } default: break; } f = (xFeedbackState *) ((char *)f + f->length); Feedback = (XFeedbackState *) ((char *)Feedback + Feedback->length); } } out: XFree((char *)sav); UnlockDisplay(dpy); SyncHandle(); return (Sav); } Commit Message: CWE ID: CWE-284 Target: 1 Example 2: Code: int ConvertSubpixelRendering( gfx::FontRenderParams::SubpixelRendering rendering) { switch (rendering) { case gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE: return 0; case gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB: return 1; case gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR: return 1; case gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB: return 1; case gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR: return 1; } NOTREACHED() << "Unexpected subpixel rendering value " << rendering; return 0; } Commit Message: Serialize struct tm in a safe way. BUG=765512 Change-Id: If235b8677eb527be2ac0fe621fc210e4116a7566 Reviewed-on: https://chromium-review.googlesource.com/679441 Commit-Queue: Chris Palmer <[email protected]> Reviewed-by: Julien Tinnes <[email protected]> Cr-Commit-Position: refs/heads/master@{#503948} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static uint32_t readU16(const uint8_t* data, size_t offset) { return data[offset] << 8 | data[offset + 1]; } Commit Message: Avoid integer overflows in parsing fonts A malformed TTF can cause size calculations to overflow. This patch checks the maximum reasonable value so that the total size fits in 32 bits. It also adds some explicit casting to avoid possible technical undefined behavior when parsing sized unsigned values. Bug: 25645298 Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616 (cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274) 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: bool BaseSessionService::RestoreUpdateTabNavigationCommand( const SessionCommand& command, TabNavigation* navigation, SessionID::id_type* tab_id) { scoped_ptr<Pickle> pickle(command.PayloadAsPickle()); if (!pickle.get()) return false; void* iterator = NULL; std::string url_spec; if (!pickle->ReadInt(&iterator, tab_id) || !pickle->ReadInt(&iterator, &(navigation->index_)) || !pickle->ReadString(&iterator, &url_spec) || !pickle->ReadString16(&iterator, &(navigation->title_)) || !pickle->ReadString(&iterator, &(navigation->state_)) || !pickle->ReadInt(&iterator, reinterpret_cast<int*>(&(navigation->transition_)))) return false; bool has_type_mask = pickle->ReadInt(&iterator, &(navigation->type_mask_)); if (has_type_mask) { std::string referrer_spec; pickle->ReadString(&iterator, &referrer_spec); int policy_int; WebReferrerPolicy policy; if (pickle->ReadInt(&iterator, &policy_int)) policy = static_cast<WebReferrerPolicy>(policy_int); else policy = WebKit::WebReferrerPolicyDefault; navigation->referrer_ = content::Referrer( referrer_spec.empty() ? GURL() : GURL(referrer_spec), policy); std::string content_state; if (CompressDataHelper::ReadAndDecompressStringFromPickle( *pickle.get(), &iterator, &content_state) && !content_state.empty()) { navigation->state_ = content_state; } } navigation->virtual_url_ = GURL(url_spec); return true; } Commit Message: Metrics for measuring how much overhead reading compressed content states adds. BUG=104293 TEST=NONE Review URL: https://chromiumcodereview.appspot.com/9426039 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@123733 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: R_API ut64 r_bin_java_bootstrap_arg_calc_size(RBinJavaBootStrapArgument *bsm_arg) { ut64 size = 0; if (bsm_arg) { size += 2; } return size; } Commit Message: Fix #10498 - Crash in fuzzed java file 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 snd_msnd_write_cfg_irq(int cfg, int num, u16 irq) { if (snd_msnd_write_cfg(cfg, IREG_LOGDEVICE, num)) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_NUMBER, LOBYTE(irq))) return -EIO; if (snd_msnd_write_cfg(cfg, IREG_IRQ_TYPE, IRQTYPE_EDGE)) return -EIO; return 0; } Commit Message: ALSA: msnd: Optimize / harden DSP and MIDI loops The ISA msnd drivers have loops fetching the ring-buffer head, tail and size values inside the loops. Such codes are inefficient and fragile. This patch optimizes it, and also adds the sanity check to avoid the endless loops. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131 Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133 Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void balloon_process(struct work_struct *work) { enum bp_state state = BP_DONE; long credit; do { mutex_lock(&balloon_mutex); credit = current_credit(); if (credit > 0) { if (balloon_is_inflated()) state = increase_reservation(credit); else state = reserve_additional_memory(); } if (credit < 0) state = decrease_reservation(-credit, GFP_BALLOON); state = update_schedule(state); mutex_unlock(&balloon_mutex); cond_resched(); } while (credit && state == BP_DONE); /* Schedule more work if there is some still to be done. */ if (state == BP_EAGAIN) schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ); } Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream. Instead of trying to allocate pages with GFP_USER in add_ballooned_pages() check the available free memory via si_mem_available(). GFP_USER is far less limiting memory exhaustion than the test via si_mem_available(). This will avoid dom0 running out of memory due to excessive foreign page mappings especially on ARM and on x86 in PVH mode, as those don't have a pre-ballooned area which can be used for foreign mappings. As the normal ballooning suffers from the same problem don't balloon down more than si_mem_available() pages in one iteration. At the same time limit the default maximum number of retries. This is part of XSA-300. Signed-off-by: Juergen Gross <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Target: 1 Example 2: Code: void showTree(const blink::FrameSelection& sel) { sel.ShowTreeForThis(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static Image *ReadTGAImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; PixelInfo pixel; Quantum index; register Quantum *q; register ssize_t i, x; size_t base, flag, offset, real, skip; ssize_t count, y; TGAInfo tga_info; unsigned char j, k, pixels[4], runlength; unsigned int alpha_bits; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read TGA header information. */ count=ReadBlob(image,1,&tga_info.id_length); tga_info.colormap_type=(unsigned char) ReadBlobByte(image); tga_info.image_type=(TGAImageType) ReadBlobByte(image); if ((count != 1) || ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARGB) && (tga_info.image_type != TGAMonochrome) && (tga_info.image_type != TGARLEColormap) && (tga_info.image_type != TGARLERGB) && (tga_info.image_type != TGARLEMonochrome)) || (((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGARLEColormap)) && (tga_info.colormap_type == 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); tga_info.colormap_index=ReadBlobLSBShort(image); tga_info.colormap_length=ReadBlobLSBShort(image); tga_info.colormap_size=(unsigned char) ReadBlobByte(image); tga_info.x_origin=ReadBlobLSBShort(image); tga_info.y_origin=ReadBlobLSBShort(image); tga_info.width=(unsigned short) ReadBlobLSBShort(image); tga_info.height=(unsigned short) ReadBlobLSBShort(image); tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image); tga_info.attributes=(unsigned char) ReadBlobByte(image); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) && (tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ image->columns=tga_info.width; image->rows=tga_info.height; alpha_bits=(tga_info.attributes & 0x0FU); image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) || (tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait; if ((tga_info.image_type != TGAColormap) && (tga_info.image_type != TGARLEColormap)) image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 : (tga_info.bits_per_pixel <= 16) ? 5 : (tga_info.bits_per_pixel == 24) ? 8 : (tga_info.bits_per_pixel == 32) ? 8 : 8); else image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 : (tga_info.colormap_size <= 16) ? 5 : (tga_info.colormap_size == 24) ? 8 : (tga_info.colormap_size == 32) ? 8 : 8); if ((tga_info.image_type == TGAColormap) || (tga_info.image_type == TGAMonochrome) || (tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome)) image->storage_class=PseudoClass; image->compression=NoCompression; if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLEMonochrome) || (tga_info.image_type == TGARLERGB)) image->compression=RLECompression; if (image->storage_class == PseudoClass) { if (tga_info.colormap_type != 0) image->colors=tga_info.colormap_index+tga_info.colormap_length; else { size_t one; one=1; image->colors=one << tga_info.bits_per_pixel; if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (tga_info.id_length != 0) { char *comment; size_t length; /* TGA image comment. */ length=(size_t) tga_info.id_length; comment=(char *) NULL; if (~length >= (MagickPathExtent-1)) comment=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment); comment[tga_info.id_length]='\0'; (void) SetImageProperty(image,"comment",comment,exception); comment=DestroyString(comment); } if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(image); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.alpha=(MagickRealType) OpaqueAlpha; if (tga_info.colormap_type != 0) { /* Read TGA raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) tga_info.colormap_index; i++) image->colormap[i]=pixel; for ( ; i < (ssize_t) image->colors; i++) { switch (tga_info.colormap_size) { case 8: default: { /* Gray scale. */ pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=pixel.red; pixel.blue=pixel.red; break; } case 15: case 16: { QuantumAny range; /* 5 bits each of red green and blue. */ j=(unsigned char) ReadBlobByte(image); k=(unsigned char) ReadBlobByte(image); range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); break; } case 24: { /* 8 bits each of blue, green and red. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } case 32: { /* 8 bits each of blue, green, red, and alpha. */ pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); break; } } image->colormap[i]=pixel; } } /* Convert TGA pixels to pixel packets. */ base=0; flag=0; skip=MagickFalse; real=0; index=0; runlength=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { real=offset; if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0) real=image->rows-real-1; q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((tga_info.image_type == TGARLEColormap) || (tga_info.image_type == TGARLERGB) || (tga_info.image_type == TGARLEMonochrome)) { if (runlength != 0) { runlength--; skip=flag != 0; } else { count=ReadBlob(image,1,&runlength); if (count != 1) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); flag=runlength & 0x80; if (flag != 0) runlength-=128; skip=MagickFalse; } } if (skip == MagickFalse) switch (tga_info.bits_per_pixel) { case 8: default: { /* Gray scale. */ index=(Quantum) ReadBlobByte(image); if (tga_info.colormap_type != 0) pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image, (ssize_t) index,exception)]; else { pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char) index); pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char) index); } break; } case 15: case 16: { QuantumAny range; /* 5 bits each of RGB. */ if (ReadBlob(image,2,pixels) != 2) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); j=pixels[0]; k=pixels[1]; range=GetQuantumRange(5UL); pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2, range); pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL* (k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range); pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range); if (image->alpha_trait != UndefinedPixelTrait) pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum) TransparentAlpha : (Quantum) OpaqueAlpha); if (image->storage_class == PseudoClass) index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+ j,exception); break; } case 24: { /* BGR pixels. */ if (ReadBlob(image,3,pixels) != 3) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); break; } case 32: { /* BGRA pixels. */ if (ReadBlob(image,4,pixels) != 4) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]); pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]); pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]); pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]); break; } } if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (image->storage_class == PseudoClass) SetPixelIndex(image,index,q); SetPixelRed(image,ClampToQuantum(pixel.red),q); SetPixelGreen(image,ClampToQuantum(pixel.green),q); SetPixelBlue(image,ClampToQuantum(pixel.blue),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); q+=GetPixelChannels(image); } /* if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4) offset+=4; else */ if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2) offset+=2; else offset++; if (offset >= image->rows) { base++; offset=base; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: https://bugs.launchpad.net/ubuntu/+source/imagemagick/+bug/1490362 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: void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) { struct iphdr *iph; int room; struct icmp_bxm icmp_param; struct rtable *rt = skb_rtable(skb_in); struct ipcm_cookie ipc; __be32 saddr; u8 tos; struct net *net; struct sock *sk; if (!rt) goto out; net = dev_net(rt->dst.dev); /* * Find the original header. It is expected to be valid, of course. * Check this, icmp_send is called from the most obscure devices * sometimes. */ iph = ip_hdr(skb_in); if ((u8 *)iph < skb_in->head || (skb_in->network_header + sizeof(*iph)) > skb_in->tail) goto out; /* * No replies to physical multicast/broadcast */ if (skb_in->pkt_type != PACKET_HOST) goto out; /* * Now check at the protocol level */ if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) goto out; /* * Only reply to fragment 0. We byte re-order the constant * mask for efficiency. */ if (iph->frag_off & htons(IP_OFFSET)) goto out; /* * If we send an ICMP error to an ICMP error a mess would result.. */ if (icmp_pointers[type].error) { /* * We are an error, check if we are replying to an * ICMP error */ if (iph->protocol == IPPROTO_ICMP) { u8 _inner_type, *itp; itp = skb_header_pointer(skb_in, skb_network_header(skb_in) + (iph->ihl << 2) + offsetof(struct icmphdr, type) - skb_in->data, sizeof(_inner_type), &_inner_type); if (itp == NULL) goto out; /* * Assume any unknown ICMP type is an error. This * isn't specified by the RFC, but think about it.. */ if (*itp > NR_ICMP_TYPES || icmp_pointers[*itp].error) goto out; } } sk = icmp_xmit_lock(net); if (sk == NULL) return; /* * Construct source address and options. */ saddr = iph->daddr; if (!(rt->rt_flags & RTCF_LOCAL)) { struct net_device *dev = NULL; rcu_read_lock(); if (rt_is_input_route(rt) && net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr) dev = dev_get_by_index_rcu(net, rt->rt_iif); if (dev) saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK); else saddr = 0; rcu_read_unlock(); } tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) | IPTOS_PREC_INTERNETCONTROL) : iph->tos; if (ip_options_echo(&icmp_param.replyopts, skb_in)) goto out_unlock; /* * Prepare data for ICMP header. */ icmp_param.data.icmph.type = type; icmp_param.data.icmph.code = code; icmp_param.data.icmph.un.gateway = info; icmp_param.data.icmph.checksum = 0; icmp_param.skb = skb_in; icmp_param.offset = skb_network_offset(skb_in); inet_sk(sk)->tos = tos; ipc.addr = iph->saddr; ipc.opt = &icmp_param.replyopts; ipc.tx_flags = 0; rt = icmp_route_lookup(net, skb_in, iph, saddr, tos, type, code, &icmp_param); if (IS_ERR(rt)) goto out_unlock; if (!icmpv4_xrlim_allow(net, rt, type, code)) goto ende; /* RFC says return as much as we can without exceeding 576 bytes. */ room = dst_mtu(&rt->dst); if (room > 576) room = 576; room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen; room -= sizeof(struct icmphdr); icmp_param.data_len = skb_in->len - icmp_param.offset; if (icmp_param.data_len > room) icmp_param.data_len = room; icmp_param.head_len = sizeof(struct icmphdr); icmp_push_reply(&icmp_param, &ipc, &rt); ende: ip_rt_put(rt); out_unlock: icmp_xmit_unlock(sk); out:; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: bool OmniboxViewViews::OnAfterPossibleChange(bool allow_keyword_ui_change) { State new_state; GetState(&new_state); OmniboxView::StateChanges state_changes = GetStateChanges(state_before_change_, new_state); state_changes.text_differs = state_changes.text_differs || (ime_composing_before_change_ != IsIMEComposing()); const bool something_changed = model()->OnAfterPossibleChange( state_changes, allow_keyword_ui_change && !IsIMEComposing()); if (something_changed && (state_changes.text_differs || state_changes.keyword_differs)) TextChanged(); else if (state_changes.selection_differs) EmphasizeURLComponents(); else if (delete_at_end_pressed_) model()->OnChanged(); return something_changed; } Commit Message: Strip JavaScript schemas on Linux text drop When dropping text onto the Omnibox, any leading JavaScript schemes should be stripped to avoid a "self-XSS" attack. This stripping already occurs in all cases except when plaintext is dropped on Linux. This CL corrects that oversight. Bug: 768910 Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062 Reviewed-on: https://chromium-review.googlesource.com/685638 Reviewed-by: Justin Donnelly <[email protected]> Commit-Queue: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#504695} CWE ID: CWE-79 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int cmd_stdin(void *data, const char *input) { RCore *core = (RCore *)data; if (input[0] == '?') { r_cons_printf ("Usage: '-' '.-' '. -' do the same\n"); return false; } return r_core_run_script (core, "-"); } Commit Message: Fix #7727 - undefined pointers and out of band string access fixes 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 FaviconWebUIHandler::OnFaviconDataAvailable( FaviconService::Handle request_handle, history::FaviconData favicon) { FaviconService* favicon_service = web_ui_->GetProfile()->GetFaviconService(Profile::EXPLICIT_ACCESS); int id = consumer_.GetClientData(favicon_service, request_handle); if (favicon.is_valid()) { FundamentalValue id_value(id); color_utils::GridSampler sampler; SkColor color = color_utils::CalculateKMeanColorOfPNG(favicon.image_data, 100, 665, sampler); std::string css_color = base::StringPrintf("rgb(%d, %d, %d)", SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); StringValue color_value(css_color); web_ui_->CallJavascriptFunction("ntp4.setFaviconDominantColor", id_value, color_value); } } Commit Message: ntp4: show larger favicons in most visited page extend favicon source to provide larger icons. For now, larger means at most 32x32. Also, the only icon we actually support at this resolution is the default (globe). BUG=none TEST=manual Review URL: http://codereview.chromium.org/7300017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91517 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize) { int c; char *bufptr; assert(bufsize > 0); JAS_DBGLOG(100, ("jas_stream_gets(%p, %p, %d)\n", stream, buf, bufsize)); bufptr = buf; while (bufsize > 1) { if ((c = jas_stream_getc(stream)) == EOF) { break; } *bufptr++ = c; --bufsize; if (c == '\n') { break; } } *bufptr = '\0'; return buf; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: base::string16 AuthenticatorInsertAndActivateUsbSheetModel::GetStepTitle() const { return l10n_util::GetStringFUTF16(IDS_WEBAUTHN_GENERIC_TITLE, GetRelyingPartyIdString(dialog_model())); } Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break. As requested by UX in [1], allow long host names to split a title into two lines. This allows us to show more of the name before eliding, although sufficiently long names will still trigger elision. Screenshot at https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r. [1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12 Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34 Bug: 870892 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812 Auto-Submit: Adam Langley <[email protected]> Commit-Queue: Nina Satragno <[email protected]> Reviewed-by: Nina Satragno <[email protected]> Cr-Commit-Position: refs/heads/master@{#658114} 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 RegisterProperties(IBusPropList* ibus_prop_list) { DLOG(INFO) << "RegisterProperties" << (ibus_prop_list ? "" : " (clear)"); ImePropertyList prop_list; // our representation. if (ibus_prop_list) { if (!FlattenPropertyList(ibus_prop_list, &prop_list)) { RegisterProperties(NULL); return; } } register_ime_properties_(language_library_, prop_list); } 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 void strictFunctionMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "strictFunction", "TestObject", info.Holder(), info.GetIsolate()); if (UNLIKELY(info.Length() < 3)) { exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(3, info.Length())); exceptionState.throwIfNeeded(); return; } TestObject* imp = V8TestObject::toNative(info.Holder()); V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, str, info[0]); V8TRYCATCH_VOID(float, a, static_cast<float>(info[1]->NumberValue())); V8TRYCATCH_EXCEPTION_VOID(int, b, toInt32(info[2], exceptionState), exceptionState); bool result = imp->strictFunction(str, a, b, exceptionState); if (exceptionState.throwIfNeeded()) return; v8SetReturnValueBool(info, result); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly) { ASSERT(&topResolver.runs() == &bidiRuns); ASSERT(topResolver.position() != endOfRuns); RenderObject* currentRoot = topResolver.position().root(); topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly); while (!topResolver.isolatedRuns().isEmpty()) { BidiRun* isolatedRun = topResolver.isolatedRuns().last(); topResolver.isolatedRuns().removeLast(); RenderObject* startObj = isolatedRun->object(); RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); InlineBidiResolver isolatedResolver; EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi(); TextDirection direction = isolatedInline->style()->direction(); if (unicodeBidi == Plaintext) direction = determinePlaintextDirectionality(isolatedInline, startObj); else { ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride); direction = isolatedInline->style()->direction(); } isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi))); setupResolverToResumeInIsolate(isolatedResolver, isolatedInline, startObj); InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start); isolatedResolver.setPositionIgnoringNestedIsolates(iter); isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly); if (isolatedResolver.runs().runCount()) bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs()); if (!isolatedResolver.isolatedRuns().isEmpty()) { topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns()); isolatedResolver.isolatedRuns().clear(); currentRoot = isolatedInline; } } } Commit Message: Update containtingIsolate to go back all the way to top isolate from current root, rather than stopping at the first isolate it finds. This works because the current root is always updated with each isolate run. BUG=279277 Review URL: https://chromiumcodereview.appspot.com/23972003 git-svn-id: svn://svn.chromium.org/blink/trunk@157268 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = 0; size_t n; if( ssl->conf->f_psk == NULL && ( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL || ssl->conf->psk_identity_len == 0 || ssl->conf->psk_len == 0 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Receive client pre-shared key identity name */ if( *p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( n < 1 || n > 65535 || *p + n > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( n != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } *p += n; return( 0 ); } Commit Message: Prevent bounds check bypass through overflow in PSK identity parsing The check `if( *p + n > end )` in `ssl_parse_client_psk_identity` is unsafe because `*p + n` might overflow, thus bypassing the check. As `n` is a user-specified value up to 65K, this is relevant if the library happens to be located in the last 65K of virtual memory. This commit replaces the check by a safe version. CWE ID: CWE-190 Target: 1 Example 2: Code: SplashError Splash::drawImage(SplashImageSource src, void *srcData, SplashColorMode srcMode, GBool srcAlpha, int w, int h, SplashCoord *mat, GBool interpolate, GBool tilingPattern) { GBool ok; SplashBitmap *scaledImg; SplashClipResult clipRes; GBool minorAxisZero; int x0, y0, x1, y1, scaledWidth, scaledHeight; int nComps; int yp; if (debugMode) { printf("drawImage: srcMode=%d srcAlpha=%d w=%d h=%d mat=[%.2f %.2f %.2f %.2f %.2f %.2f]\n", srcMode, srcAlpha, w, h, (double)mat[0], (double)mat[1], (double)mat[2], (double)mat[3], (double)mat[4], (double)mat[5]); } ok = gFalse; // make gcc happy nComps = 0; // make gcc happy switch (bitmap->mode) { case splashModeMono1: case splashModeMono8: ok = srcMode == splashModeMono8; nComps = 1; break; case splashModeRGB8: ok = srcMode == splashModeRGB8; nComps = 3; break; case splashModeXBGR8: ok = srcMode == splashModeXBGR8; nComps = 4; break; case splashModeBGR8: ok = srcMode == splashModeBGR8; nComps = 3; break; #if SPLASH_CMYK case splashModeCMYK8: ok = srcMode == splashModeCMYK8; nComps = 4; break; case splashModeDeviceN8: ok = srcMode == splashModeDeviceN8; nComps = SPOT_NCOMPS+4; break; #endif default: ok = gFalse; break; } if (!ok) { return splashErrModeMismatch; } if (!splashCheckDet(mat[0], mat[1], mat[2], mat[3], 0.000001)) { return splashErrSingularMatrix; } minorAxisZero = mat[1] == 0 && mat[2] == 0; if (mat[0] > 0 && minorAxisZero && mat[3] > 0) { x0 = imgCoordMungeLower(mat[4]); y0 = imgCoordMungeLower(mat[5]); x1 = imgCoordMungeUpper(mat[0] + mat[4]); y1 = imgCoordMungeUpper(mat[3] + mat[5]); if (x0 == x1) { ++x1; } if (y0 == y1) { ++y1; } clipRes = state->clip->testRect(x0, y0, x1 - 1, y1 - 1); opClipRes = clipRes; if (clipRes != splashClipAllOutside) { scaledWidth = x1 - x0; scaledHeight = y1 - y0; yp = h / scaledHeight; if (yp < 0 || yp > INT_MAX - 1) { return splashErrBadArg; } scaledImg = scaleImage(src, srcData, srcMode, nComps, srcAlpha, w, h, scaledWidth, scaledHeight, interpolate); if (scaledImg == NULL) { return splashErrBadArg; } blitImage(scaledImg, srcAlpha, x0, y0, clipRes); delete scaledImg; } } else if (mat[0] > 0 && minorAxisZero && mat[3] < 0) { x0 = imgCoordMungeLower(mat[4]); y0 = imgCoordMungeLower(mat[3] + mat[5]); x1 = imgCoordMungeUpper(mat[0] + mat[4]); y1 = imgCoordMungeUpper(mat[5]); if (x0 == x1) { if (mat[4] + mat[0] * 0.5 < x0) { --x0; } else { ++x1; } } if (y0 == y1) { if (mat[5] + mat[1] * 0.5 < y0) { --y0; } else { ++y1; } } clipRes = state->clip->testRect(x0, y0, x1 - 1, y1 - 1); opClipRes = clipRes; if (clipRes != splashClipAllOutside) { scaledWidth = x1 - x0; scaledHeight = y1 - y0; yp = h / scaledHeight; if (yp < 0 || yp > INT_MAX - 1) { return splashErrBadArg; } scaledImg = scaleImage(src, srcData, srcMode, nComps, srcAlpha, w, h, scaledWidth, scaledHeight, interpolate); if (scaledImg == NULL) { return splashErrBadArg; } vertFlipImage(scaledImg, scaledWidth, scaledHeight, nComps); blitImage(scaledImg, srcAlpha, x0, y0, clipRes); delete scaledImg; } } else { return arbitraryTransformImage(src, srcData, srcMode, nComps, srcAlpha, w, h, mat, interpolate, tilingPattern); } return splashOk; } Commit Message: CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void BeginInstallWithManifestFunction::OnParseSuccess( const SkBitmap& icon, DictionaryValue* parsed_manifest) { CHECK(parsed_manifest); icon_ = icon; parsed_manifest_.reset(parsed_manifest); std::string init_errors; dummy_extension_ = Extension::Create( FilePath(), Extension::INTERNAL, *static_cast<DictionaryValue*>(parsed_manifest_.get()), Extension::NO_FLAGS, &init_errors); if (!dummy_extension_.get()) { OnParseFailure(MANIFEST_ERROR, std::string(kInvalidManifestError)); return; } if (icon_.empty()) icon_ = Extension::GetDefaultIcon(dummy_extension_->is_app()); ShowExtensionInstallDialog(profile(), this, dummy_extension_.get(), &icon_, dummy_extension_->GetPermissionMessageStrings(), ExtensionInstallUI::INSTALL_PROMPT); } Commit Message: Adding tests for new webstore beginInstallWithManifest method. BUG=75821 TEST=none Review URL: http://codereview.chromium.org/6900059 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@83080 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
1