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 gboolean cosine_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) { gint64 offset; int pkt_len; char line[COSINE_LINE_LENGTH]; /* Find the next packet */ offset = cosine_seek_next_packet(wth, err, err_info, line); if (offset < 0) return FALSE; *data_offset = offset; /* Parse the header */ pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info); if (pkt_len == -1) return FALSE; /* Convert the ASCII hex dump to binary data */ return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len, wth->frame_buffer, err, err_info); } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12395 Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2 Reviewed-on: https://code.wireshark.org/review/15172 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static void terminate_walk(struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { path_put(&nd->path); } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } } 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: virtual void DescribeNegationTo(::std::ostream* os) const { *os << "is definitely NOT the same url filter as " << &to_match_; } Commit Message: Don't downcast DownloadManagerDelegate to ChromeDownloadManagerDelegate. DownloadManager has public SetDelegate method and tests and or other subsystems can install their own implementations of the delegate. Bug: 805905 Change-Id: Iecf1e0aceada0e1048bed1e2d2ceb29ca64295b8 TBR: tests updated to follow the API change. Reviewed-on: https://chromium-review.googlesource.com/894702 Reviewed-by: David Vallet <[email protected]> Reviewed-by: Min Qin <[email protected]> Cr-Commit-Position: refs/heads/master@{#533515} 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 cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: static int hash_sendmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t ignored) { int limit = ALG_MAX_PAGES * PAGE_SIZE; struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned long iovlen; struct iovec *iov; long copied = 0; int err; if (limit > sk->sk_sndbuf) limit = sk->sk_sndbuf; lock_sock(sk); if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } ctx->more = 0; for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0; iovlen--, iov++) { unsigned long seglen = iov->iov_len; char __user *from = iov->iov_base; while (seglen) { int len = min_t(unsigned long, seglen, limit); int newlen; newlen = af_alg_make_sg(&ctx->sgl, from, len, 0); if (newlen < 0) { err = copied ? 0 : newlen; goto unlock; } ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, newlen); err = af_alg_wait_for_completion( crypto_ahash_update(&ctx->req), &ctx->completion); af_alg_free_sg(&ctx->sgl); if (err) goto unlock; seglen -= newlen; from += newlen; copied += newlen; } } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more) { ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); } unlock: release_sock(sk); return err ?: copied; } Commit Message: crypto: algif - suppress sending source address information in recvmsg The current code does not set the msg_namelen member to 0 and therefore makes net/socket.c leak the local sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. Fix that. Cc: <[email protected]> # 2.6.38 Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int proc_claim_port(struct usb_dev_state *ps, void __user *arg) { unsigned portnum; int rc; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; rc = usb_hub_claim_port(ps->dev, portnum, ps); if (rc == 0) snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n", portnum, task_pid_nr(current), current->comm); return rc; } Commit Message: USB: usbfs: fix potential infoleak in devio The stack object “ci” has a total size of 8 bytes. Its last 3 bytes are padding bytes which are not initialized and leaked to userland via “copy_to_user”. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2) { register const struct ip6_frag *dp; register const struct ip6_hdr *ip6; dp = (const struct ip6_frag *)bp; ip6 = (const struct ip6_hdr *)bp2; ND_TCHECK(dp->ip6f_offlg); if (ndo->ndo_vflag) { ND_PRINT((ndo, "frag (0x%08x:%d|%ld)", EXTRACT_32BITS(&dp->ip6f_ident), EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } else { ND_PRINT((ndo, "frag (%d|%ld)", EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } /* it is meaningless to decode non-first fragment */ if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0) return -1; else { ND_PRINT((ndo, " ")); return sizeof(struct ip6_frag); } trunc: ND_PRINT((ndo, "[|frag]")); return -1; } Commit Message: CVE-2017-13031/Check for the presence of the entire IPv6 fragment header. 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. Clean up some whitespace in tests/TESTLIST while we're at it. CWE ID: CWE-125 Target: 1 Example 2: Code: void Run(const v8::FunctionCallbackInfo<v8::Value>& args) { v8::Isolate* isolate = automation_bindings_->GetIsolate(); if (args.Length() < 4 || !args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) { ThrowInvalidArgumentsException(automation_bindings_); } int tree_id = args[0]->Int32Value(); int node_id = args[1]->Int32Value(); int start = args[2]->Int32Value(); int end = args[3]->Int32Value(); TreeCache* cache = automation_bindings_->GetTreeCacheFromTreeID(tree_id); if (!cache) return; ui::AXNode* node = cache->tree.GetFromId(node_id); if (!node) return; function_(isolate, args.GetReturnValue(), cache, node, start, end); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID: Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PHPAPI zend_string *php_addslashes(zend_string *str, int should_free) { /* maximum string length, worst case situation */ char *source, *target; char *end; size_t offset; zend_string *new_str; if (!str) { return ZSTR_EMPTY_ALLOC(); } source = ZSTR_VAL(str); end = source + ZSTR_LEN(str); while (source < end) { switch (*source) { case '\0': case '\'': case '\"': case '\\': goto do_escape; default: source++; break; } } if (!should_free) { return zend_string_copy(str); } return str; do_escape: offset = source - (char *)ZSTR_VAL(str); new_str = zend_string_alloc(offset + (2 * (ZSTR_LEN(str) - offset)), 0); memcpy(ZSTR_VAL(new_str), ZSTR_VAL(str), offset); target = ZSTR_VAL(new_str) + offset; while (source < end) { switch (*source) { case '\0': *target++ = '\\'; *target++ = '0'; break; case '\'': case '\"': case '\\': *target++ = '\\'; /* break is missing *intentionally* */ default: *target++ = *source; break; } source++; } *target = 0; if (should_free) { zend_string_release(str); } if (ZSTR_LEN(new_str) - (target - ZSTR_VAL(new_str)) > 16) { new_str = zend_string_truncate(new_str, target - ZSTR_VAL(new_str), 0); } else { ZSTR_LEN(new_str) = target - ZSTR_VAL(new_str); } return new_str; } Commit Message: CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: 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->card = card; 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: Fix replacing user controls There are two issues with the current implementation for replacing user controls. The first is that the code does not check if the control is actually a user control and neither does it check if the control is owned by the process that tries to remove it. That allows userspace applications to remove arbitrary controls, which can cause a user after free if a for example a driver does not expect a control to be removed from under its feed. The second issue is that on one hand when a control is replaced the user_ctl_count limit is not checked and on the other hand the user_ctl_count is increased (even though the number of user controls does not change). This allows userspace, once the user_ctl_count limit as been reached, to repeatedly replace a control until user_ctl_count overflows. Once that happens new controls can be added effectively bypassing the user_ctl_count limit. Both issues can be fixed by instead of open-coding the removal of the control that is to be replaced to use snd_ctl_remove_user_ctl(). This function does proper permission checks as well as decrements user_ctl_count after the control has been removed. Note that by using snd_ctl_remove_user_ctl() the check which returns -EBUSY at beginning of the function if the control already exists is removed. This is not a problem though since the check is quite useless, because the lock that is protecting the control list is released between the check and before adding the new control to the list, which means that it is possible that a different control with the same settings is added to the list after the check. Luckily there is another check that is done while holding the lock in snd_ctl_add(), so we'll rely on that to make sure that the same control is not added twice. 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-189 Target: 1 Example 2: Code: void MetadataRetrieverClient::disconnect() { ALOGV("disconnect from pid %d", mPid); Mutex::Autolock lock(mLock); mRetriever.clear(); mThumbnail.clear(); mAlbumArt.clear(); IPCThreadState::self()->flushCommands(); } Commit Message: Clear unused pointer field when sending across binder Bug: 28377502 Change-Id: Iad5ebfb0a9ef89f09755bb332579dbd3534f9c98 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: Profile* BrowserCommandController::profile() { return browser_->profile(); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; if (a->type == szMAPI_UNICODE_STRING) { v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; } Commit Message: Use asserts on lengths to prevent invalid reads/writes. CWE ID: CWE-125 Target: 1 Example 2: Code: static void mem_cgroup_oom_notify(struct mem_cgroup *memcg) { struct mem_cgroup *iter; for_each_mem_cgroup_tree(iter, memcg) mem_cgroup_oom_notify_cb(iter); } 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: void utf16_to_utf8(const char16_t* src, size_t src_len, char* dst) { if (src == NULL || src_len == 0 || dst == NULL) { return; } const char16_t* cur_utf16 = src; const char16_t* const end_utf16 = src + src_len; char *cur = dst; while (cur_utf16 < end_utf16) { char32_t utf32; if((*cur_utf16 & 0xFC00) == 0xD800 && (cur_utf16 + 1) < end_utf16 && (*(cur_utf16 + 1) & 0xFC00) == 0xDC00) { utf32 = (*cur_utf16++ - 0xD800) << 10; utf32 |= *cur_utf16++ - 0xDC00; utf32 += 0x10000; } else { utf32 = (char32_t) *cur_utf16++; } const size_t len = utf32_codepoint_utf8_length(utf32); utf32_codepoint_to_utf8((uint8_t*)cur, utf32, len); cur += len; } *cur = '\0'; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119 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: WebSocketJob::WebSocketJob(SocketStream::Delegate* delegate) : delegate_(delegate), state_(INITIALIZED), waiting_(false), callback_(NULL), handshake_request_(new WebSocketHandshakeRequestHandler), handshake_response_(new WebSocketHandshakeResponseHandler), started_to_send_handshake_request_(false), handshake_request_sent_(0), response_cookies_save_index_(0), send_frame_handler_(new WebSocketFrameHandler), receive_frame_handler_(new WebSocketFrameHandler) { } Commit Message: Use ScopedRunnableMethodFactory in WebSocketJob Don't post SendPending if it is already posted. BUG=89795 TEST=none Review URL: http://codereview.chromium.org/7488007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93599 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: int ASN1_TYPE_get(ASN1_TYPE *a) { if ((a->value.ptr != NULL) || (a->type == V_ASN1_NULL)) return (a->type); else return (0); } Commit Message: CWE ID: CWE-17 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: lspping_print(netdissect_options *ndo, register const u_char *pptr, register u_int len) { const struct lspping_common_header *lspping_com_header; const struct lspping_tlv_header *lspping_tlv_header; const struct lspping_tlv_header *lspping_subtlv_header; const u_char *tptr,*tlv_tptr,*subtlv_tptr; u_int tlen,lspping_tlv_len,lspping_tlv_type,tlv_tlen; int tlv_hexdump,subtlv_hexdump; u_int lspping_subtlv_len,lspping_subtlv_type; struct timeval timestamp; union { const struct lspping_tlv_downstream_map_t *lspping_tlv_downstream_map; const struct lspping_tlv_downstream_map_ipv4_t *lspping_tlv_downstream_map_ipv4; const struct lspping_tlv_downstream_map_ipv4_unmb_t *lspping_tlv_downstream_map_ipv4_unmb; const struct lspping_tlv_downstream_map_ipv6_t *lspping_tlv_downstream_map_ipv6; const struct lspping_tlv_downstream_map_ipv6_unmb_t *lspping_tlv_downstream_map_ipv6_unmb; const struct lspping_tlv_downstream_map_info_t *lspping_tlv_downstream_map_info; } tlv_ptr; union { const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *lspping_tlv_targetfec_subtlv_ldp_ipv4; const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *lspping_tlv_targetfec_subtlv_ldp_ipv6; const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *lspping_tlv_targetfec_subtlv_rsvp_ipv4; const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *lspping_tlv_targetfec_subtlv_rsvp_ipv6; const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv4; const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv6; const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *lspping_tlv_targetfec_subtlv_l2vpn_endpt; const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *lspping_tlv_targetfec_subtlv_l2vpn_vcid_old; const struct lspping_tlv_targetfec_subtlv_fec_128_pw *lspping_tlv_targetfec_subtlv_l2vpn_vcid; const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *lspping_tlv_targetfec_subtlv_bgp_ipv4; const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *lspping_tlv_targetfec_subtlv_bgp_ipv6; } subtlv_ptr; tptr=pptr; lspping_com_header = (const struct lspping_common_header *)pptr; if (len < sizeof(const struct lspping_common_header)) goto tooshort; ND_TCHECK(*lspping_com_header); /* * Sanity checking of the header. */ if (EXTRACT_16BITS(&lspping_com_header->version[0]) != LSPPING_VERSION) { ND_PRINT((ndo, "LSP-PING version %u packet not supported", EXTRACT_16BITS(&lspping_com_header->version[0]))); return; } /* in non-verbose mode just lets print the basic Message Type*/ if (ndo->ndo_vflag < 1) { ND_PRINT((ndo, "LSP-PINGv%u, %s, seq %u, length: %u", EXTRACT_16BITS(&lspping_com_header->version[0]), tok2str(lspping_msg_type_values, "unknown (%u)",lspping_com_header->msg_type), EXTRACT_32BITS(lspping_com_header->seq_number), len)); return; } /* ok they seem to want to know everything - lets fully decode it */ tlen=len; ND_PRINT((ndo, "\n\tLSP-PINGv%u, msg-type: %s (%u), length: %u\n\t reply-mode: %s (%u)", EXTRACT_16BITS(&lspping_com_header->version[0]), tok2str(lspping_msg_type_values, "unknown",lspping_com_header->msg_type), lspping_com_header->msg_type, len, tok2str(lspping_reply_mode_values, "unknown",lspping_com_header->reply_mode), lspping_com_header->reply_mode)); /* * the following return codes require that the subcode is attached * at the end of the translated token output */ if (lspping_com_header->return_code == 3 || lspping_com_header->return_code == 4 || lspping_com_header->return_code == 8 || lspping_com_header->return_code == 10 || lspping_com_header->return_code == 11 || lspping_com_header->return_code == 12 ) ND_PRINT((ndo, "\n\t Return Code: %s %u (%u)\n\t Return Subcode: (%u)", tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code), lspping_com_header->return_subcode, lspping_com_header->return_code, lspping_com_header->return_subcode)); else ND_PRINT((ndo, "\n\t Return Code: %s (%u)\n\t Return Subcode: (%u)", tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code), lspping_com_header->return_code, lspping_com_header->return_subcode)); ND_PRINT((ndo, "\n\t Sender Handle: 0x%08x, Sequence: %u", EXTRACT_32BITS(lspping_com_header->sender_handle), EXTRACT_32BITS(lspping_com_header->seq_number))); timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_sent_sec); timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_sent_usec); ND_PRINT((ndo, "\n\t Sender Timestamp: ")); ts_print(ndo, &timestamp); timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_sec); timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_usec); ND_PRINT((ndo, "Receiver Timestamp: ")); if ((timestamp.tv_sec != 0) && (timestamp.tv_usec != 0)) ts_print(ndo, &timestamp); else ND_PRINT((ndo, "no timestamp")); tptr+=sizeof(const struct lspping_common_header); tlen-=sizeof(const struct lspping_common_header); while (tlen != 0) { /* Does the TLV go past the end of the packet? */ if (tlen < sizeof(struct lspping_tlv_header)) goto tooshort; /* did we capture enough for fully decoding the tlv header ? */ ND_TCHECK2(*tptr, sizeof(struct lspping_tlv_header)); lspping_tlv_header = (const struct lspping_tlv_header *)tptr; lspping_tlv_type=EXTRACT_16BITS(lspping_tlv_header->type); lspping_tlv_len=EXTRACT_16BITS(lspping_tlv_header->length); ND_PRINT((ndo, "\n\t %s TLV (%u), length: %u", tok2str(lspping_tlv_values, "Unknown", lspping_tlv_type), lspping_tlv_type, lspping_tlv_len)); /* some little sanity checking */ if (lspping_tlv_len == 0) { tptr+=sizeof(struct lspping_tlv_header); tlen-=sizeof(struct lspping_tlv_header); continue; /* no value to dissect */ } tlv_tptr=tptr+sizeof(struct lspping_tlv_header); tlv_tlen=lspping_tlv_len; /* header not included -> no adjustment */ /* Does the TLV go past the end of the packet? */ if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header)) goto tooshort; /* did we capture enough for fully decoding the tlv ? */ ND_TCHECK2(*tlv_tptr, lspping_tlv_len); tlv_hexdump=FALSE; switch(lspping_tlv_type) { case LSPPING_TLV_TARGET_FEC_STACK: while (tlv_tlen != 0) { /* Does the subTLV header go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_header)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* did we capture enough for fully decoding the subtlv header ? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_header)); subtlv_hexdump=FALSE; lspping_subtlv_header = (const struct lspping_tlv_header *)tlv_tptr; lspping_subtlv_type=EXTRACT_16BITS(lspping_subtlv_header->type); lspping_subtlv_len=EXTRACT_16BITS(lspping_subtlv_header->length); subtlv_tptr=tlv_tptr+sizeof(struct lspping_tlv_header); /* Does the subTLV go past the end of the TLV? */ if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for fully decoding the subTLV? */ ND_TCHECK2(*subtlv_tptr, lspping_subtlv_len); ND_PRINT((ndo, "\n\t %s subTLV (%u), length: %u", tok2str(lspping_tlvtargetfec_subtlv_values, "Unknown", lspping_subtlv_type), lspping_subtlv_type, lspping_subtlv_len)); switch(lspping_subtlv_type) { case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 5) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4 = \ (const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t %s/%u", ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 17) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6 = \ (const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t %s/%u", ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 5) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4 = \ (const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t %s/%u", ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 17) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6 = \ (const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t %s/%u", ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 20) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 20")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4 = \ (const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \ "\n\t tunnel-id 0x%04x, extended tunnel-id %s", ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_endpoint), ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_sender), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->lsp_id), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_id), ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->extended_tunnel_id))); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 56) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 56")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6 = \ (const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \ "\n\t tunnel-id 0x%04x, extended tunnel-id %s", ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_endpoint), ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_sender), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->lsp_id), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_id), ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->extended_tunnel_id))); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 13) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 13")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4 = \ (const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t RD: %s, %s/%u", bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->rd), ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 25) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 25")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6 = \ (const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t RD: %s, %s/%u", bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->rd), ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix), subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix_len)); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 14) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt = \ (const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *)subtlv_tptr; ND_PRINT((ndo, "\n\t RD: %s, Sender VE ID: %u, Receiver VE ID: %u" \ "\n\t Encapsulation Type: %s (%u)", bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->rd), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->sender_ve_id), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->receiver_ve_id), tok2str(mpls_pw_types_values, "unknown", EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation)), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation))); } break; /* the old L2VPN VCID subTLV does not have support for the sender field */ case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 10) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 10")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old = \ (const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *)subtlv_tptr; ND_PRINT((ndo, "\n\t Remote PE: %s" \ "\n\t PW ID: 0x%08x, PW Type: %s (%u)", ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->remote_pe_address), EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_id), tok2str(mpls_pw_types_values, "unknown", EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type)), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type))); } break; case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW: /* Is the subTLV length correct? */ if (lspping_subtlv_len != 14) { ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14")); subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ } else { subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid = \ (const struct lspping_tlv_targetfec_subtlv_fec_128_pw *)subtlv_tptr; ND_PRINT((ndo, "\n\t Sender PE: %s, Remote PE: %s" \ "\n\t PW ID: 0x%08x, PW Type: %s (%u)", ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->sender_pe_address), ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->remote_pe_address), EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_id), tok2str(mpls_pw_types_values, "unknown", EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type)), EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type))); } break; default: subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */ break; } /* do we want to see an additionally subtlv hexdump ? */ if (ndo->ndo_vflag > 1 || subtlv_hexdump==TRUE) print_unknown_data(ndo, tlv_tptr+sizeof(struct lspping_tlv_header), \ "\n\t ", lspping_subtlv_len); /* All subTLVs are aligned to four octet boundary */ if (lspping_subtlv_len % 4) { lspping_subtlv_len += 4 - (lspping_subtlv_len % 4); /* Does the subTLV, including padding, go past the end of the TLV? */ if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) { ND_PRINT((ndo, "\n\t\t TLV is too short")); return; } } tlv_tptr+=lspping_subtlv_len; tlv_tlen-=lspping_subtlv_len+sizeof(struct lspping_tlv_header); } break; case LSPPING_TLV_DOWNSTREAM_MAPPING: /* Does the header go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough to get the address family? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_t)); tlv_ptr.lspping_tlv_downstream_map= \ (const struct lspping_tlv_downstream_map_t *)tlv_tptr; /* that strange thing with the downstream map TLV is that until now * we do not know if its IPv4 or IPv6 or is unnumbered; after * we find the address-type, we recast the tlv_tptr and move on. */ ND_PRINT((ndo, "\n\t MTU: %u, Address-Type: %s (%u)", EXTRACT_16BITS(tlv_ptr.lspping_tlv_downstream_map->mtu), tok2str(lspping_tlv_downstream_addr_values, "unknown", tlv_ptr.lspping_tlv_downstream_map->address_type), tlv_ptr.lspping_tlv_downstream_map->address_type)); switch(tlv_ptr.lspping_tlv_downstream_map->address_type) { case LSPPING_AFI_IPV4: /* Does the data go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for this part of the TLV? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_t)); tlv_ptr.lspping_tlv_downstream_map_ipv4= \ (const struct lspping_tlv_downstream_map_ipv4_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Downstream IP: %s" \ "\n\t Downstream Interface IP: %s", ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_ip), ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_interface))); tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_t); tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_t); break; case LSPPING_AFI_IPV4_UNMB: /* Does the data go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for this part of the TLV? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t)); tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb= \ (const struct lspping_tlv_downstream_map_ipv4_unmb_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Downstream IP: %s" \ "\n\t Downstream Interface Index: 0x%08x", ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_ip), EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_interface))); tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t); tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t); break; case LSPPING_AFI_IPV6: /* Does the data go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for this part of the TLV? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_t)); tlv_ptr.lspping_tlv_downstream_map_ipv6= \ (const struct lspping_tlv_downstream_map_ipv6_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Downstream IP: %s" \ "\n\t Downstream Interface IP: %s", ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_ip), ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_interface))); tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_t); tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_t); break; case LSPPING_AFI_IPV6_UNMB: /* Does the data go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for this part of the TLV? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t)); tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb= \ (const struct lspping_tlv_downstream_map_ipv6_unmb_t *)tlv_tptr; ND_PRINT((ndo, "\n\t Downstream IP: %s" \ "\n\t Downstream Interface Index: 0x%08x", ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_ip), EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_interface))); tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t); tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t); break; default: /* should not happen ! - no error message - tok2str() has barked already */ break; } /* Does the data go past the end of the TLV? */ if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_info_t)) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } /* Did we capture enough for this part of the TLV? */ ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_info_t)); tlv_ptr.lspping_tlv_downstream_map_info= \ (const struct lspping_tlv_downstream_map_info_t *)tlv_tptr; /* FIXME add hash-key type, depth limit, multipath processing */ tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_info_t); tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_info_t); /* FIXME print downstream labels */ tlv_hexdump=TRUE; /* dump the TLV until code complete */ break; case LSPPING_TLV_BFD_DISCRIMINATOR: if (tlv_tlen < LSPPING_TLV_BFD_DISCRIMINATOR_LEN) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } else { ND_TCHECK2(*tptr, LSPPING_TLV_BFD_DISCRIMINATOR_LEN); ND_PRINT((ndo, "\n\t BFD Discriminator 0x%08x", EXTRACT_32BITS(tptr))); } break; case LSPPING_TLV_VENDOR_ENTERPRISE: { uint32_t vendor_id; if (tlv_tlen < LSPPING_TLV_VENDOR_ENTERPRISE_LEN) { ND_PRINT((ndo, "\n\t TLV is too short")); tlv_hexdump = TRUE; goto tlv_tooshort; } else { ND_TCHECK2(*tptr, LSPPING_TLV_VENDOR_ENTERPRISE_LEN); vendor_id = EXTRACT_32BITS(tlv_tptr); ND_PRINT((ndo, "\n\t Vendor: %s (0x%04x)", tok2str(smi_values, "Unknown", vendor_id), vendor_id)); } } break; /* * FIXME those are the defined TLVs that lack a decoder * you are welcome to contribute code ;-) */ case LSPPING_TLV_PAD: case LSPPING_TLV_ERROR_CODE: case LSPPING_TLV_VENDOR_PRIVATE: default: if (ndo->ndo_vflag <= 1) print_unknown_data(ndo, tlv_tptr, "\n\t ", tlv_tlen); break; } /* do we want to see an additionally tlv hexdump ? */ tlv_tooshort: if (ndo->ndo_vflag > 1 || tlv_hexdump==TRUE) print_unknown_data(ndo, tptr+sizeof(struct lspping_tlv_header), "\n\t ", lspping_tlv_len); /* All TLVs are aligned to four octet boundary */ if (lspping_tlv_len % 4) { lspping_tlv_len += (4 - lspping_tlv_len % 4); /* Does the TLV, including padding, go past the end of the packet? */ if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header)) goto tooshort; } tptr+=lspping_tlv_len+sizeof(struct lspping_tlv_header); tlen-=lspping_tlv_len+sizeof(struct lspping_tlv_header); } return; tooshort: ND_PRINT((ndo, "\n\t\t packet is too short")); return; trunc: ND_PRINT((ndo, "\n\t\t packet exceeded snapshot")); return; } Commit Message: CVE-2017-12900/Properly terminate all struct tok arrays. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void GpuDataManager::UpdateGpuFeatureFlags() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &GpuDataManager::UpdateGpuFeatureFlags)); return; } GpuBlacklist* gpu_blacklist = GetGpuBlacklist(); if (gpu_blacklist == NULL) return; if (!gpu_blacklist) { gpu_feature_flags_.set_flags(0); return; } { base::AutoLock auto_lock(gpu_info_lock_); gpu_feature_flags_ = gpu_blacklist->DetermineGpuFeatureFlags( GpuBlacklist::kOsAny, NULL, gpu_info_); } uint32 max_entry_id = gpu_blacklist->max_entry_id(); if (!gpu_feature_flags_.flags()) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", 0, max_entry_id + 1); return; } RunGpuInfoUpdateCallbacks(); std::vector<uint32> flag_entries; gpu_blacklist->GetGpuFeatureFlagEntries( GpuFeatureFlags::kGpuFeatureAll, flag_entries); DCHECK_GT(flag_entries.size(), 0u); for (size_t i = 0; i < flag_entries.size(); ++i) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", flag_entries[i], max_entry_id + 1); } } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: static int efx_pm_resume(struct device *dev) { struct pci_dev *pci_dev = to_pci_dev(dev); struct efx_nic *efx = pci_get_drvdata(pci_dev); int rc; rc = pci_set_power_state(pci_dev, PCI_D0); if (rc) return rc; pci_restore_state(pci_dev); rc = pci_enable_device(pci_dev); if (rc) return rc; pci_set_master(efx->pci_dev); rc = efx->type->reset(efx, RESET_TYPE_ALL); if (rc) return rc; rc = efx->type->init(efx); if (rc) return rc; efx_pm_thaw(dev); return 0; } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void close_all_sockets(atransport* t) { asocket* s; /* this is a little gross, but since s->close() *will* modify ** the list out from under you, your options are limited. */ std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); restart: for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->transport == t || (s->peer && s->peer->transport == t)) { local_socket_close(s); goto restart; } } } Commit Message: adb: use asocket's close function when closing. close_all_sockets was assuming that all registered local sockets used local_socket_close as their close function. However, this is not true for JDWP sockets. Bug: http://b/28347842 Change-Id: I40a1174845cd33f15f30ce70828a7081cd5a087e (cherry picked from commit 53eb31d87cb84a4212f4850bf745646e1fb12814) 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: InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( const Resource& cached_resource) { switch (cached_resource.GetType()) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 1 Example 2: Code: void LayerTreeHostImpl::SetViewportDamage(const gfx::Rect& damage_rect) { viewport_damage_rect_.Union(damage_rect); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hwahc_security_create(struct hwahc *hwahc) { int result; struct wusbhc *wusbhc = &hwahc->wusbhc; struct usb_device *usb_dev = hwahc->wa.usb_dev; struct device *dev = &usb_dev->dev; struct usb_security_descriptor *secd; struct usb_encryption_descriptor *etd; void *itr, *top; size_t itr_size, needed, bytes; u8 index; char buf[64]; /* Find the host's security descriptors in the config descr bundle */ index = (usb_dev->actconfig - usb_dev->config) / sizeof(usb_dev->config[0]); itr = usb_dev->rawdescriptors[index]; itr_size = le16_to_cpu(usb_dev->actconfig->desc.wTotalLength); top = itr + itr_size; result = __usb_get_extra_descriptor(usb_dev->rawdescriptors[index], le16_to_cpu(usb_dev->actconfig->desc.wTotalLength), USB_DT_SECURITY, (void **) &secd); if (result == -1) { dev_warn(dev, "BUG? WUSB host has no security descriptors\n"); return 0; } needed = sizeof(*secd); if (top - (void *)secd < needed) { dev_err(dev, "BUG? Not enough data to process security " "descriptor header (%zu bytes left vs %zu needed)\n", top - (void *) secd, needed); return 0; } needed = le16_to_cpu(secd->wTotalLength); if (top - (void *)secd < needed) { dev_err(dev, "BUG? Not enough data to process security " "descriptors (%zu bytes left vs %zu needed)\n", top - (void *) secd, needed); return 0; } /* Walk over the sec descriptors and store CCM1's on wusbhc */ itr = (void *) secd + sizeof(*secd); top = (void *) secd + le16_to_cpu(secd->wTotalLength); index = 0; bytes = 0; while (itr < top) { etd = itr; if (top - itr < sizeof(*etd)) { dev_err(dev, "BUG: bad host security descriptor; " "not enough data (%zu vs %zu left)\n", top - itr, sizeof(*etd)); break; } if (etd->bLength < sizeof(*etd)) { dev_err(dev, "BUG: bad host encryption descriptor; " "descriptor is too short " "(%zu vs %zu needed)\n", (size_t)etd->bLength, sizeof(*etd)); break; } itr += etd->bLength; bytes += snprintf(buf + bytes, sizeof(buf) - bytes, "%s (0x%02x) ", wusb_et_name(etd->bEncryptionType), etd->bEncryptionValue); wusbhc->ccm1_etd = etd; } dev_info(dev, "supported encryption types: %s\n", buf); if (wusbhc->ccm1_etd == NULL) { dev_err(dev, "E: host doesn't support CCM-1 crypto\n"); return 0; } /* Pretty print what we support */ return 0; } Commit Message: USB: check usb_get_extra_descriptor for proper size When reading an extra descriptor, we need to properly check the minimum and maximum size allowed, to prevent from invalid data being sent by a device. Reported-by: Hui Peng <[email protected]> Reported-by: Mathias Payer <[email protected]> Co-developed-by: Linus Torvalds <[email protected]> Signed-off-by: Hui Peng <[email protected]> Signed-off-by: Mathias Payer <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-400 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void acpi_ns_terminate(void) { acpi_status status; ACPI_FUNCTION_TRACE(ns_terminate); #ifdef ACPI_EXEC_APP { union acpi_operand_object *prev; union acpi_operand_object *next; /* Delete any module-level code blocks */ next = acpi_gbl_module_code_list; while (next) { prev = next; next = next->method.mutex; prev->method.mutex = NULL; /* Clear the Mutex (cheated) field */ acpi_ut_remove_reference(prev); } } #endif /* * Free the entire namespace -- all nodes and all objects * attached to the nodes */ acpi_ns_delete_namespace_subtree(acpi_gbl_root_node); /* Delete any objects attached to the root node */ status = acpi_ut_acquire_mutex(ACPI_MTX_NAMESPACE); if (ACPI_FAILURE(status)) { return_VOID; } acpi_ns_delete_node(acpi_gbl_root_node); (void)acpi_ut_release_mutex(ACPI_MTX_NAMESPACE); ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Namespace freed\n")); return_VOID; } Commit Message: ACPICA: Namespace: fix operand cache leak ACPICA commit a23325b2e583556eae88ed3f764e457786bf4df6 I found some ACPI operand cache leaks in ACPI early abort cases. Boot log of ACPI operand cache leak is as follows: >[ 0.174332] ACPI: Added _OSI(Module Device) >[ 0.175504] ACPI: Added _OSI(Processor Device) >[ 0.176010] ACPI: Added _OSI(3.0 _SCP Extensions) >[ 0.177032] ACPI: Added _OSI(Processor Aggregator Device) >[ 0.178284] ACPI: SCI (IRQ16705) allocation failed >[ 0.179352] ACPI Exception: AE_NOT_ACQUIRED, Unable to install System Control Interrupt handler (20160930/evevent-131) >[ 0.180008] ACPI: Unable to start the ACPI Interpreter >[ 0.181125] ACPI Error: Could not remove SCI handler (20160930/evmisc-281) >[ 0.184068] kmem_cache_destroy Acpi-Operand: Slab cache still has objects >[ 0.185358] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 4.10.0-rc3 #2 >[ 0.186820] Hardware name: innotek gmb_h virtual_box/virtual_box, BIOS virtual_box 12/01/2006 >[ 0.188000] Call Trace: >[ 0.188000] ? dump_stack+0x5c/0x7d >[ 0.188000] ? kmem_cache_destroy+0x224/0x230 >[ 0.188000] ? acpi_sleep_proc_init+0x22/0x22 >[ 0.188000] ? acpi_os_delete_cache+0xa/0xd >[ 0.188000] ? acpi_ut_delete_caches+0x3f/0x7b >[ 0.188000] ? acpi_terminate+0x5/0xf >[ 0.188000] ? acpi_init+0x288/0x32e >[ 0.188000] ? __class_create+0x4c/0x80 >[ 0.188000] ? video_setup+0x7a/0x7a >[ 0.188000] ? do_one_initcall+0x4e/0x1b0 >[ 0.188000] ? kernel_init_freeable+0x194/0x21a >[ 0.188000] ? rest_init+0x80/0x80 >[ 0.188000] ? kernel_init+0xa/0x100 >[ 0.188000] ? ret_from_fork+0x25/0x30 When early abort is occurred due to invalid ACPI information, Linux kernel terminates ACPI by calling acpi_terminate() function. The function calls acpi_ns_terminate() function to delete namespace data and ACPI operand cache (acpi_gbl_module_code_list). But the deletion code in acpi_ns_terminate() function is wrapped in ACPI_EXEC_APP definition, therefore the code is only executed when the definition exists. If the define doesn't exist, ACPI operand cache (acpi_gbl_module_code_list) is leaked, and stack dump is shown in kernel log. This causes a security threat because the old kernel (<= 4.9) shows memory locations of kernel functions in stack dump, therefore kernel ASLR can be neutralized. To fix ACPI operand leak for enhancing security, I made a patch which removes the ACPI_EXEC_APP define in acpi_ns_terminate() function for executing the deletion code unconditionally. Link: https://github.com/acpica/acpica/commit/a23325b2 Signed-off-by: Seunghun Han <[email protected]> Signed-off-by: Lv Zheng <[email protected]> Signed-off-by: Bob Moore <[email protected]> Signed-off-by: Rafael J. Wysocki <[email protected]> CWE ID: CWE-755 Target: 1 Example 2: Code: JsArgList GetNodeInfoById(const JsArgList& args, UserShare* user_share, DictionaryValue* (BaseNode::*info_getter)() const) { CHECK(info_getter); ListValue return_args; ListValue* node_summaries = new ListValue(); return_args.Append(node_summaries); ListValue* id_list = NULL; ReadTransaction trans(FROM_HERE, user_share); if (args.Get().GetList(0, &id_list)) { CHECK(id_list); for (size_t i = 0; i < id_list->GetSize(); ++i) { int64 id = GetId(*id_list, i); if (id == kInvalidId) { continue; } ReadNode node(&trans); if (node.InitByIdLookup(id) != sync_api::BaseNode::INIT_OK) { continue; } node_summaries->Append((node.*info_getter)()); } } return JsArgList(&return_args); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 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 Image *ReadMONOImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; MagickBooleanType status; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t bit, byte; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (DiscardBlobBytes(image,image->offset) == MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); /* Initialize image colormap. */ image->depth=1; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(size_t) ReadBlobByte(image); if (image_info->endian == LSBEndian) SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01) else SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00) bit++; if (bit == 8) bit=0; byte>>=1; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int airspy_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct airspy *s; int ret; u8 u8tmp, buf[BUF_SIZE]; s = kzalloc(sizeof(struct airspy), GFP_KERNEL); if (s == NULL) { dev_err(&intf->dev, "Could not allocate memory for state\n"); return -ENOMEM; } mutex_init(&s->v4l2_lock); mutex_init(&s->vb_queue_lock); spin_lock_init(&s->queued_bufs_lock); INIT_LIST_HEAD(&s->queued_bufs); s->dev = &intf->dev; s->udev = interface_to_usbdev(intf); s->f_adc = bands[0].rangelow; s->f_rf = bands_rf[0].rangelow; s->pixelformat = formats[0].pixelformat; s->buffersize = formats[0].buffersize; /* Detect device */ ret = airspy_ctrl_msg(s, CMD_BOARD_ID_READ, 0, 0, &u8tmp, 1); if (ret == 0) ret = airspy_ctrl_msg(s, CMD_VERSION_STRING_READ, 0, 0, buf, BUF_SIZE); if (ret) { dev_err(s->dev, "Could not detect board\n"); goto err_free_mem; } buf[BUF_SIZE - 1] = '\0'; dev_info(s->dev, "Board ID: %02x\n", u8tmp); dev_info(s->dev, "Firmware version: %s\n", buf); /* Init videobuf2 queue structure */ s->vb_queue.type = V4L2_BUF_TYPE_SDR_CAPTURE; s->vb_queue.io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ; s->vb_queue.drv_priv = s; s->vb_queue.buf_struct_size = sizeof(struct airspy_frame_buf); s->vb_queue.ops = &airspy_vb2_ops; s->vb_queue.mem_ops = &vb2_vmalloc_memops; s->vb_queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; ret = vb2_queue_init(&s->vb_queue); if (ret) { dev_err(s->dev, "Could not initialize vb2 queue\n"); goto err_free_mem; } /* Init video_device structure */ s->vdev = airspy_template; s->vdev.queue = &s->vb_queue; s->vdev.queue->lock = &s->vb_queue_lock; video_set_drvdata(&s->vdev, s); /* Register the v4l2_device structure */ s->v4l2_dev.release = airspy_video_release; ret = v4l2_device_register(&intf->dev, &s->v4l2_dev); if (ret) { dev_err(s->dev, "Failed to register v4l2-device (%d)\n", ret); goto err_free_mem; } /* Register controls */ v4l2_ctrl_handler_init(&s->hdl, 5); s->lna_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN_AUTO, 0, 1, 1, 0); s->lna_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_LNA_GAIN, 0, 14, 1, 8); v4l2_ctrl_auto_cluster(2, &s->lna_gain_auto, 0, false); s->mixer_gain_auto = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN_AUTO, 0, 1, 1, 0); s->mixer_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_MIXER_GAIN, 0, 15, 1, 8); v4l2_ctrl_auto_cluster(2, &s->mixer_gain_auto, 0, false); s->if_gain = v4l2_ctrl_new_std(&s->hdl, &airspy_ctrl_ops, V4L2_CID_RF_TUNER_IF_GAIN, 0, 15, 1, 0); if (s->hdl.error) { ret = s->hdl.error; dev_err(s->dev, "Could not initialize controls\n"); goto err_free_controls; } v4l2_ctrl_handler_setup(&s->hdl); s->v4l2_dev.ctrl_handler = &s->hdl; s->vdev.v4l2_dev = &s->v4l2_dev; s->vdev.lock = &s->v4l2_lock; ret = video_register_device(&s->vdev, VFL_TYPE_SDR, -1); if (ret) { dev_err(s->dev, "Failed to register as video device (%d)\n", ret); goto err_unregister_v4l2_dev; } dev_info(s->dev, "Registered as %s\n", video_device_node_name(&s->vdev)); dev_notice(s->dev, "SDR API is still slightly experimental and functionality changes may follow\n"); return 0; err_free_controls: v4l2_ctrl_handler_free(&s->hdl); err_unregister_v4l2_dev: v4l2_device_unregister(&s->v4l2_dev); err_free_mem: kfree(s); return ret; } Commit Message: media: fix airspy usb probe error path Fix a memory leak on probe error of the airspy usb device driver. The problem is triggered when more than 64 usb devices register with v4l2 of type VFL_TYPE_SDR or VFL_TYPE_SUBDEV. The memory leak is caused by the probe function of the airspy driver mishandeling errors and not freeing the corresponding control structures when an error occours registering the device to v4l2 core. A badusb device can emulate 64 of these devices, and then through continual emulated connect/disconnect of the 65th device, cause the kernel to run out of RAM and crash the kernel, thus causing a local DOS vulnerability. Fixes CVE-2016-5400 Signed-off-by: James Patrick-Evans <[email protected]> Reviewed-by: Kees Cook <[email protected]> Cc: [email protected] # 3.17+ Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static int raw_cmd_ioctl(int cmd, void __user *param) { struct floppy_raw_cmd *my_raw_cmd; int drive; int ret2; int ret; if (FDCS->rawcmd <= 1) FDCS->rawcmd = 1; for (drive = 0; drive < N_DRIVE; drive++) { if (FDC(drive) != fdc) continue; if (drive == current_drive) { if (UDRS->fd_ref > 1) { FDCS->rawcmd = 2; break; } } else if (UDRS->fd_ref) { FDCS->rawcmd = 2; break; } } if (FDCS->reset) return -EIO; ret = raw_cmd_copyin(cmd, param, &my_raw_cmd); if (ret) { raw_cmd_free(&my_raw_cmd); return ret; } raw_cmd = my_raw_cmd; cont = &raw_cmd_cont; ret = wait_til_done(floppy_start, true); debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n"); if (ret != -EINTR && FDCS->reset) ret = -EIO; DRS->track = NO_TRACK; ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd); if (!ret) ret = ret2; raw_cmd_free(&my_raw_cmd); return ret; } Commit Message: floppy: don't write kernel-only members to FDRAWCMD ioctl output Do not leak kernel-only floppy_raw_cmd structure members to userspace. This includes the linked-list pointer and the pointer to the allocated DMA space. Signed-off-by: Matthew Daley <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ec_mul_consttime(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar, const EC_POINT *point, BN_CTX *ctx) { int i, cardinality_bits, group_top, kbit, pbit, Z_is_one; EC_POINT *s = NULL; BIGNUM *k = NULL; BIGNUM *lambda = NULL; BIGNUM *cardinality = NULL; BN_CTX *new_ctx = NULL; int ret = 0; if (ctx == NULL && (ctx = new_ctx = BN_CTX_secure_new()) == NULL) return 0; BN_CTX_start(ctx); s = EC_POINT_new(group); if (s == NULL) goto err; if (point == NULL) { if (!EC_POINT_copy(s, group->generator)) goto err; } else { if (!EC_POINT_copy(s, point)) goto err; } EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME); cardinality = BN_CTX_get(ctx); lambda = BN_CTX_get(ctx); k = BN_CTX_get(ctx); if (k == NULL || !BN_mul(cardinality, group->order, group->cofactor, ctx)) goto err; /* * Group cardinalities are often on a word boundary. * So when we pad the scalar, some timing diff might * pop if it needs to be expanded due to carries. * So expand ahead of time. */ cardinality_bits = BN_num_bits(cardinality); group_top = bn_get_top(cardinality); if ((bn_wexpand(k, group_top + 1) == NULL) || (bn_wexpand(lambda, group_top + 1) == NULL)) goto err; if (!BN_copy(k, scalar)) goto err; BN_set_flags(k, BN_FLG_CONSTTIME); if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) { /*- * this is an unusual input, and we don't guarantee * constant-timeness */ if (!BN_nnmod(k, k, cardinality, ctx)) goto err; } if (!BN_add(lambda, k, cardinality)) goto err; BN_set_flags(lambda, BN_FLG_CONSTTIME); if (!BN_add(k, lambda, cardinality)) goto err; /* * lambda := scalar + cardinality * k := scalar + 2*cardinality */ kbit = BN_is_bit_set(lambda, cardinality_bits); BN_consttime_swap(kbit, k, lambda, group_top + 1); group_top = bn_get_top(group->field); if ((bn_wexpand(s->X, group_top) == NULL) || (bn_wexpand(s->Y, group_top) == NULL) || (bn_wexpand(s->Z, group_top) == NULL) || (bn_wexpand(r->X, group_top) == NULL) || (bn_wexpand(r->Y, group_top) == NULL) || (bn_wexpand(r->Z, group_top) == NULL)) goto err; /*- * Apply coordinate blinding for EC_POINT. * * The underlying EC_METHOD can optionally implement this function: * ec_point_blind_coordinates() returns 0 in case of errors or 1 on * success or if coordinate blinding is not implemented for this * group. */ if (!ec_point_blind_coordinates(group, s, ctx)) goto err; /* top bit is a 1, in a fixed pos */ if (!EC_POINT_copy(r, s)) goto err; EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME); if (!EC_POINT_dbl(group, s, s, ctx)) goto err; pbit = 0; #define EC_POINT_CSWAP(c, a, b, w, t) do { \ BN_consttime_swap(c, (a)->X, (b)->X, w); \ BN_consttime_swap(c, (a)->Y, (b)->Y, w); \ BN_consttime_swap(c, (a)->Z, (b)->Z, w); \ t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \ (a)->Z_is_one ^= (t); \ (b)->Z_is_one ^= (t); \ } while(0) /*- * The ladder step, with branches, is * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * Swapping R, S conditionally on k[i] leaves you with state * * k[i] == 0: T, U = R, S * k[i] == 1: T, U = S, R * * Then perform the ECC ops. * * U = add(T, U) * T = dbl(T) * * Which leaves you with state * * k[i] == 0: U = add(R, S), T = dbl(R) * k[i] == 1: U = add(S, R), T = dbl(S) * * Swapping T, U conditionally on k[i] leaves you with state * * k[i] == 0: R, S = T, U * k[i] == 1: R, S = U, T * * Which leaves you with state * * k[i] == 0: S = add(R, S), R = dbl(R) * k[i] == 1: R = add(S, R), S = dbl(S) * * So we get the same logic, but instead of a branch it's a * conditional swap, followed by ECC ops, then another conditional swap. * * Optimization: The end of iteration i and start of i-1 looks like * * ... * CSWAP(k[i], R, S) * ECC * CSWAP(k[i], R, S) * (next iteration) * CSWAP(k[i-1], R, S) * ECC * CSWAP(k[i-1], R, S) * ... * * So instead of two contiguous swaps, you can merge the condition * bits and do a single swap. * * k[i] k[i-1] Outcome * 0 0 No Swap * 0 1 Swap * 1 0 Swap * 1 1 No Swap * * This is XOR. pbit tracks the previous bit of k. */ for (i = cardinality_bits - 1; i >= 0; i--) { kbit = BN_is_bit_set(k, i) ^ pbit; EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one); if (!EC_POINT_add(group, s, r, s, ctx)) goto err; if (!EC_POINT_dbl(group, r, r, ctx)) goto err; /* * pbit logic merges this cswap with that of the * next iteration */ pbit ^= kbit; } /* one final cswap to move the right value into r */ EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one); #undef EC_POINT_CSWAP ret = 1; err: EC_POINT_free(s); BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } Commit Message: CWE ID: CWE-320 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 scm_fp_copy(struct cmsghdr *cmsg, struct scm_fp_list **fplp) { int *fdp = (int*)CMSG_DATA(cmsg); struct scm_fp_list *fpl = *fplp; struct file **fpp; int i, num; num = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))/sizeof(int); if (num <= 0) return 0; if (num > SCM_MAX_FD) return -EINVAL; if (!fpl) { fpl = kmalloc(sizeof(struct scm_fp_list), GFP_KERNEL); if (!fpl) return -ENOMEM; *fplp = fpl; fpl->count = 0; fpl->max = SCM_MAX_FD; } fpp = &fpl->fp[fpl->count]; if (fpl->count + num > fpl->max) return -EINVAL; /* * Verify the descriptors and increment the usage count. */ for (i=0; i< num; i++) { int fd = fdp[i]; struct file *file; if (fd < 0 || !(file = fget_raw(fd))) return -EBADF; *fpp++ = file; fpl->count++; } return num; } Commit Message: unix: correctly track in-flight fds in sending process user_struct The commit referenced in the Fixes tag incorrectly accounted the number of in-flight fds over a unix domain socket to the original opener of the file-descriptor. This allows another process to arbitrary deplete the original file-openers resource limit for the maximum of open files. Instead the sending processes and its struct cred should be credited. To do so, we add a reference counted struct user_struct pointer to the scm_fp_list and use it to account for the number of inflight unix fds. Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets") Reported-by: David Herrmann <[email protected]> Cc: David Herrmann <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: Linus Torvalds <[email protected]> Suggested-by: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399 Target: 1 Example 2: Code: static int usbhid_output_report(struct hid_device *hid, __u8 *buf, size_t count) { struct usbhid_device *usbhid = hid->driver_data; struct usb_device *dev = hid_to_usb_dev(hid); int actual_length, skipped_report_id = 0, ret; if (!usbhid->urbout) return -ENOSYS; if (buf[0] == 0x0) { /* Don't send the Report ID */ buf++; count--; skipped_report_id = 1; } ret = usb_interrupt_msg(dev, usbhid->urbout->pipe, buf, count, &actual_length, USB_CTRL_SET_TIMEOUT); /* return the number of bytes transferred */ if (ret == 0) { ret = actual_length; /* count also the report id */ if (skipped_report_id) ret++; } return ret; } Commit Message: HID: usbhid: fix out-of-bounds bug The hid descriptor identifies the length and type of subordinate descriptors for a device. If the received hid descriptor is smaller than the size of the struct hid_descriptor, it is possible to cause out-of-bounds. In addition, if bNumDescriptors of the hid descriptor have an incorrect value, this can also cause out-of-bounds while approaching hdesc->desc[n]. So check the size of hid descriptor and bNumDescriptors. BUG: KASAN: slab-out-of-bounds in usbhid_parse+0x9b1/0xa20 Read of size 1 at addr ffff88006c5f8edf by task kworker/1:2/1261 CPU: 1 PID: 1261 Comm: kworker/1:2 Not tainted 4.14.0-rc1-42251-gebb2c2437d80 #169 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 Workqueue: usb_hub_wq hub_event Call Trace: __dump_stack lib/dump_stack.c:16 dump_stack+0x292/0x395 lib/dump_stack.c:52 print_address_description+0x78/0x280 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 kasan_report+0x22f/0x340 mm/kasan/report.c:409 __asan_report_load1_noabort+0x19/0x20 mm/kasan/report.c:427 usbhid_parse+0x9b1/0xa20 drivers/hid/usbhid/hid-core.c:1004 hid_add_device+0x16b/0xb30 drivers/hid/hid-core.c:2944 usbhid_probe+0xc28/0x1100 drivers/hid/usbhid/hid-core.c:1369 usb_probe_interface+0x35d/0x8e0 drivers/usb/core/driver.c:361 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_set_configuration+0x104e/0x1870 drivers/usb/core/message.c:1932 generic_probe+0x73/0xe0 drivers/usb/core/generic.c:174 usb_probe_device+0xaf/0xe0 drivers/usb/core/driver.c:266 really_probe drivers/base/dd.c:413 driver_probe_device+0x610/0xa00 drivers/base/dd.c:557 __device_attach_driver+0x230/0x290 drivers/base/dd.c:653 bus_for_each_drv+0x161/0x210 drivers/base/bus.c:463 __device_attach+0x26e/0x3d0 drivers/base/dd.c:710 device_initial_probe+0x1f/0x30 drivers/base/dd.c:757 bus_probe_device+0x1eb/0x290 drivers/base/bus.c:523 device_add+0xd0b/0x1660 drivers/base/core.c:1835 usb_new_device+0x7b8/0x1020 drivers/usb/core/hub.c:2457 hub_port_connect drivers/usb/core/hub.c:4903 hub_port_connect_change drivers/usb/core/hub.c:5009 port_event drivers/usb/core/hub.c:5115 hub_event+0x194d/0x3740 drivers/usb/core/hub.c:5195 process_one_work+0xc7f/0x1db0 kernel/workqueue.c:2119 worker_thread+0x221/0x1850 kernel/workqueue.c:2253 kthread+0x3a1/0x470 kernel/kthread.c:231 ret_from_fork+0x2a/0x40 arch/x86/entry/entry_64.S:431 Cc: [email protected] Reported-by: Andrey Konovalov <[email protected]> Signed-off-by: Jaejoong Kim <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Acked-by: Alan Stern <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp) { start_thread_common(regs, new_ip, new_sp, test_thread_flag(TIF_X32) ? __USER_CS : __USER32_CS, __USER_DS, __USER_DS); } Commit Message: x86_64, switch_to(): Load TLS descriptors before switching DS and ES Otherwise, if buggy user code points DS or ES into the TLS array, they would be corrupted after a context switch. This also significantly improves the comments and documents some gotchas in the code. Before this patch, the both tests below failed. With this patch, the es test passes, although the gsbase test still fails. ----- begin es test ----- /* * Copyright (c) 2014 Andy Lutomirski * GPL v2 */ static unsigned short GDT3(int idx) { return (idx << 3) | 3; } static int create_tls(int idx, unsigned int base) { struct user_desc desc = { .entry_number = idx, .base_addr = base, .limit = 0xfffff, .seg_32bit = 1, .contents = 0, /* Data, grow-up */ .read_exec_only = 0, .limit_in_pages = 1, .seg_not_present = 0, .useable = 0, }; if (syscall(SYS_set_thread_area, &desc) != 0) err(1, "set_thread_area"); return desc.entry_number; } int main() { int idx = create_tls(-1, 0); printf("Allocated GDT index %d\n", idx); unsigned short orig_es; asm volatile ("mov %%es,%0" : "=rm" (orig_es)); int errors = 0; int total = 1000; for (int i = 0; i < total; i++) { asm volatile ("mov %0,%%es" : : "rm" (GDT3(idx))); usleep(100); unsigned short es; asm volatile ("mov %%es,%0" : "=rm" (es)); asm volatile ("mov %0,%%es" : : "rm" (orig_es)); if (es != GDT3(idx)) { if (errors == 0) printf("[FAIL]\tES changed from 0x%hx to 0x%hx\n", GDT3(idx), es); errors++; } } if (errors) { printf("[FAIL]\tES was corrupted %d/%d times\n", errors, total); return 1; } else { printf("[OK]\tES was preserved\n"); return 0; } } ----- end es test ----- ----- begin gsbase test ----- /* * gsbase.c, a gsbase test * Copyright (c) 2014 Andy Lutomirski * GPL v2 */ static unsigned char *testptr, *testptr2; static unsigned char read_gs_testvals(void) { unsigned char ret; asm volatile ("movb %%gs:%1, %0" : "=r" (ret) : "m" (*testptr)); return ret; } int main() { int errors = 0; testptr = mmap((void *)0x200000000UL, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if (testptr == MAP_FAILED) err(1, "mmap"); testptr2 = mmap((void *)0x300000000UL, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if (testptr2 == MAP_FAILED) err(1, "mmap"); *testptr = 0; *testptr2 = 1; if (syscall(SYS_arch_prctl, ARCH_SET_GS, (unsigned long)testptr2 - (unsigned long)testptr) != 0) err(1, "ARCH_SET_GS"); usleep(100); if (read_gs_testvals() == 1) { printf("[OK]\tARCH_SET_GS worked\n"); } else { printf("[FAIL]\tARCH_SET_GS failed\n"); errors++; } asm volatile ("mov %0,%%gs" : : "r" (0)); if (read_gs_testvals() == 0) { printf("[OK]\tWriting 0 to gs worked\n"); } else { printf("[FAIL]\tWriting 0 to gs failed\n"); errors++; } usleep(100); if (read_gs_testvals() == 0) { printf("[OK]\tgsbase is still zero\n"); } else { printf("[FAIL]\tgsbase was corrupted\n"); errors++; } return errors == 0 ? 0 : 1; } ----- end gsbase test ----- Signed-off-by: Andy Lutomirski <[email protected]> Cc: <[email protected]> Cc: Andi Kleen <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/509d27c9fec78217691c3dad91cec87e1006b34a.1418075657.git.luto@amacapital.net Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-200 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void check_pointer_type_change(Notifier *notifier, void *data) { VncState *vs = container_of(notifier, VncState, mouse_mode_notifier); int absolute = qemu_input_is_absolute(); if (vnc_has_feature(vs, VNC_FEATURE_POINTER_TYPE_CHANGE) && vs->absolute != absolute) { vnc_write_u8(vs, 0); vnc_write_u16(vs, 1); vnc_framebuffer_update(vs, absolute, 0, surface_width(vs->vd->ds), surface_height(vs->vd->ds), VNC_ENCODING_POINTER_TYPE_CHANGE); vnc_unlock_output(vs); vnc_flush(vs); vnc_unlock_output(vs); vnc_flush(vs); } vs->absolute = absolute; } Commit Message: CWE ID: CWE-125 Target: 1 Example 2: Code: __xmlTreeIndentString(void) { if (IS_MAIN_THREAD) return (&xmlTreeIndentString); else return (&xmlGetGlobalState()->xmlTreeIndentString); } Commit Message: Attempt to address libxml crash. BUG=129930 Review URL: https://chromiumcodereview.appspot.com/10458051 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@142822 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: status_t SoundTriggerHwService::Module::loadSoundModel(const sp<IMemory>& modelMemory, sound_model_handle_t *handle) { ALOGV("loadSoundModel() handle"); if (!captureHotwordAllowed()) { return PERMISSION_DENIED; } if (modelMemory == 0 || modelMemory->pointer() == NULL) { ALOGE("loadSoundModel() modelMemory is 0 or has NULL pointer()"); return BAD_VALUE; } struct sound_trigger_sound_model *sound_model = (struct sound_trigger_sound_model *)modelMemory->pointer(); AutoMutex lock(mLock); if (mModels.size() >= mDescriptor.properties.max_sound_models) { ALOGW("loadSoundModel(): Not loading, max number of models (%d) would be exceeded", mDescriptor.properties.max_sound_models); return INVALID_OPERATION; } status_t status = mHwDevice->load_sound_model(mHwDevice, sound_model, SoundTriggerHwService::soundModelCallback, this, handle); if (status != NO_ERROR) { return status; } audio_session_t session; audio_io_handle_t ioHandle; audio_devices_t device; status = AudioSystem::acquireSoundTriggerSession(&session, &ioHandle, &device); if (status != NO_ERROR) { return status; } sp<Model> model = new Model(*handle, session, ioHandle, device, sound_model->type); mModels.replaceValueFor(*handle, model); return status; } Commit Message: soundtrigger: add size check on sound model and recogntion data Bug: 30148546 Change-Id: I082f535a853c96571887eeea37c6d41ecee7d8c0 (cherry picked from commit bb00d8f139ff51336ab3c810d35685003949bcf8) (cherry picked from commit ef0c91518446e65533ca8bab6726a845f27c73fd) 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 PaymentRequest::NoUpdatedPaymentDetails() { spec_->RecomputeSpecForDetails(); } Commit Message: [Payment Request][Desktop] Prevent use after free. Before this patch, a compromised renderer on desktop could make IPC methods into Payment Request in an unexpected ordering and cause use after free in the browser. This patch will disconnect the IPC pipes if: - Init() is called more than once. - Any other method is called before Init(). - Show() is called more than once. - Retry(), UpdateWith(), NoupdatedPaymentDetails(), Abort(), or Complete() are called before Show(). This patch re-orders the IPC methods in payment_request.cc to match the order in payment_request.h, which eases verifying correctness of their error handling. This patch prints more errors to the developer console, if available, to improve debuggability by web developers, who rarely check where LOG prints. After this patch, unexpected ordering of calls into the Payment Request IPC from the renderer to the browser on desktop will print an error in the developer console and disconnect the IPC pipes. The binary might increase slightly in size because more logs are included in the release version instead of being stripped at compile time. Bug: 912947 Change-Id: Iac2131181c64cd49b4e5ec99f4b4a8ae5d8df57a Reviewed-on: https://chromium-review.googlesource.com/c/1370198 Reviewed-by: anthonyvd <[email protected]> Commit-Queue: Rouslan Solomakhin <[email protected]> Cr-Commit-Position: refs/heads/master@{#616822} CWE ID: CWE-189 Target: 1 Example 2: Code: megasas_dump_pending_frames(struct megasas_instance *instance) { struct megasas_cmd *cmd; int i,n; union megasas_sgl *mfi_sgl; struct megasas_io_frame *ldio; struct megasas_pthru_frame *pthru; u32 sgcount; u16 max_cmd = instance->max_fw_cmds; dev_err(&instance->pdev->dev, "[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no); dev_err(&instance->pdev->dev, "[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding)); if (IS_DMA64) dev_err(&instance->pdev->dev, "[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no); else dev_err(&instance->pdev->dev, "[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no); dev_err(&instance->pdev->dev, "[%d]: Pending OS cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (!cmd->scmd) continue; dev_err(&instance->pdev->dev, "[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr); if (megasas_cmd_type(cmd->scmd) == READ_WRITE_LDIO) { ldio = (struct megasas_io_frame *)cmd->frame; mfi_sgl = &ldio->sgl; sgcount = ldio->sge_count; dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x," " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n", instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id, le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi), le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount); } else { pthru = (struct megasas_pthru_frame *) cmd->frame; mfi_sgl = &pthru->sgl; sgcount = pthru->sge_count; dev_err(&instance->pdev->dev, "[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, " "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n", instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id, pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len), le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount); } if (megasas_dbg_lvl & MEGASAS_DBG_LVL) { for (n = 0; n < sgcount; n++) { if (IS_DMA64) dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%llx\n", le32_to_cpu(mfi_sgl->sge64[n].length), le64_to_cpu(mfi_sgl->sge64[n].phys_addr)); else dev_err(&instance->pdev->dev, "sgl len : 0x%x, sgl addr : 0x%x\n", le32_to_cpu(mfi_sgl->sge32[n].length), le32_to_cpu(mfi_sgl->sge32[n].phys_addr)); } } } /*for max_cmd*/ dev_err(&instance->pdev->dev, "[%d]: Pending Internal cmds in FW : \n",instance->host->host_no); for (i = 0; i < max_cmd; i++) { cmd = instance->cmd_list[i]; if (cmd->sync_cmd == 1) dev_err(&instance->pdev->dev, "0x%08lx : ", (unsigned long)cmd->frame_phys_addr); } dev_err(&instance->pdev->dev, "[%d]: Dumping Done\n\n",instance->host->host_no); } Commit Message: scsi: megaraid_sas: return error when create DMA pool failed when create DMA pool for cmd frames failed, we should return -ENOMEM, instead of 0. In some case in: megasas_init_adapter_fusion() -->megasas_alloc_cmds() -->megasas_create_frame_pool create DMA pool failed, --> megasas_free_cmds() [1] -->megasas_alloc_cmds_fusion() failed, then goto fail_alloc_cmds. -->megasas_free_cmds() [2] we will call megasas_free_cmds twice, [1] will kfree cmd_list, [2] will use cmd_list.it will cause a problem: Unable to handle kernel NULL pointer dereference at virtual address 00000000 pgd = ffffffc000f70000 [00000000] *pgd=0000001fbf893003, *pud=0000001fbf893003, *pmd=0000001fbf894003, *pte=006000006d000707 Internal error: Oops: 96000005 [#1] SMP Modules linked in: CPU: 18 PID: 1 Comm: swapper/0 Not tainted task: ffffffdfb9290000 ti: ffffffdfb923c000 task.ti: ffffffdfb923c000 PC is at megasas_free_cmds+0x30/0x70 LR is at megasas_free_cmds+0x24/0x70 ... Call trace: [<ffffffc0005b779c>] megasas_free_cmds+0x30/0x70 [<ffffffc0005bca74>] megasas_init_adapter_fusion+0x2f4/0x4d8 [<ffffffc0005b926c>] megasas_init_fw+0x2dc/0x760 [<ffffffc0005b9ab0>] megasas_probe_one+0x3c0/0xcd8 [<ffffffc0004a5abc>] local_pci_probe+0x4c/0xb4 [<ffffffc0004a5c40>] pci_device_probe+0x11c/0x14c [<ffffffc00053a5e4>] driver_probe_device+0x1ec/0x430 [<ffffffc00053a92c>] __driver_attach+0xa8/0xb0 [<ffffffc000538178>] bus_for_each_dev+0x74/0xc8 [<ffffffc000539e88>] driver_attach+0x28/0x34 [<ffffffc000539a18>] bus_add_driver+0x16c/0x248 [<ffffffc00053b234>] driver_register+0x6c/0x138 [<ffffffc0004a5350>] __pci_register_driver+0x5c/0x6c [<ffffffc000ce3868>] megasas_init+0xc0/0x1a8 [<ffffffc000082a58>] do_one_initcall+0xe8/0x1ec [<ffffffc000ca7be8>] kernel_init_freeable+0x1c8/0x284 [<ffffffc0008d90b8>] kernel_init+0x1c/0xe4 Signed-off-by: Jason Yan <[email protected]> Acked-by: Sumit Saxena <[email protected]> Signed-off-by: Martin K. Petersen <[email protected]> CWE ID: CWE-476 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: have_sampled_guard_with_id(guard_selection_t *gs, const uint8_t *rsa_id) { return get_sampled_guard_with_id(gs, rsa_id) != NULL; } Commit Message: Consider the exit family when applying guard restrictions. When the new path selection logic went into place, I accidentally dropped the code that considered the _family_ of the exit node when deciding if the guard was usable, and we didn't catch that during code review. This patch makes the guard_restriction_t code consider the exit family as well, and adds some (hopefully redundant) checks for the case where we lack a node_t for a guard but we have a bridge_info_t for it. Fixes bug 22753; bugfix on 0.3.0.1-alpha. Tracked as TROVE-2016-006 and CVE-2017-0377. 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 usage(char *progname) { printf("Usage:\n"); printf("%s <input_yuv> <width>x<height> <target_width>x<target_height> ", progname); printf("<output_yuv> [<frames>]\n"); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void usage(void) { printf("\nusage:\n"); printf("\ttcmu-runner [options]\n"); printf("\noptions:\n"); printf("\t-h, --help: print this message and exit\n"); printf("\t-V, --version: print version and exit\n"); printf("\t-d, --debug: enable debug messages\n"); printf("\t--handler-path: set path to search for handler modules\n"); printf("\t\tdefault is %s\n", DEFAULT_HANDLER_PATH); printf("\t-l, --tcmu-log-dir: tcmu log dir\n"); printf("\t\tdefault is %s\n", TCMU_LOG_DIR_DEFAULT); printf("\n"); } Commit Message: fixed local DoS when UnregisterHandler was called for a not existing handler Any user with DBUS access could cause a SEGFAULT in tcmu-runner by running something like this: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123 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: IMPEG2D_ERROR_CODES_T impeg2d_dec_d_slice(dec_state_t *ps_dec) { UWORD32 i; yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; stream_t *ps_stream = &ps_dec->s_bit_stream; UWORD8 *pu1_vld_buf; WORD16 i2_dc_diff; UWORD32 u4_frame_width = ps_dec->u2_frame_width; UWORD32 u4_frm_offset = 0; if(ps_dec->u2_picture_structure != FRAME_PICTURE) { u4_frame_width <<= 1; if(ps_dec->u2_picture_structure == BOTTOM_FIELD) { u4_frm_offset = ps_dec->u2_frame_width; } } do { UWORD32 u4_x_offset, u4_y_offset; UWORD32 u4_blk_pos; WORD16 i2_dc_val; UWORD32 u4_dst_x_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); UWORD32 u4_dst_y_offset = (ps_dec->u2_mb_y << 4) * u4_frame_width; UWORD8 *pu1_vld_buf8 = ps_cur_frm_buf->pu1_y + u4_dst_x_offset + u4_dst_y_offset; UWORD32 u4_dst_wd = u4_frame_width; /*------------------------------------------------------------------*/ /* Discard the Macroblock stuffing in case of MPEG-1 stream */ /*------------------------------------------------------------------*/ while(impeg2d_bit_stream_nxt(ps_stream,MB_STUFFING_CODE_LEN) == MB_STUFFING_CODE) impeg2d_bit_stream_flush(ps_stream,MB_STUFFING_CODE_LEN); /*------------------------------------------------------------------*/ /* Flush 2 bits from bitstream [MB_Type and MacroBlockAddrIncrement]*/ /*------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,1); if(impeg2d_bit_stream_get(ps_stream, 1) != 0x01) { /* Ignore and continue decoding. */ } /* Process LUMA blocks of the MB */ for(i = 0; i < NUM_LUMA_BLKS; ++i) { u4_x_offset = gai2_impeg2_blk_x_off[i]; u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; u4_blk_pos = (u4_y_offset * u4_dst_wd) + u4_x_offset; pu1_vld_buf = pu1_vld_buf8 + u4_blk_pos; i2_dc_diff = impeg2d_get_luma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[Y_LUMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[Y_LUMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); } /* Process U block of the MB */ u4_dst_x_offset >>= 1; u4_dst_y_offset >>= 2; u4_dst_wd >>= 1; pu1_vld_buf = ps_cur_frm_buf->pu1_u + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[U_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[U_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Process V block of the MB */ pu1_vld_buf = ps_cur_frm_buf->pu1_v + u4_dst_x_offset + u4_dst_y_offset; i2_dc_diff = impeg2d_get_chroma_dc_diff(ps_stream); i2_dc_val = ps_dec->u2_def_dc_pred[V_CHROMA] + i2_dc_diff; ps_dec->u2_def_dc_pred[V_CHROMA] = i2_dc_val; i2_dc_val = CLIP_U8(i2_dc_val); ps_dec->pf_memset_8bit_8x8_block(pu1_vld_buf, i2_dc_val, u4_dst_wd); /* Common MB processing Steps */ ps_dec->u2_num_mbs_left--; ps_dec->u2_mb_x++; if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) { return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; } else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) { ps_dec->u2_mb_x = 0; ps_dec->u2_mb_y++; } /* Flush end of macro block */ impeg2d_bit_stream_flush(ps_stream,1); } while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }/* End of impeg2d_dec_d_slice() */ Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254 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 jas_matrix_asl(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = jas_seqent_asl(*data, n); } } } } 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: void WebGLRenderingContextBase::lineWidth(GLfloat width) { if (isContextLost()) return; ContextGL()->LineWidth(width); } 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: my_object_unstringify (MyObject *obj, const char *str, GValue *value, GError **error) { if (str[0] == '\0' || !g_ascii_isdigit (str[0])) { g_value_init (value, G_TYPE_STRING); g_value_set_string (value, str); } else { g_value_init (value, G_TYPE_INT); g_value_set_int (value, (int) g_ascii_strtoull (str, NULL, 10)); } return TRUE; } Commit Message: CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void CuePoint::Load(IMkvReader* pReader) { if (m_timecode >= 0) //already loaded return; assert(m_track_positions == NULL); assert(m_track_positions_count == 0); long long pos_ = -m_timecode; const long long element_start = pos_; long long stop; { long len; const long long id = ReadUInt(pReader, pos_, len); assert(id == 0x3B); //CuePoint ID if (id != 0x3B) return; pos_ += len; //consume ID const long long size = ReadUInt(pReader, pos_, len); assert(size >= 0); pos_ += len; //consume Size field stop = pos_ + size; } const long long element_size = stop - element_start; long long pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x33) //CueTime ID m_timecode = UnserializeUInt(pReader, pos, size); else if (id == 0x37) //CueTrackPosition(s) ID ++m_track_positions_count; pos += size; //consume payload assert(pos <= stop); } assert(m_timecode >= 0); assert(m_track_positions_count > 0); m_track_positions = new TrackPosition[m_track_positions_count]; TrackPosition* p = m_track_positions; pos = pos_; while (pos < stop) { long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x37) //CueTrackPosition(s) ID { TrackPosition& tp = *p++; tp.Parse(pReader, pos, size); } pos += size; //consume payload assert(pos <= stop); } assert(size_t(p - m_track_positions) == m_track_positions_count); m_element_start = element_start; m_element_size = element_size; } Commit Message: 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: MockAppCacheStorage* mock_storage() { return static_cast<MockAppCacheStorage*>(service_->storage()); } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 Tab::OnPaint(gfx::Canvas* canvas) { SkPath clip; if (!controller_->ShouldPaintTab(this, canvas->image_scale(), &clip)) return; tab_style()->PaintTab(canvas, clip); } Commit Message: Paint tab groups with the group color. * The background of TabGroupHeader now uses the group color. * The backgrounds of tabs in the group are tinted with the group color. This treatment, along with the colors chosen, are intended to be a placeholder. Bug: 905491 Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504 Commit-Queue: Bret Sepulveda <[email protected]> Reviewed-by: Taylor Bergquist <[email protected]> Cr-Commit-Position: refs/heads/master@{#660498} CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: content::WebUIDataSource* CreateOobeUIDataSource( const base::DictionaryValue& localized_strings, const std::string& display_type) { content::WebUIDataSource* source = content::WebUIDataSource::Create(chrome::kChromeUIOobeHost); source->AddLocalizedStrings(localized_strings); source->SetJsonPath(kStringsJSPath); if (display_type == OobeUI::kOobeDisplay) { source->SetDefaultResource(IDR_OOBE_HTML); source->AddResourcePath(kOobeJSPath, IDR_OOBE_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_OOBE_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_OOBE_JS); } else { source->SetDefaultResource(IDR_LOGIN_HTML); source->AddResourcePath(kLoginJSPath, IDR_LOGIN_JS); source->AddResourcePath(kCustomElementsHTMLPath, IDR_CUSTOM_ELEMENTS_LOGIN_HTML); source->AddResourcePath(kCustomElementsJSPath, IDR_CUSTOM_ELEMENTS_LOGIN_JS); } source->AddResourcePath(kPolymerConfigJSPath, IDR_POLYMER_CONFIG_JS); source->AddResourcePath(kKeyboardUtilsJSPath, IDR_KEYBOARD_UTILS_JS); source->OverrideContentSecurityPolicyFrameSrc( base::StringPrintf( "frame-src chrome://terms/ %s/;", extensions::kGaiaAuthExtensionOrigin)); source->OverrideContentSecurityPolicyObjectSrc("object-src *;"); bool is_webview_signin_enabled = StartupUtils::IsWebviewSigninEnabled(); source->AddResourcePath("gaia_auth_host.js", is_webview_signin_enabled ? IDR_GAIA_AUTH_AUTHENTICATOR_JS : IDR_GAIA_AUTH_HOST_JS); source->AddResourcePath(kEnrollmentHTMLPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_HTML : IDR_OOBE_ENROLLMENT_HTML); source->AddResourcePath(kEnrollmentCSSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_CSS : IDR_OOBE_ENROLLMENT_CSS); source->AddResourcePath(kEnrollmentJSPath, is_webview_signin_enabled ? IDR_OOBE_ENROLLMENT_WEBVIEW_JS : IDR_OOBE_ENROLLMENT_JS); if (display_type == OobeUI::kOobeDisplay) { source->AddResourcePath("Roboto-Thin.ttf", IDR_FONT_ROBOTO_THIN); source->AddResourcePath("Roboto-Light.ttf", IDR_FONT_ROBOTO_LIGHT); source->AddResourcePath("Roboto-Regular.ttf", IDR_FONT_ROBOTO_REGULAR); source->AddResourcePath("Roboto-Medium.ttf", IDR_FONT_ROBOTO_MEDIUM); source->AddResourcePath("Roboto-Bold.ttf", IDR_FONT_ROBOTO_BOLD); } return source; } Commit Message: One polymer_config.js to rule them all. [email protected],[email protected],[email protected] BUG=425626 Review URL: https://codereview.chromium.org/1224783005 Cr-Commit-Position: refs/heads/master@{#337882} CWE ID: CWE-399 Target: 1 Example 2: Code: bool Smb4KGlobal::updateMountedShare(Smb4KShare* share) { Q_ASSERT(share); bool updated = false; if (share) { Smb4KShare *mountedShare = findShareByPath(share->path()); if (mountedShare) { mountedShare->setMountData(share); updated = true; } else { } } else { } return updated; } 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 void cmd_parse_status(struct ImapData *idata, char *s) { char *value = NULL; struct Buffy *inc = NULL; struct ImapMbox mx; struct ImapStatus *status = NULL; unsigned int olduv, oldun; unsigned int litlen; short new = 0; short new_msg_count = 0; char *mailbox = imap_next_word(s); /* We need a real tokenizer. */ if (imap_get_literal_count(mailbox, &litlen) == 0) { if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) { idata->status = IMAP_FATAL; return; } mailbox = idata->buf; s = mailbox + litlen; *s = '\0'; s++; SKIPWS(s); } else { s = imap_next_word(mailbox); *(s - 1) = '\0'; imap_unmunge_mbox_name(idata, mailbox); } status = imap_mboxcache_get(idata, mailbox, 1); olduv = status->uidvalidity; oldun = status->uidnext; if (*s++ != '(') { mutt_debug(1, "Error parsing STATUS\n"); return; } while (*s && *s != ')') { value = imap_next_word(s); errno = 0; const unsigned long ulcount = strtoul(value, &value, 10); if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) { mutt_debug(1, "Error parsing STATUS number\n"); return; } const unsigned int count = (unsigned int) ulcount; if (mutt_str_strncmp("MESSAGES", s, 8) == 0) { status->messages = count; new_msg_count = 1; } else if (mutt_str_strncmp("RECENT", s, 6) == 0) status->recent = count; else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0) status->uidnext = count; else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0) status->uidvalidity = count; else if (mutt_str_strncmp("UNSEEN", s, 6) == 0) status->unseen = count; s = value; if (*s && *s != ')') s = imap_next_word(s); } mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n", status->name, status->uidvalidity, status->uidnext, status->messages, status->recent, status->unseen); /* caller is prepared to handle the result herself */ if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) { memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); return; } mutt_debug(3, "Running default STATUS handler\n"); /* should perhaps move this code back to imap_buffy_check */ for (inc = Incoming; inc; inc = inc->next) { if (inc->magic != MUTT_IMAP) continue; if (imap_parse_path(inc->path, &mx) < 0) { mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path); continue; } if (imap_account_match(&idata->conn->account, &mx.account)) { if (mx.mbox) { value = mutt_str_strdup(mx.mbox); imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); FREE(&mx.mbox); } else value = mutt_str_strdup("INBOX"); if (value && (imap_mxcmp(mailbox, value) == 0)) { mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox, olduv, oldun, status->unseen); if (MailCheckRecent) { if (olduv && olduv == status->uidvalidity) { if (oldun < status->uidnext) new = (status->unseen > 0); } else if (!olduv && !oldun) { /* first check per session, use recent. might need a flag for this. */ new = (status->recent > 0); } else new = (status->unseen > 0); } else new = (status->unseen > 0); #ifdef USE_SIDEBAR if ((inc->new != new) || (inc->msg_count != status->messages) || (inc->msg_unread != status->unseen)) { mutt_menu_set_current_redraw(REDRAW_SIDEBAR); } #endif inc->new = new; if (new_msg_count) inc->msg_count = status->messages; inc->msg_unread = status->unseen; if (inc->new) { /* force back to keep detecting new mail until the mailbox is opened */ status->uidnext = oldun; } FREE(&value); return; } FREE(&value); } FREE(&mx.mbox); } } Commit Message: Ensure litlen isn't larger than our mailbox 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 adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_reg_state *regs = cur_regs(env), *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u8 opcode = BPF_OP(insn->code); u32 dst = insn->dst_reg; dst_reg = &regs[dst]; if (WARN_ON_ONCE(known && (smin_val != smax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad sbounds\n"); return -EINVAL; } if (WARN_ON_ONCE(known && (umin_val != umax_val))) { print_verifier_state(env, env->cur_state); verbose(env, "verifier internal error: known but bad ubounds\n"); return -EINVAL; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ if (!env->allow_ptr_leaks) verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n", dst); return -EACCES; } if (ptr_reg->type == CONST_PTR_TO_MAP) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n", dst); return -EACCES; } if (ptr_reg->type == PTR_TO_PACKET_END) { if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n", dst); return -EACCES; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->range = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ if (!env->allow_ptr_leaks) verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { if (!env->allow_ptr_leaks) verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->range = ptr_reg->range; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->range = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit for now. * (However, in principle we could allow some cases, e.g. * ptr &= ~3 which would reduce min_value by 3.) */ if (!env->allow_ptr_leaks) verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ if (!env->allow_ptr_leaks) verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); return 0; } Commit Message: bpf: fix integer overflows There were various issues related to the limited size of integers used in the verifier: - `off + size` overflow in __check_map_access() - `off + reg->off` overflow in check_mem_access() - `off + reg->var_off.value` overflow or 32-bit truncation of `reg->var_off.value` in check_mem_access() - 32-bit truncation in check_stack_boundary() Make sure that any integer math cannot overflow by not allowing pointer math with large values. Also reduce the scope of "scalar op scalar" tracking. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-190 Target: 1 Example 2: Code: void CWebServer::GetJSonDevices( Json::Value &root, const std::string &rused, const std::string &rfilter, const std::string &order, const std::string &rowid, const std::string &planID, const std::string &floorID, const bool bDisplayHidden, const bool bDisplayDisabled, const bool bFetchFavorites, const time_t LastUpdate, const std::string &username, const std::string &hardwareid) { std::vector<std::vector<std::string> > result; time_t now = mytime(NULL); struct tm tm1; localtime_r(&now, &tm1); struct tm tLastUpdate; localtime_r(&now, &tLastUpdate); const time_t iLastUpdate = LastUpdate - 1; int SensorTimeOut = 60; m_sql.GetPreferencesVar("SensorTimeout", SensorTimeOut); std::map<int, _tHardwareListInt> _hardwareNames; result = m_sql.safe_query("SELECT ID, Name, Enabled, Type, Mode1, Mode2 FROM Hardware"); if (!result.empty()) { int ii = 0; for (const auto & itt : result) { std::vector<std::string> sd = itt; _tHardwareListInt tlist; int ID = atoi(sd[0].c_str()); tlist.Name = sd[1]; tlist.Enabled = (atoi(sd[2].c_str()) != 0); tlist.HardwareTypeVal = atoi(sd[3].c_str()); #ifndef ENABLE_PYTHON tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal); #else if (tlist.HardwareTypeVal != HTYPE_PythonPlugin) { tlist.HardwareType = Hardware_Type_Desc(tlist.HardwareTypeVal); } else { tlist.HardwareType = PluginHardwareDesc(ID); } #endif tlist.Mode1 = sd[4]; tlist.Mode2 = sd[5]; _hardwareNames[ID] = tlist; } } root["ActTime"] = static_cast<int>(now); char szTmp[300]; if (!m_mainworker.m_LastSunriseSet.empty()) { std::vector<std::string> strarray; StringSplit(m_mainworker.m_LastSunriseSet, ";", strarray); if (strarray.size() == 10) { strftime(szTmp, 80, "%Y-%m-%d %X", &tm1); root["ServerTime"] = szTmp; root["Sunrise"] = strarray[0]; root["Sunset"] = strarray[1]; root["SunAtSouth"] = strarray[2]; root["CivTwilightStart"] = strarray[3]; root["CivTwilightEnd"] = strarray[4]; root["NautTwilightStart"] = strarray[5]; root["NautTwilightEnd"] = strarray[6]; root["AstrTwilightStart"] = strarray[7]; root["AstrTwilightEnd"] = strarray[8]; root["DayLength"] = strarray[9]; } } char szOrderBy[50]; std::string szQuery; bool isAlpha = true; const std::string orderBy = order.c_str(); for (size_t i = 0; i < orderBy.size(); i++) { if (!isalpha(orderBy[i])) { isAlpha = false; } } if (order.empty() || (!isAlpha)) { strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC"); } else { sprintf(szOrderBy, "A.[Order],A.%%s ASC"); } unsigned char tempsign = m_sql.m_tempsign[0]; bool bHaveUser = false; int iUser = -1; unsigned int totUserDevices = 0; bool bShowScenes = true; bHaveUser = (username != ""); if (bHaveUser) { iUser = FindUser(username.c_str()); if (iUser != -1) { _eUserRights urights = m_users[iUser].userrights; if (urights != URIGHTS_ADMIN) { result = m_sql.safe_query("SELECT DeviceRowID FROM SharedDevices WHERE (SharedUserID == %lu)", m_users[iUser].ID); totUserDevices = (unsigned int)result.size(); bShowScenes = (m_users[iUser].ActiveTabs&(1 << 1)) != 0; } } } std::set<std::string> _HiddenDevices; bool bAllowDeviceToBeHidden = false; int ii = 0; if (rfilter == "all") { if ( (bShowScenes) && ((rused == "all") || (rused == "true")) ) { if (rowid != "") result = m_sql.safe_query( "SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType," " A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description" " FROM Scenes as A" " LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)" " WHERE (A.ID=='%q')", rowid.c_str()); else if ((planID != "") && (planID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType," " A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description" " FROM Scenes as A, DeviceToPlansMap as B WHERE (B.PlanID=='%q')" " AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==1) ORDER BY B.[Order]", planID.c_str()); else if ((floorID != "") && (floorID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType," " A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description" " FROM Scenes as A, DeviceToPlansMap as B, Plans as C" " WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID) AND (B.DeviceRowID==a.ID)" " AND (B.DevSceneType==1) ORDER BY B.[Order]", floorID.c_str()); else { szQuery = ( "SELECT A.ID, A.Name, A.nValue, A.LastUpdate, A.Favorite, A.SceneType," " A.Protected, B.XOffset, B.YOffset, B.PlanID, A.Description" " FROM Scenes as A" " LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==1)" " ORDER BY "); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), order.c_str()); } if (!result.empty()) { for (const auto & itt : result) { std::vector<std::string> sd = itt; unsigned char favorite = atoi(sd[4].c_str()); if ((bFetchFavorites) && (!favorite)) continue; std::string sLastUpdate = sd[3]; if (iLastUpdate != 0) { time_t cLastUpdate; ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst); if (cLastUpdate <= iLastUpdate) continue; } int nValue = atoi(sd[2].c_str()); unsigned char scenetype = atoi(sd[5].c_str()); int iProtected = atoi(sd[6].c_str()); std::string sSceneName = sd[1]; if (!bDisplayHidden && sSceneName[0] == '$') { continue; } if (scenetype == 0) { root["result"][ii]["Type"] = "Scene"; root["result"][ii]["TypeImg"] = "scene"; } else { root["result"][ii]["Type"] = "Group"; root["result"][ii]["TypeImg"] = "group"; } std::string thisIdx = sd[0]; if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) { std::string typeOfThisOne = root["result"][ii]["Type"].asString(); if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) { root["result"][ii - 1]["PlanIDs"].append(atoi(sd[9].c_str())); continue; } } root["result"][ii]["idx"] = sd[0]; root["result"][ii]["Name"] = sSceneName; root["result"][ii]["Description"] = sd[10]; root["result"][ii]["Favorite"] = favorite; root["result"][ii]["Protected"] = (iProtected != 0); root["result"][ii]["LastUpdate"] = sLastUpdate; root["result"][ii]["PlanID"] = sd[9].c_str(); Json::Value jsonArray; jsonArray.append(atoi(sd[9].c_str())); root["result"][ii]["PlanIDs"] = jsonArray; if (nValue == 0) root["result"][ii]["Status"] = "Off"; else if (nValue == 1) root["result"][ii]["Status"] = "On"; else root["result"][ii]["Status"] = "Mixed"; root["result"][ii]["Data"] = root["result"][ii]["Status"]; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(1, sd[0]); root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root["result"][ii]["CameraIdx"] = scidx.str(); } root["result"][ii]["XOffset"] = atoi(sd[7].c_str()); root["result"][ii]["YOffset"] = atoi(sd[8].c_str()); ii++; } } } } char szData[250]; if (totUserDevices == 0) { if (rowid != "") { result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used, A.Type, A.SubType," " A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue," " A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID," " A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2," " A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description," " A.Options, A.Color " "FROM DeviceStatus A LEFT OUTER JOIN DeviceToPlansMap as B ON (B.DeviceRowID==a.ID) " "WHERE (A.ID=='%q')", rowid.c_str()); } else if ((planID != "") && (planID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, B.XOffset, B.YOffset," " B.PlanID, A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, DeviceToPlansMap as B " "WHERE (B.PlanID=='%q') AND (B.DeviceRowID==a.ID)" " AND (B.DevSceneType==0) ORDER BY B.[Order]", planID.c_str()); else if ((floorID != "") && (floorID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, B.XOffset, B.YOffset," " B.PlanID, A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, DeviceToPlansMap as B," " Plans as C " "WHERE (C.FloorplanID=='%q') AND (C.ID==B.PlanID)" " AND (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) " "ORDER BY B.[Order]", floorID.c_str()); else { if (!bDisplayHidden) { result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')"); if (!result.empty()) { std::string pID = result[0][0]; result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)", pID.c_str()); if (!result.empty()) { std::vector<std::vector<std::string> >::const_iterator ittP; for (ittP = result.begin(); ittP != result.end(); ++ittP) { _HiddenDevices.insert(ittP[0][0]); } } } bAllowDeviceToBeHidden = true; } if (order.empty() || (!isAlpha)) strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC"); else { sprintf(szOrderBy, "A.[Order],A.%%s ASC"); } if (hardwareid != "") { szQuery = ( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType," " A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue," " A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID," " A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2," " A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description," " A.Options, A.Color " "FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B " "ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) " "WHERE (A.HardwareID == %q) " "ORDER BY "); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), hardwareid.c_str(), order.c_str()); } else { szQuery = ( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used,A.Type, A.SubType," " A.SignalLevel, A.BatteryLevel, A.nValue, A.sValue," " A.LastUpdate, A.Favorite, A.SwitchType, A.HardwareID," " A.AddjValue, A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1, A.StrParam2," " A.Protected, IFNULL(B.XOffset,0), IFNULL(B.YOffset,0), IFNULL(B.PlanID,0), A.Description," " A.Options, A.Color " "FROM DeviceStatus as A LEFT OUTER JOIN DeviceToPlansMap as B " "ON (B.DeviceRowID==a.ID) AND (B.DevSceneType==0) " "ORDER BY "); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), order.c_str()); } } } else { if (iUser == -1) { return; } if (rowid != "") { result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, 0 as XOffset," " 0 as YOffset, 0 as PlanID, A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, SharedDevices as B " "WHERE (B.DeviceRowID==a.ID)" " AND (B.SharedUserID==%lu) AND (A.ID=='%q')", m_users[iUser].ID, rowid.c_str()); } else if ((planID != "") && (planID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, C.XOffset," " C.YOffset, C.PlanID, A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, SharedDevices as B," " DeviceToPlansMap as C " "WHERE (C.PlanID=='%q') AND (C.DeviceRowID==a.ID)" " AND (B.DeviceRowID==a.ID) " "AND (B.SharedUserID==%lu) ORDER BY C.[Order]", planID.c_str(), m_users[iUser].ID); else if ((floorID != "") && (floorID != "0")) result = m_sql.safe_query( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, C.XOffset, C.YOffset," " C.PlanID, A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, SharedDevices as B," " DeviceToPlansMap as C, Plans as D " "WHERE (D.FloorplanID=='%q') AND (D.ID==C.PlanID)" " AND (C.DeviceRowID==a.ID) AND (B.DeviceRowID==a.ID)" " AND (B.SharedUserID==%lu) ORDER BY C.[Order]", floorID.c_str(), m_users[iUser].ID); else { if (!bDisplayHidden) { result = m_sql.safe_query("SELECT ID FROM Plans WHERE (Name=='$Hidden Devices')"); if (!result.empty()) { std::string pID = result[0][0]; result = m_sql.safe_query("SELECT DeviceRowID FROM DeviceToPlansMap WHERE (PlanID=='%q') AND (DevSceneType==0)", pID.c_str()); if (!result.empty()) { std::vector<std::vector<std::string> >::const_iterator ittP; for (ittP = result.begin(); ittP != result.end(); ++ittP) { _HiddenDevices.insert(ittP[0][0]); } } } bAllowDeviceToBeHidden = true; } if (order.empty() || (!isAlpha)) { strcpy(szOrderBy, "A.[Order],A.LastUpdate DESC"); } else { sprintf(szOrderBy, "A.[Order],A.%%s ASC"); } szQuery = ( "SELECT A.ID, A.DeviceID, A.Unit, A.Name, A.Used," " A.Type, A.SubType, A.SignalLevel, A.BatteryLevel," " A.nValue, A.sValue, A.LastUpdate, A.Favorite," " A.SwitchType, A.HardwareID, A.AddjValue," " A.AddjMulti, A.AddjValue2, A.AddjMulti2," " A.LastLevel, A.CustomImage, A.StrParam1," " A.StrParam2, A.Protected, IFNULL(C.XOffset,0)," " IFNULL(C.YOffset,0), IFNULL(C.PlanID,0), A.Description," " A.Options, A.Color " "FROM DeviceStatus as A, SharedDevices as B " "LEFT OUTER JOIN DeviceToPlansMap as C ON (C.DeviceRowID==A.ID)" "WHERE (B.DeviceRowID==A.ID)" " AND (B.SharedUserID==%lu) ORDER BY "); szQuery += szOrderBy; result = m_sql.safe_query(szQuery.c_str(), m_users[iUser].ID, order.c_str()); } } if (!result.empty()) { for (const auto & itt : result) { std::vector<std::string> sd = itt; unsigned char favorite = atoi(sd[12].c_str()); if ((planID != "") && (planID != "0")) favorite = 1; if ((bFetchFavorites) && (!favorite)) continue; std::string sDeviceName = sd[3]; if (!bDisplayHidden) { if (_HiddenDevices.find(sd[0]) != _HiddenDevices.end()) continue; if (sDeviceName[0] == '$') { if (bAllowDeviceToBeHidden) continue; if (planID.size() > 0) sDeviceName = sDeviceName.substr(1); } } int hardwareID = atoi(sd[14].c_str()); std::map<int, _tHardwareListInt>::iterator hItt = _hardwareNames.find(hardwareID); if (hItt != _hardwareNames.end()) { if ((!bDisplayDisabled) && (!(*hItt).second.Enabled)) continue; } unsigned int dType = atoi(sd[5].c_str()); unsigned int dSubType = atoi(sd[6].c_str()); unsigned int used = atoi(sd[4].c_str()); int nValue = atoi(sd[9].c_str()); std::string sValue = sd[10]; std::string sLastUpdate = sd[11]; if (sLastUpdate.size() > 19) sLastUpdate = sLastUpdate.substr(0, 19); if (iLastUpdate != 0) { time_t cLastUpdate; ParseSQLdatetime(cLastUpdate, tLastUpdate, sLastUpdate, tm1.tm_isdst); if (cLastUpdate <= iLastUpdate) continue; } _eSwitchType switchtype = (_eSwitchType)atoi(sd[13].c_str()); _eMeterType metertype = (_eMeterType)switchtype; double AddjValue = atof(sd[15].c_str()); double AddjMulti = atof(sd[16].c_str()); double AddjValue2 = atof(sd[17].c_str()); double AddjMulti2 = atof(sd[18].c_str()); int LastLevel = atoi(sd[19].c_str()); int CustomImage = atoi(sd[20].c_str()); std::string strParam1 = base64_encode(sd[21]); std::string strParam2 = base64_encode(sd[22]); int iProtected = atoi(sd[23].c_str()); std::string Description = sd[27]; std::string sOptions = sd[28]; std::string sColor = sd[29]; std::map<std::string, std::string> options = m_sql.BuildDeviceOptions(sOptions); struct tm ntime; time_t checktime; ParseSQLdatetime(checktime, ntime, sLastUpdate, tm1.tm_isdst); bool bHaveTimeout = (now - checktime >= SensorTimeOut * 60); if (dType == pTypeTEMP_RAIN) continue; //dont want you for now if ((rused == "true") && (!used)) continue; if ( (rused == "false") && (used) ) continue; if (rfilter != "") { if (rfilter == "light") { if ( (dType != pTypeLighting1) && (dType != pTypeLighting2) && (dType != pTypeLighting3) && (dType != pTypeLighting4) && (dType != pTypeLighting5) && (dType != pTypeLighting6) && (dType != pTypeFan) && (dType != pTypeColorSwitch) && (dType != pTypeSecurity1) && (dType != pTypeSecurity2) && (dType != pTypeEvohome) && (dType != pTypeEvohomeRelay) && (dType != pTypeCurtain) && (dType != pTypeBlinds) && (dType != pTypeRFY) && (dType != pTypeChime) && (dType != pTypeThermostat2) && (dType != pTypeThermostat3) && (dType != pTypeThermostat4) && (dType != pTypeRemote) && (dType != pTypeGeneralSwitch) && (dType != pTypeHomeConfort) && (dType != pTypeChime) && (dType != pTypeFS20) && (!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus))) && (!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator))) ) continue; } else if (rfilter == "temp") { if ( (dType != pTypeTEMP) && (dType != pTypeHUM) && (dType != pTypeTEMP_HUM) && (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) && (dType != pTypeEvohomeZone) && (dType != pTypeEvohomeWater) && (!((dType == pTypeWIND) && (dSubType == sTypeWIND4))) && (!((dType == pTypeUV) && (dSubType == sTypeUV3))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSystemTemp))) && (dType != pTypeThermostat1) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp))) && (dType != pTypeRego6XXTemp) ) continue; } else if (rfilter == "weather") { if ( (dType != pTypeWIND) && (dType != pTypeRAIN) && (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) && (dType != pTypeUV) && (!((dType == pTypeGeneral) && (dSubType == sTypeVisibility))) && (!((dType == pTypeGeneral) && (dSubType == sTypeBaro))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSolarRadiation))) ) continue; } else if (rfilter == "utility") { if ( (dType != pTypeRFXMeter) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorAD))) && (!((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorVolt))) && (!((dType == pTypeGeneral) && (dSubType == sTypeVoltage))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCurrent))) && (!((dType == pTypeGeneral) && (dSubType == sTypeTextStatus))) && (!((dType == pTypeGeneral) && (dSubType == sTypeAlert))) && (!((dType == pTypeGeneral) && (dSubType == sTypePressure))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSoilMoisture))) && (!((dType == pTypeGeneral) && (dSubType == sTypeLeafWetness))) && (!((dType == pTypeGeneral) && (dSubType == sTypePercentage))) && (!((dType == pTypeGeneral) && (dSubType == sTypeWaterflow))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCustom))) && (!((dType == pTypeGeneral) && (dSubType == sTypeFan))) && (!((dType == pTypeGeneral) && (dSubType == sTypeSoundLevel))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveClock))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatMode))) && (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveThermostatFanMode))) && (!((dType == pTypeGeneral) && (dSubType == sTypeDistance))) && (!((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental))) && (!((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter))) && (!((dType == pTypeGeneral) && (dSubType == sTypeKwh))) && (dType != pTypeCURRENT) && (dType != pTypeCURRENTENERGY) && (dType != pTypeENERGY) && (dType != pTypePOWER) && (dType != pTypeP1Power) && (dType != pTypeP1Gas) && (dType != pTypeYouLess) && (dType != pTypeAirQuality) && (dType != pTypeLux) && (dType != pTypeUsage) && (!((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXCounter))) && (!((dType == pTypeThermostat) && (dSubType == sTypeThermSetpoint))) && (dType != pTypeWEIGHT) && (!((dType == pTypeRadiator1) && (dSubType == sTypeSmartwares))) ) continue; } else if (rfilter == "wind") { if ( (dType != pTypeWIND) ) continue; } else if (rfilter == "rain") { if ( (dType != pTypeRAIN) ) continue; } else if (rfilter == "uv") { if ( (dType != pTypeUV) ) continue; } else if (rfilter == "baro") { if ( (dType != pTypeTEMP_HUM_BARO) && (dType != pTypeTEMP_BARO) ) continue; } else if (rfilter == "zwavealarms") { if (!((dType == pTypeGeneral) && (dSubType == sTypeZWaveAlarm))) continue; } } std::string thisIdx = sd[0]; int devIdx = atoi(thisIdx.c_str()); if ((ii > 0) && thisIdx == root["result"][ii - 1]["idx"].asString()) { std::string typeOfThisOne = RFX_Type_Desc(dType, 1); if (typeOfThisOne == root["result"][ii - 1]["Type"].asString()) { root["result"][ii - 1]["PlanIDs"].append(atoi(sd[26].c_str())); continue; } } root["result"][ii]["HardwareID"] = hardwareID; if (_hardwareNames.find(hardwareID) == _hardwareNames.end()) { root["result"][ii]["HardwareName"] = "Unknown?"; root["result"][ii]["HardwareTypeVal"] = 0; root["result"][ii]["HardwareType"] = "Unknown?"; } else { root["result"][ii]["HardwareName"] = _hardwareNames[hardwareID].Name; root["result"][ii]["HardwareTypeVal"] = _hardwareNames[hardwareID].HardwareTypeVal; root["result"][ii]["HardwareType"] = _hardwareNames[hardwareID].HardwareType; } root["result"][ii]["idx"] = sd[0]; root["result"][ii]["Protected"] = (iProtected != 0); CDomoticzHardwareBase *pHardware = m_mainworker.GetHardware(hardwareID); if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_SolarEdgeAPI) { int seSensorTimeOut = 60 * 24 * 60; bHaveTimeout = (now - checktime >= seSensorTimeOut * 60); } else if (pHardware->HwdType == HTYPE_Wunderground) { CWunderground *pWHardware = reinterpret_cast<CWunderground *>(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != "") { root["result"][ii]["forecast_url"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_DarkSky) { CDarkSky *pWHardware = reinterpret_cast<CDarkSky*>(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != "") { root["result"][ii]["forecast_url"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_AccuWeather) { CAccuWeather *pWHardware = reinterpret_cast<CAccuWeather*>(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != "") { root["result"][ii]["forecast_url"] = base64_encode(forecast_url); } } else if (pHardware->HwdType == HTYPE_OpenWeatherMap) { COpenWeatherMap *pWHardware = reinterpret_cast<COpenWeatherMap*>(pHardware); std::string forecast_url = pWHardware->GetForecastURL(); if (forecast_url != "") { root["result"][ii]["forecast_url"] = base64_encode(forecast_url); } } } if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_PythonPlugin)) { root["result"][ii]["ID"] = sd[1]; } else { sprintf(szData, "%04X", (unsigned int)atoi(sd[1].c_str())); if ( (dType == pTypeTEMP) || (dType == pTypeTEMP_BARO) || (dType == pTypeTEMP_HUM) || (dType == pTypeTEMP_HUM_BARO) || (dType == pTypeBARO) || (dType == pTypeHUM) || (dType == pTypeWIND) || (dType == pTypeRAIN) || (dType == pTypeUV) || (dType == pTypeCURRENT) || (dType == pTypeCURRENTENERGY) || (dType == pTypeENERGY) || (dType == pTypeRFXMeter) || (dType == pTypeAirQuality) || (dType == pTypeRFXSensor) || (dType == pTypeP1Power) || (dType == pTypeP1Gas) ) { root["result"][ii]["ID"] = szData; } else { root["result"][ii]["ID"] = sd[1]; } } root["result"][ii]["Unit"] = atoi(sd[2].c_str()); root["result"][ii]["Type"] = RFX_Type_Desc(dType, 1); root["result"][ii]["SubType"] = RFX_Type_SubType_Desc(dType, dSubType); root["result"][ii]["TypeImg"] = RFX_Type_Desc(dType, 2); root["result"][ii]["Name"] = sDeviceName; root["result"][ii]["Description"] = Description; root["result"][ii]["Used"] = used; root["result"][ii]["Favorite"] = favorite; int iSignalLevel = atoi(sd[7].c_str()); if (iSignalLevel < 12) root["result"][ii]["SignalLevel"] = iSignalLevel; else root["result"][ii]["SignalLevel"] = "-"; root["result"][ii]["BatteryLevel"] = atoi(sd[8].c_str()); root["result"][ii]["LastUpdate"] = sLastUpdate; root["result"][ii]["CustomImage"] = CustomImage; root["result"][ii]["XOffset"] = sd[24].c_str(); root["result"][ii]["YOffset"] = sd[25].c_str(); root["result"][ii]["PlanID"] = sd[26].c_str(); Json::Value jsonArray; jsonArray.append(atoi(sd[26].c_str())); root["result"][ii]["PlanIDs"] = jsonArray; root["result"][ii]["AddjValue"] = AddjValue; root["result"][ii]["AddjMulti"] = AddjMulti; root["result"][ii]["AddjValue2"] = AddjValue2; root["result"][ii]["AddjMulti2"] = AddjMulti2; std::stringstream s_data; s_data << int(nValue) << ", " << sValue; root["result"][ii]["Data"] = s_data.str(); root["result"][ii]["Notifications"] = (m_notifications.HasNotifications(sd[0]) == true) ? "true" : "false"; root["result"][ii]["ShowNotifications"] = true; bool bHasTimers = false; if ( (dType == pTypeLighting1) || (dType == pTypeLighting2) || (dType == pTypeLighting3) || (dType == pTypeLighting4) || (dType == pTypeLighting5) || (dType == pTypeLighting6) || (dType == pTypeFan) || (dType == pTypeColorSwitch) || (dType == pTypeCurtain) || (dType == pTypeBlinds) || (dType == pTypeRFY) || (dType == pTypeChime) || (dType == pTypeThermostat2) || (dType == pTypeThermostat3) || (dType == pTypeThermostat4) || (dType == pTypeRemote) || (dType == pTypeGeneralSwitch) || (dType == pTypeHomeConfort) || (dType == pTypeFS20) || ((dType == pTypeRadiator1) && (dSubType == sTypeSmartwaresSwitchRadiator)) || ((dType == pTypeRego6XXValue) && (dSubType == sTypeRego6XXStatus)) ) { bHasTimers = m_sql.HasTimers(sd[0]); bHaveTimeout = false; #ifdef WITH_OPENZWAVE if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; int nodeID = (ID & 0x0000FF00) >> 8; bHaveTimeout = pZWave->HasNodeFailed(nodeID); } } #endif root["result"][ii]["HaveTimeout"] = bHaveTimeout; std::string lstatus = ""; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root["result"][ii]["Status"] = lstatus; root["result"][ii]["StrParam1"] = strParam1; root["result"][ii]["StrParam2"] = strParam2; std::string IconFile = "Light"; std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage); if (ittIcon != m_custom_light_icons_lookup.end()) { IconFile = m_custom_light_icons[ittIcon->second].RootFile; } root["result"][ii]["Image"] = IconFile; if (switchtype == STYPE_Dimmer) { root["result"][ii]["Level"] = LastLevel; int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel); root["result"][ii]["LevelInt"] = iLevel; if ((dType == pTypeColorSwitch) || (dType == pTypeLighting5 && dSubType == sTypeTRC02) || (dType == pTypeLighting5 && dSubType == sTypeTRC02_2) || (dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02) || (dType == pTypeGeneralSwitch && dSubType == sSwitchTypeTRC02_2)) { _tColor color(sColor); std::string jsonColor = color.toJSONString(); root["result"][ii]["Color"] = jsonColor; llevel = LastLevel; if (lstatus == "Set Level" || lstatus == "Set Color") { sprintf(szTmp, "Set Level: %d %%", LastLevel); root["result"][ii]["Status"] = szTmp; } } } else { root["result"][ii]["Level"] = llevel; root["result"][ii]["LevelInt"] = atoi(sValue.c_str()); } root["result"][ii]["HaveDimmer"] = bHaveDimmer; std::string DimmerType = "none"; if (switchtype == STYPE_Dimmer) { DimmerType = "abs"; if (_hardwareNames.find(hardwareID) != _hardwareNames.end()) { if (_hardwareNames[hardwareID].HardwareTypeVal == HTYPE_LimitlessLights && atoi(_hardwareNames[hardwareID].Mode2.c_str()) != CLimitLess::LBTYPE_V6 && (atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_RGB || atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_White || atoi(_hardwareNames[hardwareID].Mode1.c_str()) == sTypeColor_CW_WW)) { DimmerType = "rel"; } } } root["result"][ii]["DimmerType"] = DimmerType; root["result"][ii]["MaxDimLevel"] = maxDimLevel; root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd; root["result"][ii]["SwitchType"] = Switch_Type_Desc(switchtype); root["result"][ii]["SwitchTypeVal"] = switchtype; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]); root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root["result"][ii]["CameraIdx"] = scidx.str(); } bool bIsSubDevice = false; std::vector<std::vector<std::string> > resultSD; resultSD = m_sql.safe_query("SELECT ID FROM LightSubDevices WHERE (DeviceRowID=='%q')", sd[0].c_str()); bIsSubDevice = (resultSD.size() > 0); root["result"][ii]["IsSubDevice"] = bIsSubDevice; if (switchtype == STYPE_Doorbell) { root["result"][ii]["TypeImg"] = "doorbell"; root["result"][ii]["Status"] = "";//"Pressed"; } else if (switchtype == STYPE_DoorContact) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Door"; } root["result"][ii]["TypeImg"] = "door"; bool bIsOn = IsLightSwitchOn(lstatus); root["result"][ii]["InternalState"] = (bIsOn == true) ? "Open" : "Closed"; if (bIsOn) { lstatus = "Open"; } else { lstatus = "Closed"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_DoorLock) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Door"; } root["result"][ii]["TypeImg"] = "door"; bool bIsOn = IsLightSwitchOn(lstatus); root["result"][ii]["InternalState"] = (bIsOn == true) ? "Locked" : "Unlocked"; if (bIsOn) { lstatus = "Locked"; } else { lstatus = "Unlocked"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_DoorLockInverted) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Door"; } root["result"][ii]["TypeImg"] = "door"; bool bIsOn = IsLightSwitchOn(lstatus); root["result"][ii]["InternalState"] = (bIsOn == true) ? "Unlocked" : "Locked"; if (bIsOn) { lstatus = "Unlocked"; } else { lstatus = "Locked"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_PushOn) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Push"; } root["result"][ii]["TypeImg"] = "push"; root["result"][ii]["Status"] = ""; root["result"][ii]["InternalState"] = (IsLightSwitchOn(lstatus) == true) ? "On" : "Off"; } else if (switchtype == STYPE_PushOff) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Push"; } root["result"][ii]["TypeImg"] = "push"; root["result"][ii]["Status"] = ""; root["result"][ii]["TypeImg"] = "pushoff"; } else if (switchtype == STYPE_X10Siren) root["result"][ii]["TypeImg"] = "siren"; else if (switchtype == STYPE_SMOKEDETECTOR) { root["result"][ii]["TypeImg"] = "smoke"; root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR; root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR); } else if (switchtype == STYPE_Contact) { if (CustomImage == 0) { root["result"][ii]["Image"] = "Contact"; } root["result"][ii]["TypeImg"] = "contact"; bool bIsOn = IsLightSwitchOn(lstatus); if (bIsOn) { lstatus = "Open"; } else { lstatus = "Closed"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_Media) { if ((pHardware != NULL) && (pHardware->HwdType == HTYPE_LogitechMediaServer)) root["result"][ii]["TypeImg"] = "LogitechMediaServer"; else root["result"][ii]["TypeImg"] = "Media"; root["result"][ii]["Status"] = Media_Player_States((_eMediaStatus)nValue); lstatus = sValue; } else if ( (switchtype == STYPE_Blinds) || (switchtype == STYPE_VenetianBlindsUS) || (switchtype == STYPE_VenetianBlindsEU) ) { root["result"][ii]["TypeImg"] = "blinds"; if ((lstatus == "On") || (lstatus == "Close inline relay")) { lstatus = "Closed"; } else if ((lstatus == "Stop") || (lstatus == "Stop inline relay")) { lstatus = "Stopped"; } else { lstatus = "Open"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_BlindsInverted) { root["result"][ii]["TypeImg"] = "blinds"; if (lstatus == "On") { lstatus = "Open"; } else { lstatus = "Closed"; } root["result"][ii]["Status"] = lstatus; } else if ((switchtype == STYPE_BlindsPercentage) || (switchtype == STYPE_BlindsPercentageInverted)) { root["result"][ii]["TypeImg"] = "blinds"; root["result"][ii]["Level"] = LastLevel; int iLevel = round((float(maxDimLevel) / 100.0f)*LastLevel); root["result"][ii]["LevelInt"] = iLevel; if (lstatus == "On") { lstatus = (switchtype == STYPE_BlindsPercentage) ? "Closed" : "Open"; } else if (lstatus == "Off") { lstatus = (switchtype == STYPE_BlindsPercentage) ? "Open" : "Closed"; } root["result"][ii]["Status"] = lstatus; } else if (switchtype == STYPE_Dimmer) { root["result"][ii]["TypeImg"] = "dimmer"; } else if (switchtype == STYPE_Motion) { root["result"][ii]["TypeImg"] = "motion"; } else if (switchtype == STYPE_Selector) { std::string selectorStyle = options["SelectorStyle"]; std::string levelOffHidden = options["LevelOffHidden"]; std::string levelNames = options["LevelNames"]; std::string levelActions = options["LevelActions"]; if (selectorStyle.empty()) { selectorStyle.assign("0"); // default is 'button set' } if (levelOffHidden.empty()) { levelOffHidden.assign("false"); // default is 'not hidden' } if (levelNames.empty()) { levelNames.assign("Off"); // default is Off only } root["result"][ii]["TypeImg"] = "Light"; root["result"][ii]["SelectorStyle"] = atoi(selectorStyle.c_str()); root["result"][ii]["LevelOffHidden"] = (levelOffHidden == "true"); root["result"][ii]["LevelNames"] = base64_encode(levelNames); root["result"][ii]["LevelActions"] = base64_encode(levelActions); } sprintf(szData, "%s", lstatus.c_str()); root["result"][ii]["Data"] = szData; } else if (dType == pTypeSecurity1) { std::string lstatus = ""; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root["result"][ii]["Status"] = lstatus; root["result"][ii]["HaveDimmer"] = bHaveDimmer; root["result"][ii]["MaxDimLevel"] = maxDimLevel; root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd; root["result"][ii]["SwitchType"] = "Security"; root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?; root["result"][ii]["TypeImg"] = "security"; root["result"][ii]["StrParam1"] = strParam1; root["result"][ii]["StrParam2"] = strParam2; root["result"][ii]["Protected"] = (iProtected != 0); if ((dSubType == sTypeKD101) || (dSubType == sTypeSA30) || (switchtype == STYPE_SMOKEDETECTOR)) { root["result"][ii]["SwitchTypeVal"] = STYPE_SMOKEDETECTOR; root["result"][ii]["TypeImg"] = "smoke"; root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_SMOKEDETECTOR); } sprintf(szData, "%s", lstatus.c_str()); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = false; } else if (dType == pTypeSecurity2) { std::string lstatus = ""; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root["result"][ii]["Status"] = lstatus; root["result"][ii]["HaveDimmer"] = bHaveDimmer; root["result"][ii]["MaxDimLevel"] = maxDimLevel; root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd; root["result"][ii]["SwitchType"] = "Security"; root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?; root["result"][ii]["TypeImg"] = "security"; root["result"][ii]["StrParam1"] = strParam1; root["result"][ii]["StrParam2"] = strParam2; root["result"][ii]["Protected"] = (iProtected != 0); sprintf(szData, "%s", lstatus.c_str()); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = false; } else if (dType == pTypeEvohome || dType == pTypeEvohomeRelay) { std::string lstatus = ""; int llevel = 0; bool bHaveDimmer = false; bool bHaveGroupCmd = false; int maxDimLevel = 0; GetLightStatus(dType, dSubType, switchtype, nValue, sValue, lstatus, llevel, bHaveDimmer, maxDimLevel, bHaveGroupCmd); root["result"][ii]["Status"] = lstatus; root["result"][ii]["HaveDimmer"] = bHaveDimmer; root["result"][ii]["MaxDimLevel"] = maxDimLevel; root["result"][ii]["HaveGroupCmd"] = bHaveGroupCmd; root["result"][ii]["SwitchType"] = "evohome"; root["result"][ii]["SwitchTypeVal"] = switchtype; //was 0?; root["result"][ii]["TypeImg"] = "override_mini"; root["result"][ii]["StrParam1"] = strParam1; root["result"][ii]["StrParam2"] = strParam2; root["result"][ii]["Protected"] = (iProtected != 0); sprintf(szData, "%s", lstatus.c_str()); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = false; if (dType == pTypeEvohomeRelay) { root["result"][ii]["SwitchType"] = "TPI"; root["result"][ii]["Level"] = llevel; root["result"][ii]["LevelInt"] = atoi(sValue.c_str()); if (root["result"][ii]["Unit"].asInt() > 100) root["result"][ii]["Protected"] = true; sprintf(szData, "%s: %d", lstatus.c_str(), atoi(sValue.c_str())); root["result"][ii]["Data"] = szData; } } else if ((dType == pTypeEvohomeZone) || (dType == pTypeEvohomeWater)) { root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "override_mini"; std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() >= 3) { int i = 0; double tempCelcius = atof(strarray[i++].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); double tempSetPoint; root["result"][ii]["Temp"] = temp; if (dType == pTypeEvohomeZone) { tempCelcius = atof(strarray[i++].c_str()); tempSetPoint = ConvertTemperature(tempCelcius, tempsign); root["result"][ii]["SetPoint"] = tempSetPoint; } else root["result"][ii]["State"] = strarray[i++]; std::string strstatus = strarray[i++]; root["result"][ii]["Status"] = strstatus; if ((dType == pTypeEvohomeZone || dType == pTypeEvohomeWater) && strarray.size() >= 4) { root["result"][ii]["Until"] = strarray[i++]; } if (dType == pTypeEvohomeZone) { if (tempCelcius == 325.1) sprintf(szTmp, "Off"); else sprintf(szTmp, "%.1f %c", tempSetPoint, tempsign); if (strarray.size() >= 4) sprintf(szData, "%.1f %c, (%s), %s until %s", temp, tempsign, szTmp, strstatus.c_str(), strarray[3].c_str()); else sprintf(szData, "%.1f %c, (%s), %s", temp, tempsign, szTmp, strstatus.c_str()); } else if (strarray.size() >= 4) sprintf(szData, "%.1f %c, %s, %s until %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str(), strarray[3].c_str()); else sprintf(szData, "%.1f %c, %s, %s", temp, tempsign, strarray[1].c_str(), strstatus.c_str()); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if ((dType == pTypeTEMP) || (dType == pTypeRego6XXTemp)) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; sprintf(szData, "%.1f %c", tvalue, tempsign); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } else if (dType == pTypeThermostat1) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 4) { double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; sprintf(szData, "%.1f %c", tvalue, tempsign); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if ((dType == pTypeRFXSensor) && (dSubType == sTypeRFXSensorTemp)) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; sprintf(szData, "%.1f %c", tvalue, tempsign); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "temperature"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } else if (dType == pTypeHUM) { root["result"][ii]["Humidity"] = nValue; root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(sValue.c_str())); sprintf(szData, "Humidity %d %%", nValue); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dType == pTypeTEMP_HUM) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 3) { double tempCelcius = atof(strarray[0].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); int humidity = atoi(strarray[1].c_str()); root["result"][ii]["Temp"] = temp; root["result"][ii]["Humidity"] = humidity; root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str())); sprintf(szData, "%.1f %c, %d %%", temp, tempsign, atoi(strarray[1].c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign)); root["result"][ii]["DewPoint"] = szTmp; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } } else if (dType == pTypeTEMP_HUM_BARO) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 5) { double tempCelcius = atof(strarray[0].c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); int humidity = atoi(strarray[1].c_str()); root["result"][ii]["Temp"] = temp; root["result"][ii]["Humidity"] = humidity; root["result"][ii]["HumidityStatus"] = RFX_Humidity_Status_Desc(atoi(strarray[2].c_str())); root["result"][ii]["Forecast"] = atoi(strarray[4].c_str()); sprintf(szTmp, "%.2f", ConvertTemperature(CalculateDewPoint(tempCelcius, humidity), tempsign)); root["result"][ii]["DewPoint"] = szTmp; if (dSubType == sTypeTHBFloat) { root["result"][ii]["Barometer"] = atof(strarray[3].c_str()); root["result"][ii]["ForecastStr"] = RFX_WSForecast_Desc(atoi(strarray[4].c_str())); } else { root["result"][ii]["Barometer"] = atoi(strarray[3].c_str()); root["result"][ii]["ForecastStr"] = RFX_Forecast_Desc(atoi(strarray[4].c_str())); } if (dSubType == sTypeTHBFloat) { sprintf(szData, "%.1f %c, %d %%, %.1f hPa", temp, tempsign, atoi(strarray[1].c_str()), atof(strarray[3].c_str()) ); } else { sprintf(szData, "%.1f %c, %d %%, %d hPa", temp, tempsign, atoi(strarray[1].c_str()), atoi(strarray[3].c_str()) ); } root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } } else if (dType == pTypeTEMP_BARO) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() >= 3) { double tvalue = ConvertTemperature(atof(strarray[0].c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; int forecast = atoi(strarray[2].c_str()); root["result"][ii]["Forecast"] = forecast; root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast); root["result"][ii]["Barometer"] = atof(strarray[1].c_str()); sprintf(szData, "%.1f %c, %.1f hPa", tvalue, tempsign, atof(strarray[1].c_str()) ); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } } else if (dType == pTypeUV) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 2) { float UVI = static_cast<float>(atof(strarray[0].c_str())); root["result"][ii]["UVI"] = strarray[0]; if (dSubType == sTypeUV3) { double tvalue = ConvertTemperature(atof(strarray[1].c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; sprintf(szData, "%.1f UVI, %.1f&deg; %c", UVI, tvalue, tempsign); _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } else { sprintf(szData, "%.1f UVI", UVI); } root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if (dType == pTypeWIND) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 6) { root["result"][ii]["Direction"] = atof(strarray[0].c_str()); root["result"][ii]["DirectionStr"] = strarray[1]; if (dSubType != sTypeWIND5) { int intSpeed = atoi(strarray[2].c_str()); if (m_sql.m_windunit != WINDUNIT_Beaufort) { sprintf(szTmp, "%.1f", float(intSpeed) * m_sql.m_windscale); } else { float windms = float(intSpeed) * 0.1f; sprintf(szTmp, "%d", MStoBeaufort(windms)); } root["result"][ii]["Speed"] = szTmp; } { int intGust = atoi(strarray[3].c_str()); if (m_sql.m_windunit != WINDUNIT_Beaufort) { sprintf(szTmp, "%.1f", float(intGust) *m_sql.m_windscale); } else { float gustms = float(intGust) * 0.1f; sprintf(szTmp, "%d", MStoBeaufort(gustms)); } root["result"][ii]["Gust"] = szTmp; } if ((dSubType == sTypeWIND4) || (dSubType == sTypeWINDNoTemp)) { if (dSubType == sTypeWIND4) { double tvalue = ConvertTemperature(atof(strarray[4].c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; } double tvalue = ConvertTemperature(atof(strarray[5].c_str()), tempsign); root["result"][ii]["Chill"] = tvalue; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } root["result"][ii]["Data"] = sValue; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if (dType == pTypeRAIN) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 2) { time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; if (dSubType != sTypeRAINWU) { result2 = m_sql.safe_query( "SELECT MIN(Total), MAX(Total) FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); } else { result2 = m_sql.safe_query( "SELECT Total, Total FROM Rain WHERE (DeviceRowID='%q' AND Date>='%q') ORDER BY ROWID DESC LIMIT 1", sd[0].c_str(), szDate); } if (!result2.empty()) { double total_real = 0; float rate = 0; std::vector<std::string> sd2 = result2[0]; if (dSubType != sTypeRAINWU) { double total_min = atof(sd2[0].c_str()); double total_max = atof(strarray[1].c_str()); total_real = total_max - total_min; } else { total_real = atof(sd2[1].c_str()); } total_real *= AddjMulti; rate = (static_cast<float>(atof(strarray[0].c_str())) / 100.0f)*float(AddjMulti); sprintf(szTmp, "%.1f", total_real); root["result"][ii]["Rain"] = szTmp; sprintf(szTmp, "%g", rate); root["result"][ii]["RainRate"] = szTmp; root["result"][ii]["Data"] = sValue; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else { root["result"][ii]["Rain"] = "0"; root["result"][ii]["RainRate"] = "0"; root["result"][ii]["Data"] = "0"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } } else if (dType == pTypeRFXMeter) { std::string ValueQuantity = options["ValueQuantity"]; std::string ValueUnits = options["ValueUnits"]; if (ValueQuantity.empty()) { ValueQuantity.assign("Count"); } if (ValueUnits.empty()) { ValueUnits.assign(""); } time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; uint64_t total_min = std::stoull(sd2[0]); uint64_t total_max = std::stoull(sValue); uint64_t total_real = total_max - total_min; sprintf(szTmp, "%" PRIu64, total_real); float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); float musage = 0.0f; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) / divider; sprintf(szTmp, "%.3f kWh", musage); break; case MTYPE_GAS: musage = float(total_real) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_WATER: musage = float(total_real) / (divider / 1000.0f); sprintf(szTmp, "%d Liter", round(musage)); break; case MTYPE_COUNTER: sprintf(szTmp, "%" PRIu64, total_real); if (!ValueUnits.empty()) { strcat(szTmp, " "); strcat(szTmp, ValueUnits.c_str()); } break; default: strcpy(szTmp, "?"); break; } } root["result"][ii]["CounterToday"] = szTmp; root["result"][ii]["SwitchTypeVal"] = metertype; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["ValueQuantity"] = ""; root["result"][ii]["ValueUnits"] = ""; double meteroffset = AddjValue; float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); double dvalue = static_cast<double>(atof(sValue.c_str())); switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str()); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; default: root["result"][ii]["Data"] = "?"; root["result"][ii]["Counter"] = "?"; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; } } else if ((dType == pTypeGeneral) && (dSubType == sTypeCounterIncremental)) { std::string ValueQuantity = options["ValueQuantity"]; std::string ValueUnits = options["ValueUnits"]; if (ValueQuantity.empty()) { ValueQuantity.assign("Count"); } if (ValueUnits.empty()) { ValueUnits.assign(""); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; uint64_t total_min = std::stoull(sd2[0]); uint64_t total_max = std::stoull(sValue); uint64_t total_real = total_max - total_min; sprintf(szTmp, "%" PRIu64, total_real); float musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) / divider; sprintf(szTmp, "%.3f kWh", musage); break; case MTYPE_GAS: musage = float(total_real) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_WATER: musage = float(total_real) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_COUNTER: sprintf(szTmp, "%" PRIu64, total_real); if (!ValueUnits.empty()) { strcat(szTmp, " "); strcat(szTmp, ValueUnits.c_str()); } break; default: strcpy(szTmp, "0"); break; } } root["result"][ii]["Counter"] = sValue; root["result"][ii]["CounterToday"] = szTmp; root["result"][ii]["SwitchTypeVal"] = metertype; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "counter"; root["result"][ii]["ValueQuantity"] = ""; root["result"][ii]["ValueUnits"] = ""; double dvalue = static_cast<double>(atof(sValue.c_str())); double meteroffset = AddjValue; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, "%" PRIu64 " %s", static_cast<uint64_t>(meteroffset + dvalue), ValueUnits.c_str()); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; default: root["result"][ii]["Data"] = "?"; root["result"][ii]["Counter"] = "?"; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; } } else if ((dType == pTypeGeneral) && (dSubType == sTypeManagedCounter)) { std::string ValueQuantity = options["ValueQuantity"]; std::string ValueUnits = options["ValueUnits"]; if (ValueQuantity.empty()) { ValueQuantity.assign("Count"); } if (ValueUnits.empty()) { ValueUnits.assign(""); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); std::vector<std::string> splitresults; StringSplit(sValue, ";", splitresults); double dvalue; if (splitresults.size() < 2) { dvalue = static_cast<double>(atof(sValue.c_str())); } else { dvalue = static_cast<double>(atof(splitresults[1].c_str())); if (dvalue < 0.0) { dvalue = static_cast<double>(atof(splitresults[0].c_str())); } } root["result"][ii]["Data"] = root["result"][ii]["Counter"]; root["result"][ii]["SwitchTypeVal"] = metertype; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "counter"; root["result"][ii]["ValueQuantity"] = ""; root["result"][ii]["ValueUnits"] = ""; root["result"][ii]["ShowNotifications"] = false; double meteroffset = AddjValue; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, "%.3f kWh", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_GAS: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_WATER: sprintf(szTmp, "%.3f m3", meteroffset + (dvalue / divider)); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; break; case MTYPE_COUNTER: sprintf(szTmp, "%g %s", meteroffset + dvalue, ValueUnits.c_str()); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Counter"] = szTmp; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; default: root["result"][ii]["Data"] = "?"; root["result"][ii]["Counter"] = "?"; root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; } } else if (dType == pTypeYouLess) { std::string ValueQuantity = options["ValueQuantity"]; std::string ValueUnits = options["ValueUnits"]; float musage = 0; if (ValueQuantity.empty()) { ValueQuantity.assign("Count"); } if (ValueUnits.empty()) { ValueUnits.assign(""); } float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_real; total_real = total_max - total_min; sprintf(szTmp, "%llu", total_real); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_real) / divider; sprintf(szTmp, "%.3f kWh", musage); break; case MTYPE_GAS: musage = float(total_real) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_WATER: musage = float(total_real) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_COUNTER: sprintf(szTmp, "%llu %s", total_real, ValueUnits.c_str()); break; default: strcpy(szTmp, "0"); break; } } root["result"][ii]["CounterToday"] = szTmp; std::vector<std::string> splitresults; StringSplit(sValue, ";", splitresults); if (splitresults.size() < 2) continue; unsigned long long total_actual = std::strtoull(splitresults[0].c_str(), nullptr, 10); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(total_actual) / divider; sprintf(szTmp, "%.03f", musage); break; case MTYPE_GAS: case MTYPE_WATER: musage = float(total_actual) / divider; sprintf(szTmp, "%.03f", musage); break; case MTYPE_COUNTER: sprintf(szTmp, "%llu", total_actual); break; default: strcpy(szTmp, "0"); break; } root["result"][ii]["Counter"] = szTmp; root["result"][ii]["SwitchTypeVal"] = metertype; unsigned long long acounter = std::strtoull(sValue.c_str(), nullptr, 10); musage = 0; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: musage = float(acounter) / divider; sprintf(szTmp, "%.3f kWh %s Watt", musage, splitresults[1].c_str()); break; case MTYPE_GAS: musage = float(acounter) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_WATER: musage = float(acounter) / divider; sprintf(szTmp, "%.3f m3", musage); break; case MTYPE_COUNTER: sprintf(szTmp, "%llu %s", acounter, ValueUnits.c_str()); break; default: strcpy(szTmp, "0"); break; } root["result"][ii]["Data"] = szTmp; root["result"][ii]["ValueQuantity"] = ""; root["result"][ii]["ValueUnits"] = ""; switch (metertype) { case MTYPE_ENERGY: case MTYPE_ENERGY_GENERATED: sprintf(szTmp, "%s Watt", splitresults[1].c_str()); break; case MTYPE_GAS: sprintf(szTmp, "%s m3", splitresults[1].c_str()); break; case MTYPE_WATER: sprintf(szTmp, "%s m3", splitresults[1].c_str()); break; case MTYPE_COUNTER: sprintf(szTmp, "%s", splitresults[1].c_str()); root["result"][ii]["ValueQuantity"] = ValueQuantity; root["result"][ii]["ValueUnits"] = ValueUnits; break; default: strcpy(szTmp, "0"); break; } root["result"][ii]["Usage"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dType == pTypeP1Power) { std::vector<std::string> splitresults; StringSplit(sValue, ";", splitresults); if (splitresults.size() != 6) { root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY; root["result"][ii]["Counter"] = "0"; root["result"][ii]["CounterDeliv"] = "0"; root["result"][ii]["Usage"] = "Invalid"; root["result"][ii]["UsageDeliv"] = "Invalid"; root["result"][ii]["Data"] = "Invalid!: " + sValue; root["result"][ii]["HaveTimeout"] = true; root["result"][ii]["CounterToday"] = "Invalid"; root["result"][ii]["CounterDelivToday"] = "Invalid"; } else { float EnergyDivider = 1000.0f; int tValue; if (m_sql.GetPreferencesVar("MeterDividerEnergy", tValue)) { EnergyDivider = float(tValue); } unsigned long long powerusage1 = std::strtoull(splitresults[0].c_str(), nullptr, 10); unsigned long long powerusage2 = std::strtoull(splitresults[1].c_str(), nullptr, 10); unsigned long long powerdeliv1 = std::strtoull(splitresults[2].c_str(), nullptr, 10); unsigned long long powerdeliv2 = std::strtoull(splitresults[3].c_str(), nullptr, 10); unsigned long long usagecurrent = std::strtoull(splitresults[4].c_str(), nullptr, 10); unsigned long long delivcurrent = std::strtoull(splitresults[5].c_str(), nullptr, 10); powerdeliv1 = (powerdeliv1 < 10) ? 0 : powerdeliv1; powerdeliv2 = (powerdeliv2 < 10) ? 0 : powerdeliv2; unsigned long long powerusage = powerusage1 + powerusage2; unsigned long long powerdeliv = powerdeliv1 + powerdeliv2; if (powerdeliv < 2) powerdeliv = 0; double musage = 0; root["result"][ii]["SwitchTypeVal"] = MTYPE_ENERGY; musage = double(powerusage) / EnergyDivider; sprintf(szTmp, "%.03f", musage); root["result"][ii]["Counter"] = szTmp; musage = double(powerdeliv) / EnergyDivider; sprintf(szTmp, "%.03f", musage); root["result"][ii]["CounterDeliv"] = szTmp; if (bHaveTimeout) { usagecurrent = 0; delivcurrent = 0; } sprintf(szTmp, "%llu Watt", usagecurrent); root["result"][ii]["Usage"] = szTmp; sprintf(szTmp, "%llu Watt", delivcurrent); root["result"][ii]["UsageDeliv"] = szTmp; root["result"][ii]["Data"] = sValue; root["result"][ii]["HaveTimeout"] = bHaveTimeout; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value1), MIN(Value2), MIN(Value5), MIN(Value6) FROM MultiMeter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; unsigned long long total_min_usage_1 = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_min_deliv_1 = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_min_usage_2 = std::strtoull(sd2[2].c_str(), nullptr, 10); unsigned long long total_min_deliv_2 = std::strtoull(sd2[3].c_str(), nullptr, 10); unsigned long long total_real_usage, total_real_deliv; total_real_usage = powerusage - (total_min_usage_1 + total_min_usage_2); total_real_deliv = powerdeliv - (total_min_deliv_1 + total_min_deliv_2); musage = double(total_real_usage) / EnergyDivider; sprintf(szTmp, "%.3f kWh", musage); root["result"][ii]["CounterToday"] = szTmp; musage = double(total_real_deliv) / EnergyDivider; sprintf(szTmp, "%.3f kWh", musage); root["result"][ii]["CounterDelivToday"] = szTmp; } else { sprintf(szTmp, "%.3f kWh", 0.0f); root["result"][ii]["CounterToday"] = szTmp; root["result"][ii]["CounterDelivToday"] = szTmp; } } } else if (dType == pTypeP1Gas) { root["result"][ii]["SwitchTypeVal"] = MTYPE_GAS; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; uint64_t total_min_gas = std::stoull(sd2[0]); uint64_t gasactual = std::stoull(sValue); uint64_t total_real_gas = gasactual - total_min_gas; double musage = double(gasactual) / divider; sprintf(szTmp, "%.03f", musage); root["result"][ii]["Counter"] = szTmp; musage = double(total_real_gas) / divider; sprintf(szTmp, "%.03f m3", musage); root["result"][ii]["CounterToday"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider); root["result"][ii]["Data"] = szTmp; } else { sprintf(szTmp, "%.03f", 0.0f); root["result"][ii]["Counter"] = szTmp; sprintf(szTmp, "%.03f m3", 0.0f); root["result"][ii]["CounterToday"] = szTmp; sprintf(szTmp, "%.03f", atof(sValue.c_str()) / divider); root["result"][ii]["Data"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if (dType == pTypeCURRENT) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 3) { int displaytype = 0; int voltage = 230; m_sql.GetPreferencesVar("CM113DisplayType", displaytype); m_sql.GetPreferencesVar("ElectricVoltage", voltage); double val1 = atof(strarray[0].c_str()); double val2 = atof(strarray[1].c_str()); double val3 = atof(strarray[2].c_str()); if (displaytype == 0) { if ((val2 == 0) && (val3 == 0)) sprintf(szData, "%.1f A", val1); else sprintf(szData, "%.1f A, %.1f A, %.1f A", val1, val2, val3); } else { if ((val2 == 0) && (val3 == 0)) sprintf(szData, "%d Watt", int(val1*voltage)); else sprintf(szData, "%d Watt, %d Watt, %d Watt", int(val1*voltage), int(val2*voltage), int(val3*voltage)); } root["result"][ii]["Data"] = szData; root["result"][ii]["displaytype"] = displaytype; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if (dType == pTypeCURRENTENERGY) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 4) { int displaytype = 0; int voltage = 230; m_sql.GetPreferencesVar("CM113DisplayType", displaytype); m_sql.GetPreferencesVar("ElectricVoltage", voltage); double total = atof(strarray[3].c_str()); if (displaytype == 0) { sprintf(szData, "%.1f A, %.1f A, %.1f A", atof(strarray[0].c_str()), atof(strarray[1].c_str()), atof(strarray[2].c_str())); } else { sprintf(szData, "%d Watt, %d Watt, %d Watt", int(atof(strarray[0].c_str())*voltage), int(atof(strarray[1].c_str())*voltage), int(atof(strarray[2].c_str())*voltage)); } if (total > 0) { sprintf(szTmp, ", Total: %.3f kWh", total / 1000.0f); strcat(szData, szTmp); } root["result"][ii]["Data"] = szData; root["result"][ii]["displaytype"] = displaytype; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } else if ( ((dType == pTypeENERGY) || (dType == pTypePOWER)) || ((dType == pTypeGeneral) && (dSubType == sTypeKwh)) ) { std::vector<std::string> strarray; StringSplit(sValue, ";", strarray); if (strarray.size() == 2) { double total = atof(strarray[1].c_str()) / 1000; time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { float divider = m_sql.GetCounterDivider(int(metertype), int(dType), float(AddjValue2)); std::vector<std::string> sd2 = result2[0]; double minimum = atof(sd2[0].c_str()) / divider; sprintf(szData, "%.3f kWh", total); root["result"][ii]["Data"] = szData; if ((dType == pTypeENERGY) || (dType == pTypePOWER)) { sprintf(szData, "%ld Watt", atol(strarray[0].c_str())); } else { sprintf(szData, "%g Watt", atof(strarray[0].c_str())); } root["result"][ii]["Usage"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; sprintf(szTmp, "%.3f kWh", total - minimum); root["result"][ii]["CounterToday"] = szTmp; } else { sprintf(szData, "%.3f kWh", total); root["result"][ii]["Data"] = szData; if ((dType == pTypeENERGY) || (dType == pTypePOWER)) { sprintf(szData, "%ld Watt", atol(strarray[0].c_str())); } else { sprintf(szData, "%g Watt", atof(strarray[0].c_str())); } root["result"][ii]["Usage"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; sprintf(szTmp, "%d kWh", 0); root["result"][ii]["CounterToday"] = szTmp; } root["result"][ii]["TypeImg"] = "current"; root["result"][ii]["SwitchTypeVal"] = switchtype; //MTYPE_ENERGY root["result"][ii]["EnergyMeterMode"] = options["EnergyMeterMode"]; //for alternate Energy Reading } } else if (dType == pTypeAirQuality) { if (bHaveTimeout) nValue = 0; sprintf(szTmp, "%d ppm", nValue); root["result"][ii]["Data"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; int airquality = nValue; if (airquality < 700) root["result"][ii]["Quality"] = "Excellent"; else if (airquality < 900) root["result"][ii]["Quality"] = "Good"; else if (airquality < 1100) root["result"][ii]["Quality"] = "Fair"; else if (airquality < 1600) root["result"][ii]["Quality"] = "Mediocre"; else root["result"][ii]["Quality"] = "Bad"; } else if (dType == pTypeThermostat) { if (dSubType == sTypeThermSetpoint) { bHasTimers = m_sql.HasTimers(sd[0]); double tempCelcius = atof(sValue.c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); sprintf(szTmp, "%.1f", temp); root["result"][ii]["Data"] = szTmp; root["result"][ii]["SetPoint"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "override_mini"; } } else if (dType == pTypeRadiator1) { if (dSubType == sTypeSmartwares) { bHasTimers = m_sql.HasTimers(sd[0]); double tempCelcius = atof(sValue.c_str()); double temp = ConvertTemperature(tempCelcius, tempsign); sprintf(szTmp, "%.1f", temp); root["result"][ii]["Data"] = szTmp; root["result"][ii]["SetPoint"] = szTmp; root["result"][ii]["HaveTimeout"] = false; //this device does not provide feedback, so no timeout! root["result"][ii]["TypeImg"] = "override_mini"; } } else if (dType == pTypeGeneral) { if (dSubType == sTypeVisibility) { float vis = static_cast<float>(atof(sValue.c_str())); if (metertype == 0) { sprintf(szTmp, "%.1f km", vis); } else { sprintf(szTmp, "%.1f mi", vis*0.6214f); } root["result"][ii]["Data"] = szTmp; root["result"][ii]["Visibility"] = atof(sValue.c_str()); root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "visibility"; root["result"][ii]["SwitchTypeVal"] = metertype; } else if (dSubType == sTypeDistance) { float vis = static_cast<float>(atof(sValue.c_str())); if (metertype == 0) { sprintf(szTmp, "%.1f cm", vis); } else { sprintf(szTmp, "%.1f in", vis*0.6214f); } root["result"][ii]["Data"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "visibility"; root["result"][ii]["SwitchTypeVal"] = metertype; } else if (dSubType == sTypeSolarRadiation) { float radiation = static_cast<float>(atof(sValue.c_str())); sprintf(szTmp, "%.1f Watt/m2", radiation); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Radiation"] = atof(sValue.c_str()); root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "radiation"; root["result"][ii]["SwitchTypeVal"] = metertype; } else if (dSubType == sTypeSoilMoisture) { sprintf(szTmp, "%d cb", nValue); root["result"][ii]["Data"] = szTmp; root["result"][ii]["Desc"] = Get_Moisture_Desc(nValue); root["result"][ii]["TypeImg"] = "moisture"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["SwitchTypeVal"] = metertype; } else if (dSubType == sTypeLeafWetness) { sprintf(szTmp, "%d", nValue); root["result"][ii]["Data"] = szTmp; root["result"][ii]["TypeImg"] = "leaf"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["SwitchTypeVal"] = metertype; } else if (dSubType == sTypeSystemTemp) { double tvalue = ConvertTemperature(atof(sValue.c_str()), tempsign); root["result"][ii]["Temp"] = tvalue; sprintf(szData, "%.1f %c", tvalue, tempsign); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Image"] = "Computer"; root["result"][ii]["TypeImg"] = "temperature"; root["result"][ii]["Type"] = "temperature"; _tTrendCalculator::_eTendencyType tstate = _tTrendCalculator::_eTendencyType::TENDENCY_UNKNOWN; uint64_t tID = ((uint64_t)(hardwareID & 0x7FFFFFFF) << 32) | (devIdx & 0x7FFFFFFF); if (m_mainworker.m_trend_calculator.find(tID) != m_mainworker.m_trend_calculator.end()) { tstate = m_mainworker.m_trend_calculator[tID].m_state; } root["result"][ii]["trend"] = (int)tstate; } else if (dSubType == sTypePercentage) { sprintf(szData, "%g%%", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Image"] = "Computer"; root["result"][ii]["TypeImg"] = "hardware"; } else if (dSubType == sTypeWaterflow) { sprintf(szData, "%g l/min", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Image"] = "Moisture"; root["result"][ii]["TypeImg"] = "moisture"; } else if (dSubType == sTypeCustom) { std::string szAxesLabel = ""; int SensorType = 1; std::vector<std::string> sResults; StringSplit(sOptions, ";", sResults); if (sResults.size() == 2) { SensorType = atoi(sResults[0].c_str()); szAxesLabel = sResults[1]; } sprintf(szData, "%g %s", atof(sValue.c_str()), szAxesLabel.c_str()); root["result"][ii]["Data"] = szData; root["result"][ii]["SensorType"] = SensorType; root["result"][ii]["SensorUnit"] = szAxesLabel; root["result"][ii]["HaveTimeout"] = bHaveTimeout; std::string IconFile = "Custom"; if (CustomImage != 0) { std::map<int, int>::const_iterator ittIcon = m_custom_light_icons_lookup.find(CustomImage); if (ittIcon != m_custom_light_icons_lookup.end()) { IconFile = m_custom_light_icons[ittIcon->second].RootFile; } } root["result"][ii]["Image"] = IconFile; root["result"][ii]["TypeImg"] = IconFile; } else if (dSubType == sTypeFan) { sprintf(szData, "%d RPM", atoi(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Image"] = "Fan"; root["result"][ii]["TypeImg"] = "Fan"; } else if (dSubType == sTypeSoundLevel) { sprintf(szData, "%d dB", atoi(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "Speaker"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dSubType == sTypeVoltage) { sprintf(szData, "%g V", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "current"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Voltage"] = atof(sValue.c_str()); } else if (dSubType == sTypeCurrent) { sprintf(szData, "%g A", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "current"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Current"] = atof(sValue.c_str()); } else if (dSubType == sTypeTextStatus) { root["result"][ii]["Data"] = sValue; root["result"][ii]["TypeImg"] = "text"; root["result"][ii]["HaveTimeout"] = false; root["result"][ii]["ShowNotifications"] = false; } else if (dSubType == sTypeAlert) { if (nValue > 4) nValue = 4; sprintf(szData, "Level: %d", nValue); root["result"][ii]["Data"] = szData; if (!sValue.empty()) root["result"][ii]["Data"] = sValue; else root["result"][ii]["Data"] = Get_Alert_Desc(nValue); root["result"][ii]["TypeImg"] = "Alert"; root["result"][ii]["Level"] = nValue; root["result"][ii]["HaveTimeout"] = false; } else if (dSubType == sTypePressure) { sprintf(szData, "%.1f Bar", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "gauge"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["Pressure"] = atof(sValue.c_str()); } else if (dSubType == sTypeBaro) { std::vector<std::string> tstrarray; StringSplit(sValue, ";", tstrarray); if (tstrarray.empty()) continue; sprintf(szData, "%g hPa", atof(tstrarray[0].c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "gauge"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; if (tstrarray.size() > 1) { root["result"][ii]["Barometer"] = atof(tstrarray[0].c_str()); int forecast = atoi(tstrarray[1].c_str()); root["result"][ii]["Forecast"] = forecast; root["result"][ii]["ForecastStr"] = BMP_Forecast_Desc(forecast); } } else if (dSubType == sTypeZWaveClock) { std::vector<std::string> tstrarray; StringSplit(sValue, ";", tstrarray); int day = 0; int hour = 0; int minute = 0; if (tstrarray.size() == 3) { day = atoi(tstrarray[0].c_str()); hour = atoi(tstrarray[1].c_str()); minute = atoi(tstrarray[2].c_str()); } sprintf(szData, "%s %02d:%02d", ZWave_Clock_Days(day), hour, minute); root["result"][ii]["DayTime"] = sValue; root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["TypeImg"] = "clock"; } else if (dSubType == sTypeZWaveThermostatMode) { strcpy(szData, ""); root["result"][ii]["Mode"] = nValue; root["result"][ii]["TypeImg"] = "mode"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; std::string modes = ""; #ifdef WITH_OPENZWAVE if (pHardware) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; std::vector<std::string> vmodes = pZWave->GetSupportedThermostatModes(ID); int smode = 0; char szTmp[200]; for (const auto & itt : vmodes) { sprintf(szTmp, "%d;%s;", smode, itt.c_str()); modes += szTmp; smode++; } if (!vmodes.empty()) { if (nValue < (int)vmodes.size()) { sprintf(szData, "%s", vmodes[nValue].c_str()); } } } } #endif root["result"][ii]["Data"] = szData; root["result"][ii]["Modes"] = modes; } else if (dSubType == sTypeZWaveThermostatFanMode) { sprintf(szData, "%s", ZWave_Thermostat_Fan_Modes[nValue]); root["result"][ii]["Data"] = szData; root["result"][ii]["Mode"] = nValue; root["result"][ii]["TypeImg"] = "mode"; root["result"][ii]["HaveTimeout"] = bHaveTimeout; bool bAddedSupportedModes = false; std::string modes = ""; #ifdef WITH_OPENZWAVE if (pHardware) { if (pHardware->HwdType == HTYPE_OpenZWave) { COpenZWave *pZWave = reinterpret_cast<COpenZWave*>(pHardware); unsigned long ID; std::stringstream s_strid; s_strid << std::hex << sd[1]; s_strid >> ID; modes = pZWave->GetSupportedThermostatFanModes(ID); bAddedSupportedModes = !modes.empty(); } } #endif if (!bAddedSupportedModes) { int smode = 0; while (ZWave_Thermostat_Fan_Modes[smode] != NULL) { sprintf(szTmp, "%d;%s;", smode, ZWave_Thermostat_Fan_Modes[smode]); modes += szTmp; smode++; } } root["result"][ii]["Modes"] = modes; } else if (dSubType == sTypeZWaveAlarm) { sprintf(szData, "Event: 0x%02X (%d)", nValue, nValue); root["result"][ii]["Data"] = szData; root["result"][ii]["TypeImg"] = "Alert"; root["result"][ii]["Level"] = nValue; root["result"][ii]["HaveTimeout"] = false; } } else if (dType == pTypeLux) { sprintf(szTmp, "%.0f Lux", atof(sValue.c_str())); root["result"][ii]["Data"] = szTmp; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dType == pTypeWEIGHT) { sprintf(szTmp, "%g %s", m_sql.m_weightscale * atof(sValue.c_str()), m_sql.m_weightsign.c_str()); root["result"][ii]["Data"] = szTmp; root["result"][ii]["HaveTimeout"] = false; } else if (dType == pTypeUsage) { if (dSubType == sTypeElectric) { sprintf(szData, "%g Watt", atof(sValue.c_str())); root["result"][ii]["Data"] = szData; } else { root["result"][ii]["Data"] = sValue; } root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dType == pTypeRFXSensor) { switch (dSubType) { case sTypeRFXSensorAD: sprintf(szData, "%d mV", atoi(sValue.c_str())); root["result"][ii]["TypeImg"] = "current"; break; case sTypeRFXSensorVolt: sprintf(szData, "%d mV", atoi(sValue.c_str())); root["result"][ii]["TypeImg"] = "current"; break; } root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } else if (dType == pTypeRego6XXValue) { switch (dSubType) { case sTypeRego6XXStatus: { std::string lstatus = "On"; if (atoi(sValue.c_str()) == 0) { lstatus = "Off"; } root["result"][ii]["Status"] = lstatus; root["result"][ii]["HaveDimmer"] = false; root["result"][ii]["MaxDimLevel"] = 0; root["result"][ii]["HaveGroupCmd"] = false; root["result"][ii]["TypeImg"] = "utility"; root["result"][ii]["SwitchTypeVal"] = STYPE_OnOff; root["result"][ii]["SwitchType"] = Switch_Type_Desc(STYPE_OnOff); sprintf(szData, "%d", atoi(sValue.c_str())); root["result"][ii]["Data"] = szData; root["result"][ii]["HaveTimeout"] = bHaveTimeout; root["result"][ii]["StrParam1"] = strParam1; root["result"][ii]["StrParam2"] = strParam2; root["result"][ii]["Protected"] = (iProtected != 0); if (CustomImage < static_cast<int>(m_custom_light_icons.size())) root["result"][ii]["Image"] = m_custom_light_icons[CustomImage].RootFile; else root["result"][ii]["Image"] = "Light"; uint64_t camIDX = m_mainworker.m_cameras.IsDevSceneInCamera(0, sd[0]); root["result"][ii]["UsedByCamera"] = (camIDX != 0) ? true : false; if (camIDX != 0) { std::stringstream scidx; scidx << camIDX; root["result"][ii]["CameraIdx"] = scidx.str(); } root["result"][ii]["Level"] = 0; root["result"][ii]["LevelInt"] = atoi(sValue.c_str()); } break; case sTypeRego6XXCounter: { time_t now = mytime(NULL); struct tm ltime; localtime_r(&now, &ltime); char szDate[40]; sprintf(szDate, "%04d-%02d-%02d", ltime.tm_year + 1900, ltime.tm_mon + 1, ltime.tm_mday); std::vector<std::vector<std::string> > result2; strcpy(szTmp, "0"); result2 = m_sql.safe_query("SELECT MIN(Value), MAX(Value) FROM Meter WHERE (DeviceRowID='%q' AND Date>='%q')", sd[0].c_str(), szDate); if (!result2.empty()) { std::vector<std::string> sd2 = result2[0]; unsigned long long total_min = std::strtoull(sd2[0].c_str(), nullptr, 10); unsigned long long total_max = std::strtoull(sd2[1].c_str(), nullptr, 10); unsigned long long total_real; total_real = total_max - total_min; sprintf(szTmp, "%llu", total_real); } root["result"][ii]["SwitchTypeVal"] = MTYPE_COUNTER; root["result"][ii]["Counter"] = sValue; root["result"][ii]["CounterToday"] = szTmp; root["result"][ii]["Data"] = sValue; root["result"][ii]["HaveTimeout"] = bHaveTimeout; } break; } } #ifdef ENABLE_PYTHON if (pHardware != NULL) { if (pHardware->HwdType == HTYPE_PythonPlugin) { Plugins::CPlugin *pPlugin = (Plugins::CPlugin*)pHardware; bHaveTimeout = pPlugin->HasNodeFailed(atoi(sd[2].c_str())); root["result"][ii]["HaveTimeout"] = bHaveTimeout; } } #endif root["result"][ii]["Timers"] = (bHasTimers == true) ? "true" : "false"; ii++; } } } Commit Message: Fixed possible SQL Injection Vulnerability (Thanks to Fabio Carretto!) CWE ID: CWE-89 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } Commit Message: Set pixel cache to undefined if any resource limit is exceeded 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 ManifestUmaUtil::FetchFailed(FetchFailureReason reason) { ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT; switch (reason) { case FETCH_EMPTY_URL: fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL; break; case FETCH_UNSPECIFIED_REASON: fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED; break; } DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult, fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID: Target: 1 Example 2: Code: static unsigned long mem_cgroup_recursive_stat(struct mem_cgroup *memcg, enum mem_cgroup_stat_index idx) { struct mem_cgroup *iter; long val = 0; /* Per-cpu values can be negative, use a signed accumulator */ for_each_mem_cgroup_tree(iter, memcg) val += mem_cgroup_read_stat(iter, idx); if (val < 0) /* race ? */ val = 0; return val; } 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: chpass_principal3_2_svc(chpass3_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_chpass_principal_3((void *)handle, arg->princ, arg->keepold, arg->n_ks_tuple, arg->ks_tuple, arg->pass); } else { log_unauth("kadm5_chpass_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if(ret.code != KADM5_AUTH_CHANGEPW) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_chpass_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119 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 i8042_start(struct serio *serio) { struct i8042_port *port = serio->port_data; port->exists = true; mb(); return 0; } Commit Message: Input: i8042 - fix crash at boot time The driver checks port->exists twice in i8042_interrupt(), first when trying to assign temporary "serio" variable, and second time when deciding whether it should call serio_interrupt(). The value of port->exists may change between the 2 checks, and we may end up calling serio_interrupt() with a NULL pointer: BUG: unable to handle kernel NULL pointer dereference at 0000000000000050 IP: [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 PGD 0 Oops: 0002 [#1] SMP last sysfs file: CPU 0 Modules linked in: Pid: 1, comm: swapper Not tainted 2.6.32-358.el6.x86_64 #1 QEMU Standard PC (i440FX + PIIX, 1996) RIP: 0010:[<ffffffff8150feaf>] [<ffffffff8150feaf>] _spin_lock_irqsave+0x1f/0x40 RSP: 0018:ffff880028203cc0 EFLAGS: 00010082 RAX: 0000000000010000 RBX: 0000000000000000 RCX: 0000000000000000 RDX: 0000000000000282 RSI: 0000000000000098 RDI: 0000000000000050 RBP: ffff880028203cc0 R08: ffff88013e79c000 R09: ffff880028203ee0 R10: 0000000000000298 R11: 0000000000000282 R12: 0000000000000050 R13: 0000000000000000 R14: 0000000000000000 R15: 0000000000000098 FS: 0000000000000000(0000) GS:ffff880028200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b CR2: 0000000000000050 CR3: 0000000001a85000 CR4: 00000000001407f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process swapper (pid: 1, threadinfo ffff88013e79c000, task ffff88013e79b500) Stack: ffff880028203d00 ffffffff813de186 ffffffffffffff02 0000000000000000 <d> 0000000000000000 0000000000000000 0000000000000000 0000000000000098 <d> ffff880028203d70 ffffffff813e0162 ffff880028203d20 ffffffff8103b8ac Call Trace: <IRQ> [<ffffffff813de186>] serio_interrupt+0x36/0xa0 [<ffffffff813e0162>] i8042_interrupt+0x132/0x3a0 [<ffffffff8103b8ac>] ? kvm_clock_read+0x1c/0x20 [<ffffffff8103b8b9>] ? kvm_clock_get_cycles+0x9/0x10 [<ffffffff810e1640>] handle_IRQ_event+0x60/0x170 [<ffffffff8103b154>] ? kvm_guest_apic_eoi_write+0x44/0x50 [<ffffffff810e3d8e>] handle_edge_irq+0xde/0x180 [<ffffffff8100de89>] handle_irq+0x49/0xa0 [<ffffffff81516c8c>] do_IRQ+0x6c/0xf0 [<ffffffff8100b9d3>] ret_from_intr+0x0/0x11 [<ffffffff81076f63>] ? __do_softirq+0x73/0x1e0 [<ffffffff8109b75b>] ? hrtimer_interrupt+0x14b/0x260 [<ffffffff8100c1cc>] ? call_softirq+0x1c/0x30 [<ffffffff8100de05>] ? do_softirq+0x65/0xa0 [<ffffffff81076d95>] ? irq_exit+0x85/0x90 [<ffffffff81516d80>] ? smp_apic_timer_interrupt+0x70/0x9b [<ffffffff8100bb93>] ? apic_timer_interrupt+0x13/0x20 To avoid the issue let's change the second check to test whether serio is NULL or not. Also, let's take i8042_lock in i8042_start() and i8042_stop() instead of trying to be overly smart and using memory barriers. Signed-off-by: Chen Hong <[email protected]> [dtor: take lock in i8042_start()/i8042_stop()] Cc: [email protected] Signed-off-by: Dmitry Torokhov <[email protected]> CWE ID: CWE-476 Target: 1 Example 2: Code: void Document::ReportFeaturePolicyViolation( mojom::FeaturePolicyFeature feature, mojom::FeaturePolicyDisposition disposition, const String& message) const { if (!origin_trials::FeaturePolicyReportingEnabled(this)) return; LocalFrame* frame = GetFrame(); if (!frame) return; const String& feature_name = GetNameForFeature(feature); FeaturePolicyViolationReportBody* body = MakeGarbageCollected<FeaturePolicyViolationReportBody>( feature_name, "Feature policy violation", (disposition == mojom::FeaturePolicyDisposition::kReport ? "report" : "enforce"), SourceLocation::Capture()); Report* report = MakeGarbageCollected<Report>("feature-policy-violation", Url().GetString(), body); ReportingContext::From(this)->QueueReport(report); bool is_null; int line_number = body->lineNumber(is_null); line_number = is_null ? 0 : line_number; int column_number = body->columnNumber(is_null); column_number = is_null ? 0 : column_number; frame->GetReportingService()->QueueFeaturePolicyViolationReport( Url(), feature_name, (disposition == mojom::FeaturePolicyDisposition::kReport ? "report" : "enforce"), "Feature policy violation", body->sourceFile(), line_number, column_number); if (disposition == mojom::FeaturePolicyDisposition::kEnforce) { frame->Console().AddMessage(ConsoleMessage::Create( kViolationMessageSource, mojom::ConsoleMessageLevel::kError, (message.IsEmpty() ? ("Feature policy violation: " + feature_name + " is not allowed in this document.") : message))); } } Commit Message: Cleanup and remove dead code in SetFocusedElement This early-out was added in: https://crrev.com/ce8ea3446283965c7eabab592cbffe223b1cf2bc Back then, we applied fragment focus in LayoutUpdated() which could cause this issue. This got cleaned up in: https://crrev.com/45236fd563e9df53dc45579be1f3d0b4784885a2 so that focus is no longer applied after layout. +Cleanup: Goto considered harmful Bug: 795381 Change-Id: Ifeb4d2e03e872fd48cca6720b1d4de36ad1ecbb7 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1524417 Commit-Queue: David Bokan <[email protected]> Reviewed-by: Stefan Zager <[email protected]> Cr-Commit-Position: refs/heads/master@{#641101} CWE ID: CWE-416 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: cib_remote_msg(gpointer data) { const char *value = NULL; xmlNode *command = NULL; cib_client_t *client = data; crm_trace("%s callback", client->encrypted ? "secure" : "clear-text"); command = crm_recv_remote_msg(client->session, client->encrypted); if (command == NULL) { return -1; } value = crm_element_name(command); if (safe_str_neq(value, "cib_command")) { crm_log_xml_trace(command, "Bad command: "); goto bail; } if (client->name == NULL) { value = crm_element_value(command, F_CLIENTNAME); if (value == NULL) { client->name = strdup(client->id); } else { client->name = strdup(value); } } if (client->callback_id == NULL) { value = crm_element_value(command, F_CIB_CALLBACK_TOKEN); if (value != NULL) { client->callback_id = strdup(value); crm_trace("Callback channel for %s is %s", client->id, client->callback_id); } else { client->callback_id = strdup(client->id); } } /* unset dangerous options */ xml_remove_prop(command, F_ORIG); xml_remove_prop(command, F_CIB_HOST); xml_remove_prop(command, F_CIB_GLOBAL_UPDATE); crm_xml_add(command, F_TYPE, T_CIB); crm_xml_add(command, F_CIB_CLIENTID, client->id); crm_xml_add(command, F_CIB_CLIENTNAME, client->name); #if ENABLE_ACL crm_xml_add(command, F_CIB_USER, client->user); #endif if (crm_element_value(command, F_CIB_CALLID) == NULL) { char *call_uuid = crm_generate_uuid(); /* fix the command */ crm_xml_add(command, F_CIB_CALLID, call_uuid); free(call_uuid); } if (crm_element_value(command, F_CIB_CALLOPTS) == NULL) { crm_xml_add_int(command, F_CIB_CALLOPTS, 0); } crm_log_xml_trace(command, "Remote command: "); cib_common_callback_worker(0, 0, command, client, TRUE); bail: free_xml(command); command = NULL; return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. 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 SaveCardBubbleControllerImpl::ReshowBubble() { is_reshow_ = true; AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); ShowBubble(); } Commit Message: [autofill] Avoid duplicate instances of the SaveCardBubble. autofill::SaveCardBubbleControllerImpl::ShowBubble() expects (via DCHECK) to only be called when the save card bubble is not already visible. This constraint is violated if the user clicks multiple times on a submit button. If the underlying page goes away, the last SaveCardBubbleView created by the controller will be automatically cleaned up, but any others are left visible on the screen... holding a refence to a possibly-deleted controller. This CL early exits the ShowBubbleFor*** and ReshowBubble logic if the bubble is already visible. BUG=708819 Review-Url: https://codereview.chromium.org/2862933002 Cr-Commit-Position: refs/heads/master@{#469768} CWE ID: CWE-416 Target: 1 Example 2: Code: static std::string FixupPath(const std::string& text) { DCHECK(!text.empty()); FilePath::StringType filename; #if defined(OS_WIN) FilePath input_path(UTF8ToWide(text)); PrepareStringForFileOps(input_path, &filename); if (filename.length() > 1 && filename[1] == '|') filename[1] = ':'; #elif defined(OS_POSIX) FilePath input_path(text); PrepareStringForFileOps(input_path, &filename); if (filename.length() > 0 && filename[0] == '~') filename = FixupHomedir(filename); #endif GURL file_url = net::FilePathToFileURL(FilePath(filename)); if (file_url.is_valid()) { return UTF16ToUTF8(net::FormatUrl(file_url, std::string(), net::kFormatUrlOmitUsernamePassword, UnescapeRule::NORMAL, NULL, NULL, NULL)); } return text; } Commit Message: Be a little more careful whether something is an URL or a file path. BUG=72492 Review URL: http://codereview.chromium.org/7572046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@95731 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __init video_setup(char *options) { int i, global = 0; if (!options || !*options) global = 1; if (!global && !strncmp(options, "ofonly", 6)) { ofonly = 1; global = 1; } if (!global && !strchr(options, ':')) { fb_mode_option = options; global = 1; } if (!global) { for (i = 0; i < FB_MAX; i++) { if (video_options[i] == NULL) { video_options[i] = options; break; } } } return 1; } Commit Message: vm: convert fb_mmap to vm_iomap_memory() helper This is my example conversion of a few existing mmap users. The fb_mmap() case is a good example because it is a bit more complicated than some: fb_mmap() mmaps one of two different memory areas depending on the page offset of the mmap (but happily there is never any mixing of the two, so the helper function still works). Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: virtual void AddObserver(Observer* observer) { if (!observers_.size()) { observer->FirstObserverIsAdded(this); } observers_.AddObserver(observer); } 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 queue_del(struct queue *q) { q->q_prev->q_next = q->q_next; q->q_next->q_prev = q->q_prev; } Commit Message: OSdep: Fixed segmentation fault that happens with a malicious server sending a negative length (Closes #16 on GitHub). git-svn-id: http://svn.aircrack-ng.org/trunk@2419 28c6078b-6c39-48e3-add9-af49d547ecab CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void PasswordStoreLoginsChangedObserver::IndicateError( const std::string& error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (automation_) AutomationJSONReply(automation_, reply_message_.release()).SendError(error); Release(); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> fooCallback(const v8::Arguments& args) { INC_STATS("DOM.Float64Array.foo"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); Float64Array* imp = V8Float64Array::toNative(args.Holder()); EXCEPTION_BLOCK(Float32Array*, array, V8Float32Array::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8Float32Array::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); return toV8(imp->foo(array), args.GetIsolate()); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: static int load_balance(int this_cpu, struct rq *this_rq, struct sched_domain *sd, enum cpu_idle_type idle, int *continue_balancing) { int ld_moved, cur_ld_moved, active_balance = 0; struct sched_domain *sd_parent = sd->parent; struct sched_group *group; struct rq *busiest; struct rq_flags rf; struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); struct lb_env env = { .sd = sd, .dst_cpu = this_cpu, .dst_rq = this_rq, .dst_grpmask = sched_group_span(sd->groups), .idle = idle, .loop_break = sched_nr_migrate_break, .cpus = cpus, .fbq_type = all, .tasks = LIST_HEAD_INIT(env.tasks), }; cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); schedstat_inc(sd->lb_count[idle]); redo: if (!should_we_balance(&env)) { *continue_balancing = 0; goto out_balanced; } group = find_busiest_group(&env); if (!group) { schedstat_inc(sd->lb_nobusyg[idle]); goto out_balanced; } busiest = find_busiest_queue(&env, group); if (!busiest) { schedstat_inc(sd->lb_nobusyq[idle]); goto out_balanced; } BUG_ON(busiest == env.dst_rq); schedstat_add(sd->lb_imbalance[idle], env.imbalance); env.src_cpu = busiest->cpu; env.src_rq = busiest; ld_moved = 0; if (busiest->nr_running > 1) { /* * Attempt to move tasks. If find_busiest_group has found * an imbalance but busiest->nr_running <= 1, the group is * still unbalanced. ld_moved simply stays zero, so it is * correctly treated as an imbalance. */ env.flags |= LBF_ALL_PINNED; env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); more_balance: rq_lock_irqsave(busiest, &rf); update_rq_clock(busiest); /* * cur_ld_moved - load moved in current iteration * ld_moved - cumulative load moved across iterations */ cur_ld_moved = detach_tasks(&env); /* * We've detached some tasks from busiest_rq. Every * task is masked "TASK_ON_RQ_MIGRATING", so we can safely * unlock busiest->lock, and we are able to be sure * that nobody can manipulate the tasks in parallel. * See task_rq_lock() family for the details. */ rq_unlock(busiest, &rf); if (cur_ld_moved) { attach_tasks(&env); ld_moved += cur_ld_moved; } local_irq_restore(rf.flags); if (env.flags & LBF_NEED_BREAK) { env.flags &= ~LBF_NEED_BREAK; goto more_balance; } /* * Revisit (affine) tasks on src_cpu that couldn't be moved to * us and move them to an alternate dst_cpu in our sched_group * where they can run. The upper limit on how many times we * iterate on same src_cpu is dependent on number of CPUs in our * sched_group. * * This changes load balance semantics a bit on who can move * load to a given_cpu. In addition to the given_cpu itself * (or a ilb_cpu acting on its behalf where given_cpu is * nohz-idle), we now have balance_cpu in a position to move * load to given_cpu. In rare situations, this may cause * conflicts (balance_cpu and given_cpu/ilb_cpu deciding * _independently_ and at _same_ time to move some load to * given_cpu) causing exceess load to be moved to given_cpu. * This however should not happen so much in practice and * moreover subsequent load balance cycles should correct the * excess load moved. */ if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { /* Prevent to re-select dst_cpu via env's CPUs */ cpumask_clear_cpu(env.dst_cpu, env.cpus); env.dst_rq = cpu_rq(env.new_dst_cpu); env.dst_cpu = env.new_dst_cpu; env.flags &= ~LBF_DST_PINNED; env.loop = 0; env.loop_break = sched_nr_migrate_break; /* * Go back to "more_balance" rather than "redo" since we * need to continue with same src_cpu. */ goto more_balance; } /* * We failed to reach balance because of affinity. */ if (sd_parent) { int *group_imbalance = &sd_parent->groups->sgc->imbalance; if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) *group_imbalance = 1; } /* All tasks on this runqueue were pinned by CPU affinity */ if (unlikely(env.flags & LBF_ALL_PINNED)) { cpumask_clear_cpu(cpu_of(busiest), cpus); /* * Attempting to continue load balancing at the current * sched_domain level only makes sense if there are * active CPUs remaining as possible busiest CPUs to * pull load from which are not contained within the * destination group that is receiving any migrated * load. */ if (!cpumask_subset(cpus, env.dst_grpmask)) { env.loop = 0; env.loop_break = sched_nr_migrate_break; goto redo; } goto out_all_pinned; } } if (!ld_moved) { schedstat_inc(sd->lb_failed[idle]); /* * Increment the failure counter only on periodic balance. * We do not want newidle balance, which can be very * frequent, pollute the failure counter causing * excessive cache_hot migrations and active balances. */ if (idle != CPU_NEWLY_IDLE) sd->nr_balance_failed++; if (need_active_balance(&env)) { unsigned long flags; raw_spin_lock_irqsave(&busiest->lock, flags); /* * Don't kick the active_load_balance_cpu_stop, * if the curr task on busiest CPU can't be * moved to this_cpu: */ if (!cpumask_test_cpu(this_cpu, &busiest->curr->cpus_allowed)) { raw_spin_unlock_irqrestore(&busiest->lock, flags); env.flags |= LBF_ALL_PINNED; goto out_one_pinned; } /* * ->active_balance synchronizes accesses to * ->active_balance_work. Once set, it's cleared * only after active load balance is finished. */ if (!busiest->active_balance) { busiest->active_balance = 1; busiest->push_cpu = this_cpu; active_balance = 1; } raw_spin_unlock_irqrestore(&busiest->lock, flags); if (active_balance) { stop_one_cpu_nowait(cpu_of(busiest), active_load_balance_cpu_stop, busiest, &busiest->active_balance_work); } /* We've kicked active balancing, force task migration. */ sd->nr_balance_failed = sd->cache_nice_tries+1; } } else sd->nr_balance_failed = 0; if (likely(!active_balance)) { /* We were unbalanced, so reset the balancing interval */ sd->balance_interval = sd->min_interval; } else { /* * If we've begun active balancing, start to back off. This * case may not be covered by the all_pinned logic if there * is only 1 task on the busy runqueue (because we don't call * detach_tasks). */ if (sd->balance_interval < sd->max_interval) sd->balance_interval *= 2; } goto out; out_balanced: /* * We reach balance although we may have faced some affinity * constraints. Clear the imbalance flag if it was set. */ if (sd_parent) { int *group_imbalance = &sd_parent->groups->sgc->imbalance; if (*group_imbalance) *group_imbalance = 0; } out_all_pinned: /* * We reach balance because all tasks are pinned at this level so * we can't migrate them. Let the imbalance flag set so parent level * can try to migrate them. */ schedstat_inc(sd->lb_balanced[idle]); sd->nr_balance_failed = 0; out_one_pinned: ld_moved = 0; /* * idle_balance() disregards balance intervals, so we could repeatedly * reach this code, which would lead to balance_interval skyrocketting * in a short amount of time. Skip the balance_interval increase logic * to avoid that. */ if (env.idle == CPU_NEWLY_IDLE) goto out; /* tune up the balancing interval */ if ((env.flags & LBF_ALL_PINNED && sd->balance_interval < MAX_PINNED_INTERVAL) || sd->balance_interval < sd->max_interval) sd->balance_interval *= 2; out: return ld_moved; } Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the scheduler under high loads, starting at around the v4.18 time frame, and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list manipulation. Do a (manual) revert of: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") It turns out that the list_del_leaf_cfs_rq() introduced by this commit is a surprising property that was not considered in followup commits such as: 9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list") As Vincent Guittot explains: "I think that there is a bigger problem with commit a9e7f6544b9c and cfs_rq throttling: Let take the example of the following topology TG2 --> TG1 --> root: 1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1 cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in one path because it has never been used and can't be throttled so tmp_alone_branch will point to leaf_cfs_rq_list at the end. 2) Then TG1 is throttled 3) and we add TG3 as a new child of TG1. 4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1 cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list. With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list. So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1 cfs_rq is removed from the list. Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list but tmp_alone_branch still points to TG3 cfs_rq because its throttled parent can't be enqueued when the lock is released. tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should. So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch points on another TG cfs_rq, the next TG cfs_rq that will be added, will be linked outside rq->leaf_cfs_rq_list - which is bad. In addition, we can break the ordering of the cfs_rq in rq->leaf_cfs_rq_list but this ordering is used to update and propagate the update from leaf down to root." Instead of trying to work through all these cases and trying to reproduce the very high loads that produced the lockup to begin with, simplify the code temporarily by reverting a9e7f6544b9c - which change was clearly not thought through completely. This (hopefully) gives us a kernel that doesn't lock up so people can continue to enjoy their holidays without worrying about regressions. ;-) [ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ] Analyzed-by: Xie XiuQi <[email protected]> Analyzed-by: Vincent Guittot <[email protected]> Reported-by: Zhipeng Xie <[email protected]> Reported-by: Sargun Dhillon <[email protected]> Reported-by: Xie XiuQi <[email protected]> Tested-by: Zhipeng Xie <[email protected]> Tested-by: Sargun Dhillon <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Vincent Guittot <[email protected]> Cc: <[email protected]> # v4.13+ Cc: Bin Li <[email protected]> Cc: Mike Galbraith <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: Tejun Heo <[email protected]> Cc: Thomas Gleixner <[email protected]> Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path") Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-400 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static enum TIFFReadDirEntryErr TIFFReadDirEntryCheckRangeLongSshort(int16 value) { if (value<0) return(TIFFReadDirEntryErrRange); else return(TIFFReadDirEntryErrOk); } Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip), instead of a logic based on the total size of data. Which is faulty is the total size of data is not sufficient to fill the whole image, and thus results in reading outside of the StripByCounts/StripOffsets arrays when using TIFFReadScanline(). Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608. * libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since the above change is a better fix that makes it unnecessary. CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } Commit Message: l2tp: fix info leak in l2tp_ip6_recvmsg() The L2TP code for IPv6 fails to initialize the l2tp_conn_id member of struct sockaddr_l2tpip6 and therefore leaks four bytes kernel stack in l2tp_ip6_recvmsg() in case msg_name is set. Initialize l2tp_conn_id with 0 to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void) { return NULL; } Commit Message: CWE ID: CWE-310 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static zend_object_value php_create_incomplete_object(zend_class_entry *class_type TSRMLS_DC) { zend_object *object; zend_object_value value; value = zend_objects_new(&object, class_type TSRMLS_CC); value.handlers = &php_incomplete_object_handlers; object_properties_init(object, class_type); return value; } 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: int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr, struct usb_interface *intf, u8 *buffer, int buflen) { /* duplicates are ignored */ struct usb_cdc_union_desc *union_header = NULL; /* duplicates are not tolerated */ struct usb_cdc_header_desc *header = NULL; struct usb_cdc_ether_desc *ether = NULL; struct usb_cdc_mdlm_detail_desc *detail = NULL; struct usb_cdc_mdlm_desc *desc = NULL; unsigned int elength; int cnt = 0; memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header)); hdr->phonet_magic_present = false; while (buflen > 0) { elength = buffer[0]; if (!elength) { dev_err(&intf->dev, "skipping garbage byte\n"); elength = 1; goto next_desc; } if (buffer[1] != USB_DT_CS_INTERFACE) { dev_err(&intf->dev, "skipping garbage\n"); goto next_desc; } switch (buffer[2]) { case USB_CDC_UNION_TYPE: /* we've found it */ if (elength < sizeof(struct usb_cdc_union_desc)) goto next_desc; if (union_header) { dev_err(&intf->dev, "More than one union descriptor, skipping ...\n"); goto next_desc; } union_header = (struct usb_cdc_union_desc *)buffer; break; case USB_CDC_COUNTRY_TYPE: if (elength < sizeof(struct usb_cdc_country_functional_desc)) goto next_desc; hdr->usb_cdc_country_functional_desc = (struct usb_cdc_country_functional_desc *)buffer; break; case USB_CDC_HEADER_TYPE: if (elength != sizeof(struct usb_cdc_header_desc)) goto next_desc; if (header) return -EINVAL; header = (struct usb_cdc_header_desc *)buffer; break; case USB_CDC_ACM_TYPE: if (elength < sizeof(struct usb_cdc_acm_descriptor)) goto next_desc; hdr->usb_cdc_acm_descriptor = (struct usb_cdc_acm_descriptor *)buffer; break; case USB_CDC_ETHERNET_TYPE: if (elength != sizeof(struct usb_cdc_ether_desc)) goto next_desc; if (ether) return -EINVAL; ether = (struct usb_cdc_ether_desc *)buffer; break; case USB_CDC_CALL_MANAGEMENT_TYPE: if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor)) goto next_desc; hdr->usb_cdc_call_mgmt_descriptor = (struct usb_cdc_call_mgmt_descriptor *)buffer; break; case USB_CDC_DMM_TYPE: if (elength < sizeof(struct usb_cdc_dmm_desc)) goto next_desc; hdr->usb_cdc_dmm_desc = (struct usb_cdc_dmm_desc *)buffer; break; case USB_CDC_MDLM_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_desc *)) goto next_desc; if (desc) return -EINVAL; desc = (struct usb_cdc_mdlm_desc *)buffer; break; case USB_CDC_MDLM_DETAIL_TYPE: if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *)) goto next_desc; if (detail) return -EINVAL; detail = (struct usb_cdc_mdlm_detail_desc *)buffer; break; case USB_CDC_NCM_TYPE: if (elength < sizeof(struct usb_cdc_ncm_desc)) goto next_desc; hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer; break; case USB_CDC_MBIM_TYPE: if (elength < sizeof(struct usb_cdc_mbim_desc)) goto next_desc; hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer; break; case USB_CDC_MBIM_EXTENDED_TYPE: if (elength < sizeof(struct usb_cdc_mbim_extended_desc)) break; hdr->usb_cdc_mbim_extended_desc = (struct usb_cdc_mbim_extended_desc *)buffer; break; case CDC_PHONET_MAGIC_NUMBER: hdr->phonet_magic_present = true; break; default: /* * there are LOTS more CDC descriptors that * could legitimately be found here. */ dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n", buffer[2], elength); goto next_desc; } cnt++; next_desc: buflen -= elength; buffer += elength; } hdr->usb_cdc_union_desc = union_header; hdr->usb_cdc_header_desc = header; hdr->usb_cdc_mdlm_detail_desc = detail; hdr->usb_cdc_mdlm_desc = desc; hdr->usb_cdc_ether_desc = ether; return cnt; } Commit Message: USB: core: harden cdc_parse_cdc_header Andrey Konovalov reported a possible out-of-bounds problem for the cdc_parse_cdc_header function. He writes: It looks like cdc_parse_cdc_header() doesn't validate buflen before accessing buffer[1], buffer[2] and so on. The only check present is while (buflen > 0). So fix this issue up by properly validating the buffer length matches what the descriptor says it is. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: bool GLES2DecoderImpl::BoundFramebufferHasStencilAttachment() { Framebuffer* framebuffer = GetBoundDrawFramebuffer(); if (framebuffer) { return framebuffer->HasStencilAttachment(); } if (offscreen_target_frame_buffer_.get()) { return offscreen_target_stencil_format_ != 0 || offscreen_target_depth_format_ == GL_DEPTH24_STENCIL8; } return back_buffer_has_stencil_; } 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: void LocalFrameClientImpl::AbortClientNavigation() { if (web_frame_->Client()) web_frame_->Client()->AbortClientNavigation(); } Commit Message: Prevent renderer initiated back navigation to cancel a browser one. Renderer initiated back/forward navigations must not be able to cancel ongoing browser initiated navigation if they are not user initiated. Note: 'normal' renderer initiated navigation uses the FrameHost::BeginNavigation() path. A code similar to this patch is done in NavigatorImpl::OnBeginNavigation(). Test: ----- Added: NavigationBrowserTest. * HistoryBackInBeforeUnload * HistoryBackInBeforeUnloadAfterSetTimeout * HistoryBackCancelPendingNavigationNoUserGesture * HistoryBackCancelPendingNavigationUserGesture Fixed: * (WPT) .../the-history-interface/traverse_the_history_2.html * (WPT) .../the-history-interface/traverse_the_history_3.html * (WPT) .../the-history-interface/traverse_the_history_4.html * (WPT) .../the-history-interface/traverse_the_history_5.html Bug: 879965 Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c Reviewed-on: https://chromium-review.googlesource.com/1209744 Commit-Queue: Arthur Sonzogni <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Mustaq Ahmed <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#592823} CWE ID: CWE-254 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 smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = mss->vma; pte_t *pte; spinlock_t *ptl; 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(vma->anon_vma, pmd); } else { smaps_pte_entry(*(pte_t *)pmd, addr, HPAGE_PMD_SIZE, walk); spin_unlock(&walk->mm->page_table_lock); mss->anonymous_thp += HPAGE_PMD_SIZE; return 0; } } else { spin_unlock(&walk->mm->page_table_lock); } /* * The mmap_sem held all the way back in m_start() is what * keeps khugepaged out of here and from collapsing things * in here. */ pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) smaps_pte_entry(*pte, addr, PAGE_SIZE, walk); pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } Commit Message: mm: thp: fix pmd_bad() triggering in code paths holding mmap_sem read mode commit 1a5a9906d4e8d1976b701f889d8f35d54b928f25 upstream. In some cases it may happen that pmd_none_or_clear_bad() is called with the mmap_sem hold in read mode. In those cases the huge page faults can allocate hugepmds under pmd_none_or_clear_bad() and that can trigger a false positive from pmd_bad() that will not like to see a pmd materializing as trans huge. It's not khugepaged causing the problem, khugepaged holds the mmap_sem in write mode (and all those sites must hold the mmap_sem in read mode to prevent pagetables to go away from under them, during code review it seems vm86 mode on 32bit kernels requires that too unless it's restricted to 1 thread per process or UP builds). The race is only with the huge pagefaults that can convert a pmd_none() into a pmd_trans_huge(). Effectively all these pmd_none_or_clear_bad() sites running with mmap_sem in read mode are somewhat speculative with the page faults, and the result is always undefined when they run simultaneously. This is probably why it wasn't common to run into this. For example if the madvise(MADV_DONTNEED) runs zap_page_range() shortly before the page fault, the hugepage will not be zapped, if the page fault runs first it will be zapped. Altering pmd_bad() not to error out if it finds hugepmds won't be enough to fix this, because zap_pmd_range would then proceed to call zap_pte_range (which would be incorrect if the pmd become a pmd_trans_huge()). The simplest way to fix this is to read the pmd in the local stack (regardless of what we read, no need of actual CPU barriers, only compiler barrier needed), and be sure it is not changing under the code that computes its value. Even if the real pmd is changing under the value we hold on the stack, we don't care. If we actually end up in zap_pte_range it means the pmd was not none already and it was not huge, and it can't become huge from under us (khugepaged locking explained above). All we need is to enforce that there is no way anymore that in a code path like below, pmd_trans_huge can be false, but pmd_none_or_clear_bad can run into a hugepmd. The overhead of a barrier() is just a compiler tweak and should not be measurable (I only added it for THP builds). I don't exclude different compiler versions may have prevented the race too by caching the value of *pmd on the stack (that hasn't been verified, but it wouldn't be impossible considering pmd_none_or_clear_bad, pmd_bad, pmd_trans_huge, pmd_none are all inlines and there's no external function called in between pmd_trans_huge and pmd_none_or_clear_bad). if (pmd_trans_huge(*pmd)) { if (next-addr != HPAGE_PMD_SIZE) { VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); split_huge_page_pmd(vma->vm_mm, pmd); } else if (zap_huge_pmd(tlb, vma, pmd, addr)) continue; /* fall through */ } if (pmd_none_or_clear_bad(pmd)) Because this race condition could be exercised without special privileges this was reported in CVE-2012-1179. The race was identified and fully explained by Ulrich who debugged it. I'm quoting his accurate explanation below, for reference. ====== start quote ======= mapcount 0 page_mapcount 1 kernel BUG at mm/huge_memory.c:1384! At some point prior to the panic, a "bad pmd ..." message similar to the following is logged on the console: mm/memory.c:145: bad pmd ffff8800376e1f98(80000000314000e7). The "bad pmd ..." message is logged by pmd_clear_bad() before it clears the page's PMD table entry. 143 void pmd_clear_bad(pmd_t *pmd) 144 { -> 145 pmd_ERROR(*pmd); 146 pmd_clear(pmd); 147 } After the PMD table entry has been cleared, there is an inconsistency between the actual number of PMD table entries that are mapping the page and the page's map count (_mapcount field in struct page). When the page is subsequently reclaimed, __split_huge_page() detects this inconsistency. 1381 if (mapcount != page_mapcount(page)) 1382 printk(KERN_ERR "mapcount %d page_mapcount %d\n", 1383 mapcount, page_mapcount(page)); -> 1384 BUG_ON(mapcount != page_mapcount(page)); The root cause of the problem is a race of two threads in a multithreaded process. Thread B incurs a page fault on a virtual address that has never been accessed (PMD entry is zero) while Thread A is executing an madvise() system call on a virtual address within the same 2 MB (huge page) range. virtual address space .---------------------. | | | | .-|---------------------| | | | | | |<-- B(fault) | | | 2 MB | |/////////////////////|-. huge < |/////////////////////| > A(range) page | |/////////////////////|-' | | | | | | '-|---------------------| | | | | '---------------------' - Thread A is executing an madvise(..., MADV_DONTNEED) system call on the virtual address range "A(range)" shown in the picture. sys_madvise // Acquire the semaphore in shared mode. down_read(&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: int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ) { if( mbedtls_mpi_cmp_mpi( &P->X, &Q->X ) == 0 && mbedtls_mpi_cmp_mpi( &P->Y, &Q->Y ) == 0 && mbedtls_mpi_cmp_mpi( &P->Z, &Q->Z ) == 0 ) { return( 0 ); } return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length) { int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); if (errno == EINTR) { /* retry again */ ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } else { skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } return ret; } 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 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: ext2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size) { struct inode *inode = d_inode(dentry); struct buffer_head *bh = NULL; struct ext2_xattr_entry *entry; char *end; size_t rest = buffer_size; int error; ea_idebug(inode, "buffer=%p, buffer_size=%ld", buffer, (long)buffer_size); down_read(&EXT2_I(inode)->xattr_sem); error = 0; if (!EXT2_I(inode)->i_file_acl) goto cleanup; ea_idebug(inode, "reading block %d", EXT2_I(inode)->i_file_acl); bh = sb_bread(inode->i_sb, EXT2_I(inode)->i_file_acl); error = -EIO; if (!bh) goto cleanup; ea_bdebug(bh, "b_count=%d, refcount=%d", atomic_read(&(bh->b_count)), le32_to_cpu(HDR(bh)->h_refcount)); end = bh->b_data + bh->b_size; if (HDR(bh)->h_magic != cpu_to_le32(EXT2_XATTR_MAGIC) || HDR(bh)->h_blocks != cpu_to_le32(1)) { bad_block: ext2_error(inode->i_sb, "ext2_xattr_list", "inode %ld: bad block %d", inode->i_ino, EXT2_I(inode)->i_file_acl); error = -EIO; goto cleanup; } /* check the on-disk data structure */ entry = FIRST_ENTRY(bh); while (!IS_LAST_ENTRY(entry)) { struct ext2_xattr_entry *next = EXT2_XATTR_NEXT(entry); if ((char *)next >= end) goto bad_block; entry = next; } if (ext2_xattr_cache_insert(bh)) ea_idebug(inode, "cache insert failed"); /* list the attribute names */ for (entry = FIRST_ENTRY(bh); !IS_LAST_ENTRY(entry); entry = EXT2_XATTR_NEXT(entry)) { const struct xattr_handler *handler = ext2_xattr_handler(entry->e_name_index); if (handler && (!handler->list || handler->list(dentry))) { const char *prefix = handler->prefix ?: handler->name; size_t prefix_len = strlen(prefix); size_t size = prefix_len + entry->e_name_len + 1; if (buffer) { if (size > rest) { error = -ERANGE; goto cleanup; } memcpy(buffer, prefix, prefix_len); buffer += prefix_len; memcpy(buffer, entry->e_name, entry->e_name_len); buffer += entry->e_name_len; *buffer++ = 0; } rest -= size; } } error = buffer_size - rest; /* total size */ cleanup: brelse(bh); up_read(&EXT2_I(inode)->xattr_sem); return error; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Target: 1 Example 2: Code: static void CL_Cache_MapChange_f( void ) { cacheIndex++; } 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: htmlParseExternalID(htmlParserCtxtPtr ctxt, xmlChar **publicID) { xmlChar *URI = NULL; if ((UPPER == 'S') && (UPP(1) == 'Y') && (UPP(2) == 'S') && (UPP(3) == 'T') && (UPP(4) == 'E') && (UPP(5) == 'M')) { SKIP(6); if (!IS_BLANK_CH(CUR)) { htmlParseErr(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'SYSTEM'\n", NULL, NULL); } SKIP_BLANKS; URI = htmlParseSystemLiteral(ctxt); if (URI == NULL) { htmlParseErr(ctxt, XML_ERR_URI_REQUIRED, "htmlParseExternalID: SYSTEM, no URI\n", NULL, NULL); } } else if ((UPPER == 'P') && (UPP(1) == 'U') && (UPP(2) == 'B') && (UPP(3) == 'L') && (UPP(4) == 'I') && (UPP(5) == 'C')) { SKIP(6); if (!IS_BLANK_CH(CUR)) { htmlParseErr(ctxt, XML_ERR_SPACE_REQUIRED, "Space required after 'PUBLIC'\n", NULL, NULL); } SKIP_BLANKS; *publicID = htmlParsePubidLiteral(ctxt); if (*publicID == NULL) { htmlParseErr(ctxt, XML_ERR_PUBID_REQUIRED, "htmlParseExternalID: PUBLIC, no Public Identifier\n", NULL, NULL); } SKIP_BLANKS; if ((CUR == '"') || (CUR == '\'')) { URI = htmlParseSystemLiteral(ctxt); } } return(URI); } Commit Message: Roll libxml to 3939178e4cb797417ff033b1e04ab4b038e224d9 Removes a few patches fixed upstream: https://git.gnome.org/browse/libxml2/commit/?id=e26630548e7d138d2c560844c43820b6767251e3 https://git.gnome.org/browse/libxml2/commit/?id=94691dc884d1a8ada39f073408b4bb92fe7fe882 Stops using the NOXXE flag which was reverted upstream: https://git.gnome.org/browse/libxml2/commit/?id=030b1f7a27c22f9237eddca49ec5e620b6258d7d Changes the patch to uri.c to not add limits.h, which is included upstream. Bug: 722079 Change-Id: I4b8449ed33f95de23c54c2cde99970c2df2781ac Reviewed-on: https://chromium-review.googlesource.com/535233 Reviewed-by: Scott Graham <[email protected]> Commit-Queue: Dominic Cooney <[email protected]> Cr-Commit-Position: refs/heads/master@{#480755} CWE ID: CWE-787 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void PropertyTreeManager::SetupRootTransformNode() { cc::TransformTree& transform_tree = property_trees_.transform_tree; transform_tree.clear(); property_trees_.element_id_to_transform_node_index.clear(); cc::TransformNode& transform_node = *transform_tree.Node( transform_tree.Insert(cc::TransformNode(), kRealRootNodeId)); DCHECK_EQ(transform_node.id, kSecondaryRootNodeId); transform_node.source_node_id = transform_node.parent_id; float device_scale_factor = root_layer_->layer_tree_host()->device_scale_factor(); gfx::Transform to_screen; to_screen.Scale(device_scale_factor, device_scale_factor); transform_tree.SetToScreen(kRealRootNodeId, to_screen); gfx::Transform from_screen; bool invertible = to_screen.GetInverse(&from_screen); DCHECK(invertible); transform_tree.SetFromScreen(kRealRootNodeId, from_screen); transform_tree.set_needs_update(true); transform_node_map_.Set(TransformPaintPropertyNode::Root(), transform_node.id); root_layer_->SetTransformTreeIndex(transform_node.id); } 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: 1 Example 2: Code: void HTMLFormElement::removedFrom(ContainerNode* insertionPoint) { if (m_hasElementsAssociatedByParser) { Node& root = NodeTraversal::highestAncestorOrSelf(*this); if (!m_associatedElementsAreDirty) { FormAssociatedElement::List elements(associatedElements()); notifyFormRemovedFromTree(elements, root); } else { FormAssociatedElement::List elements; collectAssociatedElements( NodeTraversal::highestAncestorOrSelf(*insertionPoint), elements); notifyFormRemovedFromTree(elements, root); collectAssociatedElements(root, elements); notifyFormRemovedFromTree(elements, root); } if (!m_imageElementsAreDirty) { HeapVector<Member<HTMLImageElement>> images(imageElements()); notifyFormRemovedFromTree(images, root); } else { HeapVector<Member<HTMLImageElement>> images; collectImageElements( NodeTraversal::highestAncestorOrSelf(*insertionPoint), images); notifyFormRemovedFromTree(images, root); collectImageElements(root, images); notifyFormRemovedFromTree(images, root); } } document().formController().willDeleteForm(this); HTMLElement::removedFrom(insertionPoint); } Commit Message: Enforce form-action CSP even when form.target is present. BUG=630332 Review-Url: https://codereview.chromium.org/2464123004 Cr-Commit-Position: refs/heads/master@{#429922} CWE ID: CWE-19 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: Response StorageHandler::TrackIndexedDBForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::TrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20 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 ftrace_syscall_enter(void *data, struct pt_regs *regs, long id) { struct trace_array *tr = data; struct ftrace_event_file *ftrace_file; struct syscall_trace_enter *entry; struct syscall_metadata *sys_data; struct ring_buffer_event *event; struct ring_buffer *buffer; unsigned long irq_flags; int pc; int syscall_nr; int size; syscall_nr = trace_get_syscall_nr(current, regs); if (syscall_nr < 0) return; /* Here we're inside tp handler's rcu_read_lock_sched (__DO_TRACE) */ ftrace_file = rcu_dereference_sched(tr->enter_syscall_files[syscall_nr]); if (!ftrace_file) return; if (ftrace_trigger_soft_disabled(ftrace_file)) return; sys_data = syscall_nr_to_meta(syscall_nr); if (!sys_data) return; size = sizeof(*entry) + sizeof(unsigned long) * sys_data->nb_args; local_save_flags(irq_flags); pc = preempt_count(); buffer = tr->trace_buffer.buffer; event = trace_buffer_lock_reserve(buffer, sys_data->enter_event->event.type, size, irq_flags, pc); if (!event) return; entry = ring_buffer_event_data(event); entry->nr = syscall_nr; syscall_get_arguments(current, regs, 0, sys_data->nb_args, entry->args); event_trigger_unlock_commit(ftrace_file, buffer, event, entry, irq_flags, pc); } Commit Message: tracing/syscalls: Ignore numbers outside NR_syscalls' range ARM has some private syscalls (for example, set_tls(2)) which lie outside the range of NR_syscalls. If any of these are called while syscall tracing is being performed, out-of-bounds array access will occur in the ftrace and perf sys_{enter,exit} handlers. # trace-cmd record -e raw_syscalls:* true && trace-cmd report ... true-653 [000] 384.675777: sys_enter: NR 192 (0, 1000, 3, 4000022, ffffffff, 0) true-653 [000] 384.675812: sys_exit: NR 192 = 1995915264 true-653 [000] 384.675971: sys_enter: NR 983045 (76f74480, 76f74000, 76f74b28, 76f74480, 76f76f74, 1) true-653 [000] 384.675988: sys_exit: NR 983045 = 0 ... # trace-cmd record -e syscalls:* true [ 17.289329] Unable to handle kernel paging request at virtual address aaaaaace [ 17.289590] pgd = 9e71c000 [ 17.289696] [aaaaaace] *pgd=00000000 [ 17.289985] Internal error: Oops: 5 [#1] PREEMPT SMP ARM [ 17.290169] Modules linked in: [ 17.290391] CPU: 0 PID: 704 Comm: true Not tainted 3.18.0-rc2+ #21 [ 17.290585] task: 9f4dab00 ti: 9e710000 task.ti: 9e710000 [ 17.290747] PC is at ftrace_syscall_enter+0x48/0x1f8 [ 17.290866] LR is at syscall_trace_enter+0x124/0x184 Fix this by ignoring out-of-NR_syscalls-bounds syscall numbers. Commit cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" added the check for less than zero, but it should have also checked for greater than NR_syscalls. Link: http://lkml.kernel.org/p/[email protected] Fixes: cd0980fc8add "tracing: Check invalid syscall nr while tracing syscalls" Cc: [email protected] # 2.6.33+ Signed-off-by: Rabin Vincent <[email protected]> Signed-off-by: Steven Rostedt <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: static void rtt_reset(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct illinois *ca = inet_csk_ca(sk); ca->end_seq = tp->snd_nxt; ca->cnt_rtt = 0; ca->sum_rtt = 0; /* TODO: age max_rtt? */ } Commit Message: net: fix divide by zero in tcp algorithm illinois Reading TCP stats when using TCP Illinois congestion control algorithm can cause a divide by zero kernel oops. The division by zero occur in tcp_illinois_info() at: do_div(t, ca->cnt_rtt); where ca->cnt_rtt can become zero (when rtt_reset is called) Steps to Reproduce: 1. Register tcp_illinois: # sysctl -w net.ipv4.tcp_congestion_control=illinois 2. Monitor internal TCP information via command "ss -i" # watch -d ss -i 3. Establish new TCP conn to machine Either it fails at the initial conn, or else it needs to wait for a loss or a reset. This is only related to reading stats. The function avg_delay() also performs the same divide, but is guarded with a (ca->cnt_rtt > 0) at its calling point in update_params(). Thus, simply fix tcp_illinois_info(). Function tcp_illinois_info() / get_info() is called without socket lock. Thus, eliminate any race condition on ca->cnt_rtt by using a local stack variable. Simply reuse info.tcpv_rttcnt, as its already set to ca->cnt_rtt. Function avg_delay() is not affected by this race condition, as its called with the socket lock. Cc: Petr Matousek <[email protected]> Signed-off-by: Jesper Dangaard Brouer <[email protected]> Acked-by: Eric Dumazet <[email protected]> Acked-by: Stephen Hemminger <[email protected]> Signed-off-by: David S. Miller <[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: bool IsAllowedScript(const Extension* extension, const GURL& url, int tab_id) { return extension->permissions_data()->CanAccessPage(extension, url, tab_id, nullptr); } Commit Message: [Extensions] Restrict tabs.captureVisibleTab() Modify the permissions for tabs.captureVisibleTab(). Instead of just checking for <all_urls> and assuming its safe, do the following: - If the page is a "normal" web page (e.g., http/https), allow the capture if the extension has activeTab granted or <all_urls>. - If the page is a file page (file:///), allow the capture if the extension has file access *and* either of the <all_urls> or activeTab permissions. - If the page is a chrome:// page, allow the capture only if the extension has activeTab granted. Bug: 810220 Change-Id: I1e2f71281e2f331d641ba0e435df10d66d721304 Reviewed-on: https://chromium-review.googlesource.com/981195 Commit-Queue: Devlin <[email protected]> Reviewed-by: Karan Bhatia <[email protected]> Cr-Commit-Position: refs/heads/master@{#548891} CWE ID: CWE-20 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 trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p = key->payload.data[0]; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kfree(datablob); kfree(new_o); return ret; } Commit Message: KEYS: Fix handling of stored error in a negatively instantiated user key If a user key gets negatively instantiated, an error code is cached in the payload area. A negatively instantiated key may be then be positively instantiated by updating it with valid data. However, the ->update key type method must be aware that the error code may be there. The following may be used to trigger the bug in the user key type: keyctl request2 user user "" @u keyctl add user user "a" @u which manifests itself as: BUG: unable to handle kernel paging request at 00000000ffffff8a IP: [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 PGD 7cc30067 PUD 0 Oops: 0002 [#1] SMP Modules linked in: CPU: 3 PID: 2644 Comm: a.out Not tainted 4.3.0+ #49 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS Bochs 01/01/2011 task: ffff88003ddea700 ti: ffff88003dd88000 task.ti: ffff88003dd88000 RIP: 0010:[<ffffffff810a376f>] [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 [<ffffffff810a376f>] __call_rcu.constprop.76+0x1f/0x280 kernel/rcu/tree.c:3046 RSP: 0018:ffff88003dd8bdb0 EFLAGS: 00010246 RAX: 00000000ffffff82 RBX: 0000000000000000 RCX: 0000000000000001 RDX: ffffffff81e3fe40 RSI: 0000000000000000 RDI: 00000000ffffff82 RBP: ffff88003dd8bde0 R08: ffff88007d2d2da0 R09: 0000000000000000 R10: 0000000000000000 R11: ffff88003e8073c0 R12: 00000000ffffff82 R13: ffff88003dd8be68 R14: ffff88007d027600 R15: ffff88003ddea700 FS: 0000000000b92880(0063) GS:ffff88007fd00000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 00000000ffffff8a CR3: 000000007cc5f000 CR4: 00000000000006e0 Stack: ffff88003dd8bdf0 ffffffff81160a8a 0000000000000000 00000000ffffff82 ffff88003dd8be68 ffff88007d027600 ffff88003dd8bdf0 ffffffff810a39e5 ffff88003dd8be20 ffffffff812a31ab ffff88007d027600 ffff88007d027620 Call Trace: [<ffffffff810a39e5>] kfree_call_rcu+0x15/0x20 kernel/rcu/tree.c:3136 [<ffffffff812a31ab>] user_update+0x8b/0xb0 security/keys/user_defined.c:129 [< inline >] __key_update security/keys/key.c:730 [<ffffffff8129e5c1>] key_create_or_update+0x291/0x440 security/keys/key.c:908 [< inline >] SYSC_add_key security/keys/keyctl.c:125 [<ffffffff8129fc21>] SyS_add_key+0x101/0x1e0 security/keys/keyctl.c:60 [<ffffffff8185f617>] entry_SYSCALL_64_fastpath+0x12/0x6a arch/x86/entry/entry_64.S:185 Note the error code (-ENOKEY) in EDX. A similar bug can be tripped by: keyctl request2 trusted user "" @u keyctl add trusted user "a" @u This should also affect encrypted keys - but that has to be correctly parameterised or it will fail with EINVAL before getting to the bit that will crashes. Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: David Howells <[email protected]> Acked-by: Mimi Zohar <[email protected]> Signed-off-by: James Morris <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void SyncManager::SyncInternal::StoreState( const std::string& state) { if (!directory()) { LOG(ERROR) << "Could not write notification state"; return; } if (VLOG_IS_ON(1)) { std::string encoded_state; base::Base64Encode(state, &encoded_state); DVLOG(1) << "Writing notification state: " << encoded_state; } directory()->SetNotificationState(state); directory()->SaveChanges(); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 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 InProcessBrowserTest::PrepareTestCommandLine(CommandLine* command_line) { test_launcher_utils::PrepareBrowserCommandLineForTests(command_line); command_line->AppendSwitchASCII(switches::kTestType, kBrowserTestType); #if defined(OS_WIN) if (command_line->HasSwitch(switches::kAshBrowserTests)) { command_line->AppendSwitchNative(switches::kViewerLaunchViaAppId, win8::test::kDefaultTestAppUserModelId); command_line->AppendSwitch(switches::kSilentLaunch); } #endif #if defined(OS_MACOSX) base::FilePath subprocess_path; PathService::Get(base::FILE_EXE, &subprocess_path); subprocess_path = subprocess_path.DirName().DirName(); DCHECK_EQ(subprocess_path.BaseName().value(), "Contents"); subprocess_path = subprocess_path.Append("Versions").Append(chrome::kChromeVersion); subprocess_path = subprocess_path.Append(chrome::kHelperProcessExecutablePath); command_line->AppendSwitchPath(switches::kBrowserSubprocessPath, subprocess_path); #endif if (exit_when_last_browser_closes_) command_line->AppendSwitch(switches::kDisableZeroBrowsersOpenForTests); if (command_line->GetArgs().empty()) command_line->AppendArg(url::kAboutBlankURL); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 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: DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } Commit Message: * tools/tiffcp.c: avoid uint32 underflow in cpDecodedStrips that can cause various issues, such as buffer overflows in the library. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2598 CWE ID: CWE-191 Target: 1 Example 2: Code: static gint64 toshiba_seek_next_packet(wtap *wth, int *err, gchar **err_info) { int byte; guint level = 0; gint64 cur_off; while ((byte = file_getc(wth->fh)) != EOF) { if (byte == toshiba_rec_magic[level]) { level++; if (level >= TOSHIBA_REC_MAGIC_SIZE) { /* note: we're leaving file pointer right after the magic characters */ cur_off = file_tell(wth->fh); if (cur_off == -1) { /* Error. */ *err = file_error(wth->fh, err_info); return -1; } return cur_off + 1; } } else { level = 0; } } /* EOF or error. */ *err = file_error(wth->fh, err_info); return -1; } Commit Message: Don't treat the packet length as unsigned. The scanf family of functions are as annoyingly bad at handling unsigned numbers as strtoul() is - both of them are perfectly willing to accept a value beginning with a negative sign as an unsigned value. When using strtoul(), you can compensate for this by explicitly checking for a '-' as the first character of the string, but you can't do that with sscanf(). So revert to having pkt_len be signed, and scanning it with %d, but check for a negative value and fail if we see a negative value. Bug: 12394 Change-Id: I4b19b95f2e1ffc96dac5c91bff6698c246f52007 Reviewed-on: https://code.wireshark.org/review/15230 Reviewed-by: Guy Harris <[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: void ImageInputType::ensurePrimaryContent() { if (!m_useFallbackContent) return; m_useFallbackContent = false; reattachFallbackContent(); } 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:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } Commit Message: fs: limit filesystem stacking depth Add a simple read-only counter to super_block that indicates how deep this is in the stack of filesystems. Previously ecryptfs was the only stackable filesystem and it explicitly disallowed multiple layers of itself. Overlayfs, however, can be stacked recursively and also may be stacked on top of ecryptfs or vice versa. To limit the kernel stack usage we must limit the depth of the filesystem stack. Initially the limit is set to 2. Signed-off-by: Miklos Szeredi <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void nfs_pageio_reset_write_mds(struct nfs_pageio_descriptor *pgio) { pgio->pg_ops = &nfs_pageio_write_ops; pgio->pg_bsize = NFS_SERVER(pgio->pg_inode)->wsize; } Commit Message: nfs: always make sure page is up-to-date before extending a write to cover the entire page We should always make sure the cached page is up-to-date when we're determining whether we can extend a write to cover the full page -- even if we've received a write delegation from the server. Commit c7559663 added logic to skip this check if we have a write delegation, which can lead to data corruption such as the following scenario if client B receives a write delegation from the NFS server: Client A: # echo 123456789 > /mnt/file Client B: # echo abcdefghi >> /mnt/file # cat /mnt/file 0�D0�abcdefghi Just because we hold a write delegation doesn't mean that we've read in the entire page contents. Cc: <[email protected]> # v3.11+ Signed-off-by: Scott Mayhew <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int setcieaspace(i_ctx_t * i_ctx_p, ref *r, int *stage, int *cont, int CIESubst) { int code = 0; ref CIEDict, *nocie; ulong dictkey; gs_md5_state_t md5; byte key[16]; if (i_ctx_p->language_level < 2) return_error(gs_error_undefined); code = dict_find_string(systemdict, "NOCIE", &nocie); if (code > 0) { if (!r_has_type(nocie, t_boolean)) return_error(gs_error_typecheck); if (nocie->value.boolval) return setgrayspace(i_ctx_p, r, stage, cont, 1); } *cont = 0; code = array_get(imemory, r, 1, &CIEDict); if (code < 0) return code; if ((*stage) > 0) { gs_client_color cc; cc.pattern = 0x00; cc.paint.values[0] = 0; code = gs_setcolor(igs, &cc); *stage = 0; return code; } gs_md5_init(&md5); /* If the hash (dictkey) is 0, we don't check for an existing * ICC profile dor this space. So if we get an error hashing * the space, we construct a new profile. */ dictkey = 0; if (hashcieaspace(i_ctx_p, r, &md5)) { /* Ideally we would use the whole md5 hash, but the ICC code only * expects a long. I'm 'slightly' concerned about collisions here * but I think its unlikely really. If it ever becomes a problem * we could add the hash bytes up, or modify the ICC cache to store * the full 16 byte hashs. */ gs_md5_finish(&md5, key); dictkey = *(ulong *)&key[sizeof(key) - sizeof(ulong)]; } else { gs_md5_finish(&md5, key); } code = cieaspace(i_ctx_p, &CIEDict, dictkey); (*stage)++; *cont = 1; return code; } Commit Message: CWE ID: CWE-704 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 BrowserTabStripController::TabDetachedAt(TabContents* contents, int model_index) { hover_tab_selector_.CancelTabTransition(); tabstrip_->RemoveTabAt(model_index); } 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: 1 Example 2: Code: void WebGLRenderingContextBase::DrawingBufferClientRestoreMaskAndClearValues() { if (destruction_in_progress_) return; if (!ContextGL()) return; bool color_mask_alpha = color_mask_[3] && active_scoped_rgb_emulation_color_masks_ == 0; ContextGL()->ColorMask(color_mask_[0], color_mask_[1], color_mask_[2], color_mask_alpha); ContextGL()->DepthMask(depth_mask_); ContextGL()->StencilMaskSeparate(GL_FRONT, stencil_mask_); ContextGL()->ClearColor(clear_color_[0], clear_color_[1], clear_color_[2], clear_color_[3]); ContextGL()->ClearDepthf(clear_depth_); ContextGL()->ClearStencil(clear_stencil_); } 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: gst_asf_demux_parse_stream_object (GstASFDemux * demux, guint8 * data, guint64 size) { AsfCorrectionType correction_type; AsfStreamType stream_type; GstClockTime time_offset; gboolean is_encrypted G_GNUC_UNUSED; guint16 stream_id; guint16 flags; ASFGuid guid; guint stream_specific_size; guint type_specific_size G_GNUC_UNUSED; guint unknown G_GNUC_UNUSED; gboolean inspect_payload = FALSE; AsfStream *stream = NULL; /* Get the rest of the header's header */ if (size < (16 + 16 + 8 + 4 + 4 + 2 + 4)) goto not_enough_data; gst_asf_demux_get_guid (&guid, &data, &size); stream_type = gst_asf_demux_identify_guid (asf_stream_guids, &guid); gst_asf_demux_get_guid (&guid, &data, &size); correction_type = gst_asf_demux_identify_guid (asf_correction_guids, &guid); time_offset = gst_asf_demux_get_uint64 (&data, &size) * 100; type_specific_size = gst_asf_demux_get_uint32 (&data, &size); stream_specific_size = gst_asf_demux_get_uint32 (&data, &size); flags = gst_asf_demux_get_uint16 (&data, &size); stream_id = flags & 0x7f; is_encrypted = ! !((flags & 0x8000) << 15); unknown = gst_asf_demux_get_uint32 (&data, &size); GST_DEBUG_OBJECT (demux, "Found stream %u, time_offset=%" GST_TIME_FORMAT, stream_id, GST_TIME_ARGS (time_offset)); /* dvr-ms has audio stream declared in stream specific data */ if (stream_type == ASF_STREAM_EXT_EMBED_HEADER) { AsfExtStreamType ext_stream_type; gst_asf_demux_get_guid (&guid, &data, &size); ext_stream_type = gst_asf_demux_identify_guid (asf_ext_stream_guids, &guid); if (ext_stream_type == ASF_EXT_STREAM_AUDIO) { inspect_payload = TRUE; gst_asf_demux_get_guid (&guid, &data, &size); gst_asf_demux_get_uint32 (&data, &size); gst_asf_demux_get_uint32 (&data, &size); gst_asf_demux_get_uint32 (&data, &size); gst_asf_demux_get_guid (&guid, &data, &size); gst_asf_demux_get_uint32 (&data, &size); stream_type = ASF_STREAM_AUDIO; } } switch (stream_type) { case ASF_STREAM_AUDIO:{ asf_stream_audio audio_object; if (!gst_asf_demux_get_stream_audio (&audio_object, &data, &size)) goto not_enough_data; GST_INFO ("Object is an audio stream with %u bytes of additional data", audio_object.size); stream = gst_asf_demux_add_audio_stream (demux, &audio_object, stream_id, &data, &size); switch (correction_type) { case ASF_CORRECTION_ON:{ guint span, packet_size, chunk_size, data_size, silence_data; GST_INFO ("Using error correction"); if (size < (1 + 2 + 2 + 2 + 1)) goto not_enough_data; span = gst_asf_demux_get_uint8 (&data, &size); packet_size = gst_asf_demux_get_uint16 (&data, &size); chunk_size = gst_asf_demux_get_uint16 (&data, &size); data_size = gst_asf_demux_get_uint16 (&data, &size); silence_data = gst_asf_demux_get_uint8 (&data, &size); stream->span = span; GST_DEBUG_OBJECT (demux, "Descrambling ps:%u cs:%u ds:%u s:%u sd:%u", packet_size, chunk_size, data_size, span, silence_data); if (stream->span > 1) { if (chunk_size == 0 || ((packet_size / chunk_size) <= 1)) { /* Disable descrambling */ stream->span = 0; } else { /* FIXME: this else branch was added for * weird_al_yankovic - the saga begins.asf */ stream->ds_packet_size = packet_size; stream->ds_chunk_size = chunk_size; } } else { /* Descambling is enabled */ stream->ds_packet_size = packet_size; stream->ds_chunk_size = chunk_size; } #if 0 /* Now skip the rest of the silence data */ if (data_size > 1) gst_bytestream_flush (demux->bs, data_size - 1); #else /* FIXME: CHECKME. And why -1? */ if (data_size > 1) { if (!gst_asf_demux_skip_bytes (data_size - 1, &data, &size)) { goto not_enough_data; } } #endif break; } case ASF_CORRECTION_OFF:{ GST_INFO ("Error correction off"); if (!gst_asf_demux_skip_bytes (stream_specific_size, &data, &size)) goto not_enough_data; break; } default: GST_ELEMENT_ERROR (demux, STREAM, DEMUX, (NULL), ("Audio stream using unknown error correction")); return NULL; } break; } case ASF_STREAM_VIDEO:{ asf_stream_video_format video_format_object; asf_stream_video video_object; guint16 vsize; if (!gst_asf_demux_get_stream_video (&video_object, &data, &size)) goto not_enough_data; vsize = video_object.size - 40; /* Byte order gets offset by single byte */ GST_INFO ("object is a video stream with %u bytes of " "additional data", vsize); if (!gst_asf_demux_get_stream_video_format (&video_format_object, &data, &size)) { goto not_enough_data; } stream = gst_asf_demux_add_video_stream (demux, &video_format_object, stream_id, &data, &size); break; } default: GST_WARNING_OBJECT (demux, "Unknown stream type for stream %u", stream_id); demux->other_streams = g_slist_append (demux->other_streams, GINT_TO_POINTER (stream_id)); break; } if (stream) stream->inspect_payload = inspect_payload; return stream; not_enough_data: { GST_WARNING_OBJECT (demux, "Unexpected end of data parsing stream object"); /* we'll error out later if we found no streams */ return NULL; } } Commit Message: asfdemux: Check that we have enough data available before parsing bool/uint extended content descriptors https://bugzilla.gnome.org/show_bug.cgi?id=777955 CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void DownloadItemImpl::UpdateProgress(int64 bytes_so_far, const std::string& hash_state) { hash_state_ = hash_state; received_bytes_ = bytes_so_far; if (received_bytes_ > total_bytes_) total_bytes_ = 0; if (bound_net_log_.IsLoggingAllEvents()) { bound_net_log_.AddEvent( net::NetLog::TYPE_DOWNLOAD_ITEM_UPDATED, net::NetLog::Int64Callback("bytes_so_far", received_bytes_)); } } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 1 Example 2: Code: MODRET set_timeoutsession(cmd_rec *cmd) { int timeout = 0, precedence = 0; config_rec *c = NULL; int ctxt = (cmd->config && cmd->config->config_type != CONF_PARAM ? cmd->config->config_type : cmd->server->config_type ? cmd->server->config_type : CONF_ROOT); /* this directive must have either 1 or 3 arguments */ if (cmd->argc-1 != 1 && cmd->argc-1 != 3) CONF_ERROR(cmd, "missing arguments"); CHECK_CONF(cmd, CONF_ROOT|CONF_VIRTUAL|CONF_GLOBAL|CONF_ANON); /* Set the precedence for this config_rec based on its configuration * context. */ if (ctxt & CONF_GLOBAL) { precedence = 1; /* These will never appear simultaneously */ } else if ((ctxt & CONF_ROOT) || (ctxt & CONF_VIRTUAL)) { precedence = 2; } else if (ctxt & CONF_ANON) { precedence = 3; } if (pr_str_get_duration(cmd->argv[1], &timeout) < 0) { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, "error parsing timeout value '", cmd->argv[1], "': ", strerror(errno), NULL)); } if (timeout == 0) { /* do nothing */ return PR_HANDLED(cmd); } if (cmd->argc-1 == 3) { if (strncmp(cmd->argv[2], "user", 5) == 0 || strncmp(cmd->argv[2], "group", 6) == 0 || strncmp(cmd->argv[2], "class", 6) == 0) { /* no op */ } else { CONF_ERROR(cmd, pstrcat(cmd->tmp_pool, cmd->argv[0], ": unknown classifier used: '", cmd->argv[2], "'", NULL)); } } if (cmd->argc-1 == 1) { c = add_config_param(cmd->argv[0], 2, NULL); c->argv[0] = pcalloc(c->pool, sizeof(int)); *((int *) c->argv[0]) = timeout; c->argv[1] = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) c->argv[1]) = precedence; } else if (cmd->argc-1 == 3) { array_header *acl = NULL; int argc = cmd->argc - 3; char **argv = cmd->argv + 2; acl = pr_expr_create(cmd->tmp_pool, &argc, argv); c = add_config_param(cmd->argv[0], 0); c->argc = argc + 2; /* add 3 to argc for the argv of the config_rec: one for the * seconds value, one for the precedence, one for the classifier, * and one for the terminating NULL */ c->argv = pcalloc(c->pool, ((argc + 4) * sizeof(char *))); /* capture the config_rec's argv pointer for doing the by-hand * population */ argv = (char **) c->argv; /* Copy in the seconds. */ *argv = pcalloc(c->pool, sizeof(int)); *((int *) *argv++) = timeout; /* Copy in the precedence. */ *argv = pcalloc(c->pool, sizeof(unsigned int)); *((unsigned int *) *argv++) = precedence; /* Copy in the classifier. */ *argv++ = pstrdup(c->pool, cmd->argv[2]); /* now, copy in the expression arguments */ if (argc && acl) { while (argc--) { *argv++ = pstrdup(c->pool, *((char **) acl->elts)); acl->elts = ((char **) acl->elts) + 1; } } /* don't forget the terminating NULL */ *argv = NULL; } else { /* Should never reach here. */ CONF_ERROR(cmd, "wrong number of parameters"); } c->flags |= CF_MERGEDOWN_MULTI; return PR_HANDLED(cmd); } 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: void CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init(); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput(); cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get( "cl_motd", "1", 0 ); #endif cl_timeout = Cvar_Get( "cl_timeout", "200", 0 ); cl_timeNudge = Cvar_Get( "cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get( "cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get( "cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get( "cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get( "cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get( "rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get( "timedemo", "0", 0 ); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_avidemo = Cvar_Get( "cl_avidemo", "0", 0 ); cl_forceavidemo = Cvar_Get( "cl_forceavidemo", "0", 0 ); rconAddress = Cvar_Get( "rconAddress", "", 0 ); cl_yawspeed = Cvar_Get( "cl_yawspeed", "140", CVAR_ARCHIVE ); cl_pitchspeed = Cvar_Get( "cl_pitchspeed", "140", CVAR_ARCHIVE ); cl_anglespeedkey = Cvar_Get( "cl_anglespeedkey", "1.5", 0 ); cl_maxpackets = Cvar_Get( "cl_maxpackets", "38", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get( "cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get( "cl_run", "1", CVAR_ARCHIVE ); cl_sensitivity = Cvar_Get( "sensitivity", "5", CVAR_ARCHIVE ); cl_mouseAccel = Cvar_Get( "cl_mouseAccel", "0", CVAR_ARCHIVE ); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get( "cl_showmouserate", "0", 0 ); cl_allowDownload = Cvar_Get( "cl_allowDownload", "0", CVAR_ARCHIVE ); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif Cvar_Get( "cg_autoswitch", "2", CVAR_ARCHIVE ); Cvar_Get( "cg_wolfparticles", "1", CVAR_ARCHIVE ); cl_conXOffset = Cvar_Get( "cl_conXOffset", "0", 0 ); cl_inGameVideo = Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE ); cl_serverStatusResendTime = Cvar_Get( "cl_serverStatusResendTime", "750", 0 ); cl_recoilPitch = Cvar_Get( "cg_recoilPitch", "0", CVAR_ROM ); m_pitch = Cvar_Get( "m_pitch", "0.022", CVAR_ARCHIVE ); m_yaw = Cvar_Get( "m_yaw", "0.022", CVAR_ARCHIVE ); m_forward = Cvar_Get( "m_forward", "0.25", CVAR_ARCHIVE ); m_side = Cvar_Get( "m_side", "0.25", CVAR_ARCHIVE ); m_filter = Cvar_Get( "m_filter", "0", CVAR_ARCHIVE ); j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); Cvar_Get( "name", "WolfPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get( "rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); // NERVE - SMF - changed from 3000 Cvar_Get( "snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "model", "bj2", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "head", "default", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "color", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "password", "", CVAR_USERINFO ); Cvar_Get( "cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif Cvar_Get( "cg_autoactivate", "1", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "cg_emptyswitch", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get( "cg_viewsize", "100", CVAR_ARCHIVE ); Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); cl_missionStats = Cvar_Get( "g_missionStats", "0", CVAR_ROM ); cl_waitForFire = Cvar_Get( "cl_waitForFire", "0", CVAR_ROM ); cl_language = Cvar_Get( "cl_language", "0", CVAR_ARCHIVE ); cl_debugTranslation = Cvar_Get( "cl_debugTranslation", "0", 0 ); Cmd_AddCommand( "cmd", CL_ForwardToServer_f ); Cmd_AddCommand( "configstrings", CL_Configstrings_f ); Cmd_AddCommand( "clientinfo", CL_Clientinfo_f ); Cmd_AddCommand( "snd_restart", CL_Snd_Restart_f ); Cmd_AddCommand( "vid_restart", CL_Vid_Restart_f ); Cmd_AddCommand( "disconnect", CL_Disconnect_f ); Cmd_AddCommand( "record", CL_Record_f ); Cmd_AddCommand( "demo", CL_PlayDemo_f ); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand( "cinematic", CL_PlayCinematic_f ); Cmd_AddCommand( "stoprecord", CL_StopRecord_f ); Cmd_AddCommand( "connect", CL_Connect_f ); Cmd_AddCommand( "reconnect", CL_Reconnect_f ); Cmd_AddCommand( "localservers", CL_LocalServers_f ); Cmd_AddCommand( "globalservers", CL_GlobalServers_f ); Cmd_AddCommand( "rcon", CL_Rcon_f ); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand( "ping", CL_Ping_f ); Cmd_AddCommand( "serverstatus", CL_ServerStatus_f ); Cmd_AddCommand( "showip", CL_ShowIP_f ); Cmd_AddCommand( "fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand( "fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); Cmd_AddCommand( "cache_startgather", CL_Cache_StartGather_f ); Cmd_AddCommand( "cache_usedfile", CL_Cache_UsedFile_f ); Cmd_AddCommand( "cache_setindex", CL_Cache_SetIndex_f ); Cmd_AddCommand( "cache_mapchange", CL_Cache_MapChange_f ); Cmd_AddCommand( "cache_endgather", CL_Cache_EndGather_f ); Cmd_AddCommand( "updatehunkusage", CL_UpdateLevelHunkUsage ); Cmd_AddCommand( "updatescreen", SCR_UpdateScreen ); Cmd_AddCommand( "cld", CL_ClientDamageCommand ); Cmd_AddCommand( "startMultiplayer", CL_startMultiplayer_f ); // NERVE - SMF Cmd_AddCommand( "shellExecute", CL_ShellExecute_URL_f ); Cmd_AddCommand( "map_restart", CL_MapRestart_f ); Cmd_AddCommand( "setRecommended", CL_SetRecommended_f ); CL_InitRef(); SCR_Init(); Cvar_Set( "cl_running", "1" ); CL_GenerateQKey(); Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM ); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269 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: SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval *zpath, *zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); MAKE_STD_ZVAL(zflags); MAKE_STD_ZVAL(zpath); ZVAL_LONG(zflags, intern->flags); ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC); zval_ptr_dtor(&zpath); zval_ptr_dtor(&zflags); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190 Target: 1 Example 2: Code: void MojoAudioOutputIPC::CreateStream(media::AudioOutputIPCDelegate* delegate, const media::AudioParameters& params) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(delegate); DCHECK(!StreamCreationRequested()); if (!AuthorizationRequested()) { DCHECK(!delegate_); delegate_ = delegate; if (!DoRequestDeviceAuthorization( 0, media::AudioDeviceDescription::kDefaultDeviceId, base::BindOnce(&TrivialAuthorizedCallback))) { return; } } DCHECK_EQ(delegate_, delegate); media::mojom::AudioOutputStreamClientPtr client_ptr; binding_.Bind(mojo::MakeRequest(&client_ptr)); stream_provider_->Acquire(mojo::MakeRequest(&stream_), std::move(client_ptr), params, base::BindOnce(&MojoAudioOutputIPC::StreamCreated, base::Unretained(this))); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void LinkChangeSerializerMarkupAccumulator::appendElement(StringBuilder& result, Element& element, Namespaces* namespaces) { if (element.hasTagName(HTMLNames::htmlTag)) { result.append('\n'); MarkupFormatter::appendComment(result, String::format(" saved from url=(%04d)%s ", static_cast<int>(document().url().string().utf8().length()), document().url().string().utf8().data())); result.append('\n'); } if (element.hasTagName(HTMLNames::baseTag)) { result.appendLiteral("<base href=\".\""); if (!document().baseTarget().isEmpty()) { result.appendLiteral(" target=\""); MarkupFormatter::appendAttributeValue(result, document().baseTarget(), document().isHTMLDocument()); result.append('"'); } if (document().isXHTMLDocument()) result.appendLiteral(" />"); else result.appendLiteral(">"); } else { SerializerMarkupAccumulator::appendElement(result, element, namespaces); } } Commit Message: Escape "--" in the page URL at page serialization This patch makes page serializer to escape the page URL embed into a HTML comment of result HTML[1] to avoid inserting text as HTML from URL by introducing a static member function |PageSerialzier::markOfTheWebDeclaration()| for sharing it between |PageSerialzier| and |WebPageSerialzier| classes. [1] We use following format for serialized HTML: saved from url=(${lengthOfURL})${URL} BUG=503217 TEST=webkit_unit_tests --gtest_filter=PageSerializerTest.markOfTheWebDeclaration TEST=webkit_unit_tests --gtest_filter=WebPageSerializerTest.fromUrlWithMinusMinu Review URL: https://codereview.chromium.org/1371323003 Cr-Commit-Position: refs/heads/master@{#351736} CWE ID: CWE-20 Target: 1 Example 2: Code: MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } 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: ZEND_API int _array_init(zval *arg, uint size ZEND_FILE_LINE_DC) /* {{{ */ { ALLOC_HASHTABLE_REL(Z_ARRVAL_P(arg)); _zend_hash_init(Z_ARRVAL_P(arg), size, ZVAL_PTR_DTOR, 0 ZEND_FILE_LINE_RELAY_CC); Z_TYPE_P(arg) = IS_ARRAY; return SUCCESS; } /* }}} */ Commit Message: 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: juniper_mlfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLC_UI): case (LLC_UI<<8): isoclns_print(ndo, p, l2info.length, l2info.caplen); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: void hnti_del(GF_Box *a) { gf_free(a); } Commit Message: fixed 2 possible heap overflows (inc. #1088) CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: nfsd4_get_readstateid(struct nfsd4_compound_state *cstate, struct nfsd4_read *read) { get_stateid(cstate, &read->rd_stateid); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int main (int argc, char *argv[]) { int objectsCount = 0; Guint numOffset = 0; std::vector<Object> pages; std::vector<Guint> offsets; XRef *yRef, *countRef; FILE *f; OutStream *outStr; int i; int j, rootNum; std::vector<PDFDoc *>docs; int majorVersion = 0; int minorVersion = 0; char *fileName = argv[argc - 1]; int exitCode; exitCode = 99; const GBool ok = parseArgs (argDesc, &argc, argv); if (!ok || argc < 3 || printVersion || printHelp) { fprintf(stderr, "pdfunite version %s\n", PACKAGE_VERSION); fprintf(stderr, "%s\n", popplerCopyright); fprintf(stderr, "%s\n", xpdfCopyright); if (!printVersion) { printUsage("pdfunite", "<PDF-sourcefile-1>..<PDF-sourcefile-n> <PDF-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; return exitCode; } exitCode = 0; globalParams = new GlobalParams(); for (i = 1; i < argc - 1; i++) { GooString *gfileName = new GooString(argv[i]); PDFDoc *doc = new PDFDoc(gfileName, NULL, NULL, NULL); if (doc->isOk() && !doc->isEncrypted()) { docs.push_back(doc); if (doc->getPDFMajorVersion() > majorVersion) { majorVersion = doc->getPDFMajorVersion(); minorVersion = doc->getPDFMinorVersion(); } else if (doc->getPDFMajorVersion() == majorVersion) { if (doc->getPDFMinorVersion() > minorVersion) { minorVersion = doc->getPDFMinorVersion(); } } } else if (doc->isOk()) { error(errUnimplemented, -1, "Could not merge encrypted files ('{0:s}')", argv[i]); return -1; } else { error(errSyntaxError, -1, "Could not merge damaged documents ('{0:s}')", argv[i]); return -1; } } if (!(f = fopen(fileName, "wb"))) { error(errIO, -1, "Could not open file '{0:s}'", fileName); return -1; } outStr = new FileOutStream(f, 0); yRef = new XRef(); countRef = new XRef(); yRef->add(0, 65535, 0, gFalse); PDFDoc::writeHeader(outStr, majorVersion, minorVersion); Object intents; Object afObj; Object ocObj; Object names; if (docs.size() >= 1) { Object catObj; docs[0]->getXRef()->getCatalog(&catObj); Dict *catDict = catObj.getDict(); catDict->lookup("OutputIntents", &intents); catDict->lookupNF("AcroForm", &afObj); Ref *refPage = docs[0]->getCatalog()->getPageRef(1); if (!afObj.isNull()) { docs[0]->markAcroForm(&afObj, yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookupNF("OCProperties", &ocObj); if (!ocObj.isNull() && ocObj.isDict()) { docs[0]->markPageObjects(ocObj.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } catDict->lookup("Names", &names); if (!names.isNull() && names.isDict()) { docs[0]->markPageObjects(names.getDict(), yRef, countRef, 0, refPage->num, refPage->num); } if (intents.isArray() && intents.arrayGetLength() > 0) { for (i = 1; i < (int) docs.size(); i++) { Object pagecatObj, pageintents; docs[i]->getXRef()->getCatalog(&pagecatObj); Dict *pagecatDict = pagecatObj.getDict(); pagecatDict->lookup("OutputIntents", &pageintents); if (pageintents.isArray() && pageintents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { Object idf; intent.dictLookup("OutputConditionIdentifier", &idf); if (idf.isString()) { GooString *gidf = idf.getString(); GBool removeIntent = gTrue; for (int k = 0; k < pageintents.arrayGetLength(); k++) { Object pgintent; pageintents.arrayGet(k, &pgintent, 0); if (pgintent.isDict()) { Object pgidf; pgintent.dictLookup("OutputConditionIdentifier", &pgidf); if (pgidf.isString()) { GooString *gpgidf = pgidf.getString(); if (gpgidf->cmp(gidf) == 0) { pgidf.free(); removeIntent = gFalse; break; } } pgidf.free(); } } if (removeIntent) { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Output intent {0:s} missing in pdf {1:s}, removed", gidf->getCString(), docs[i]->getFileName()->getCString()); } } else { intents.arrayRemove(j); error(errSyntaxWarning, -1, "Invalid output intent dict, missing required OutputConditionIdentifier"); } idf.free(); } else { intents.arrayRemove(j); } intent.free(); } } else { error(errSyntaxWarning, -1, "Output intents differs, remove them all"); intents.free(); break; } pagecatObj.free(); pageintents.free(); } } if (intents.isArray() && intents.arrayGetLength() > 0) { for (j = intents.arrayGetLength() - 1; j >= 0; j--) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { docs[0]->markPageObjects(intent.getDict(), yRef, countRef, numOffset, 0, 0); } else { intents.arrayRemove(j); } intent.free(); } } catObj.free(); } for (i = 0; i < (int) docs.size(); i++) { for (j = 1; j <= docs[i]->getNumPages(); j++) { PDFRectangle *cropBox = NULL; if (docs[i]->getCatalog()->getPage(j)->isCropped()) cropBox = docs[i]->getCatalog()->getPage(j)->getCropBox(); Object page; docs[i]->getXRef()->fetch(refPage->num, refPage->gen, &page); Dict *pageDict = page.getDict(); Dict *resDict = docs[i]->getCatalog()->getPage(j)->getResourceDict(); if (resDict) { Object *newResource = new Object(); newResource->initDict(resDict); pageDict->set("Resources", newResource); delete newResource; } pages.push_back(page); offsets.push_back(numOffset); docs[i]->markPageObjects(pageDict, yRef, countRef, numOffset, refPage->num, refPage->num); Object annotsObj; pageDict->lookupNF("Annots", &annotsObj); if (!annotsObj.isNull()) { docs[i]->markAnnotations(&annotsObj, yRef, countRef, numOffset, refPage->num, refPage->num); annotsObj.free(); } } Object pageCatObj, pageNames, pageForm; docs[i]->getXRef()->getCatalog(&pageCatObj); Dict *pageCatDict = pageCatObj.getDict(); pageCatDict->lookup("Names", &pageNames); if (!pageNames.isNull() && pageNames.isDict()) { if (!names.isDict()) { names.free(); names.initDict(yRef); } doMergeNameDict(docs[i], yRef, countRef, 0, 0, names.getDict(), pageNames.getDict(), numOffset); } pageCatDict->lookup("AcroForm", &pageForm); if (i > 0 && !pageForm.isNull() && pageForm.isDict()) { if (afObj.isNull()) { pageCatDict->lookupNF("AcroForm", &afObj); } else if (afObj.isDict()) { doMergeFormDict(afObj.getDict(), pageForm.getDict(), numOffset); } } pageForm.free(); pageNames.free(); pageCatObj.free(); objectsCount += docs[i]->writePageObjects(outStr, yRef, numOffset, gTrue); numOffset = yRef->getNumObjects() + 1; } rootNum = yRef->getNumObjects() + 1; yRef->add(rootNum, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum); outStr->printf("<< /Type /Catalog /Pages %d 0 R", rootNum + 1); if (intents.isArray() && intents.arrayGetLength() > 0) { outStr->printf(" /OutputIntents ["); for (j = 0; j < intents.arrayGetLength(); j++) { Object intent; intents.arrayGet(j, &intent, 0); if (intent.isDict()) { PDFDoc::writeObject(&intent, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); } intent.free(); } outStr->printf("]"); } intents.free(); if (!afObj.isNull()) { outStr->printf(" /AcroForm "); PDFDoc::writeObject(&afObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); afObj.free(); } if (!ocObj.isNull() && ocObj.isDict()) { outStr->printf(" /OCProperties "); PDFDoc::writeObject(&ocObj, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); ocObj.free(); } if (!names.isNull() && names.isDict()) { outStr->printf(" /Names "); PDFDoc::writeObject(&names, outStr, yRef, 0, NULL, cryptRC4, 0, 0, 0); names.free(); } outStr->printf(">>\nendobj\n"); objectsCount++; yRef->add(rootNum + 1, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + 1); outStr->printf("<< /Type /Pages /Kids ["); for (j = 0; j < (int) pages.size(); j++) outStr->printf(" %d 0 R", rootNum + j + 2); outStr->printf(" ] /Count %zd >>\nendobj\n", pages.size()); objectsCount++; for (i = 0; i < (int) pages.size(); i++) { yRef->add(rootNum + i + 2, 0, outStr->getPos(), gTrue); outStr->printf("%d 0 obj\n", rootNum + i + 2); outStr->printf("<< "); Dict *pageDict = pages[i].getDict(); for (j = 0; j < pageDict->getLength(); j++) { if (j > 0) outStr->printf(" "); const char *key = pageDict->getKey(j); Object value; pageDict->getValNF(j, &value); if (strcmp(key, "Parent") == 0) { outStr->printf("/Parent %d 0 R", rootNum + 1); } else { outStr->printf("/%s ", key); PDFDoc::writeObject(&value, outStr, yRef, offsets[i], NULL, cryptRC4, 0, 0, 0); } value.free(); } outStr->printf(" >>\nendobj\n"); objectsCount++; } Goffset uxrefOffset = outStr->getPos(); Ref ref; ref.num = rootNum; ref.gen = 0; Dict *trailerDict = PDFDoc::createTrailerDict(objectsCount, gFalse, 0, &ref, yRef, fileName, outStr->getPos()); PDFDoc::writeXRefTableTrailer(trailerDict, yRef, gTrue, // write all entries according to ISO 32000-1, 7.5.4 Cross-Reference Table: "For a file that has never been incrementally updated, the cross-reference section shall contain only one subsection, whose object numbering begins at 0." uxrefOffset, outStr, yRef); delete trailerDict; outStr->close(); delete outStr; fclose(f); delete yRef; delete countRef; for (j = 0; j < (int) pages.size (); j++) pages[j].free(); for (i = 0; i < (int) docs.size (); i++) delete docs[i]; delete globalParams; return exitCode; } Commit Message: CWE ID: CWE-476 Target: 1 Example 2: Code: bool Browser::RunUnloadEventsHelper(WebContents* contents) { if (contents->NeedToFireBeforeUnload()) { contents->GetRenderViewHost()->FirePageBeforeUnload(false); return true; } return false; } 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 kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4) { unsigned long old_cr4 = kvm_read_cr4(vcpu); unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PAE | X86_CR4_SMEP; if (cr4 & CR4_RESERVED_BITS) return 1; if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE)) return 1; if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP)) return 1; if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_RDWRGSFS)) return 1; if (is_long_mode(vcpu)) { if (!(cr4 & X86_CR4_PAE)) return 1; } else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE) && ((cr4 ^ old_cr4) & pdptr_bits) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu))) return 1; if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) { if (!guest_cpuid_has_pcid(vcpu)) return 1; /* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */ if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu)) return 1; } if (kvm_x86_ops->set_cr4(vcpu, cr4)) return 1; if (((cr4 ^ old_cr4) & pdptr_bits) || (!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE))) kvm_mmu_reset_context(vcpu); if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE) kvm_update_cpuid(vcpu); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[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 void ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: fixup_appledouble(struct archive_write_disk *a, const char *pathname) { (void)a; /* UNUSED */ (void)pathname; /* UNUSED */ return (ARCHIVE_OK); } Commit Message: Add ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS option This fixes a directory traversal in the cpio tool. CWE ID: CWE-22 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 IsMojoBlobsEnabled() { return base::FeatureList::IsEnabled(features::kMojoBlobs) || base::FeatureList::IsEnabled(features::kNetworkService); } Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6 https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604 BUG=778101 Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c Reviewed-on: https://chromium-review.googlesource.com/747941 Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: David Benjamin <[email protected]> Commit-Queue: Steven Valdez <[email protected]> Cr-Commit-Position: refs/heads/master@{#513774} CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: __xfs_get_blocks( struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create, bool direct, bool dax_fault) { struct xfs_inode *ip = XFS_I(inode); struct xfs_mount *mp = ip->i_mount; xfs_fileoff_t offset_fsb, end_fsb; int error = 0; int lockmode = 0; struct xfs_bmbt_irec imap; int nimaps = 1; xfs_off_t offset; ssize_t size; int new = 0; bool is_cow = false; bool need_alloc = false; BUG_ON(create && !direct); if (XFS_FORCED_SHUTDOWN(mp)) return -EIO; offset = (xfs_off_t)iblock << inode->i_blkbits; ASSERT(bh_result->b_size >= (1 << inode->i_blkbits)); size = bh_result->b_size; if (!create && offset >= i_size_read(inode)) return 0; /* * Direct I/O is usually done on preallocated files, so try getting * a block mapping without an exclusive lock first. */ lockmode = xfs_ilock_data_map_shared(ip); ASSERT(offset <= mp->m_super->s_maxbytes); if (offset + size > mp->m_super->s_maxbytes) size = mp->m_super->s_maxbytes - offset; end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size); offset_fsb = XFS_B_TO_FSBT(mp, offset); if (create && direct && xfs_is_reflink_inode(ip)) is_cow = xfs_reflink_find_cow_mapping(ip, offset, &imap, &need_alloc); if (!is_cow) { error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb, &imap, &nimaps, XFS_BMAPI_ENTIRE); /* * Truncate an overwrite extent if there's a pending CoW * reservation before the end of this extent. This * forces us to come back to get_blocks to take care of * the CoW. */ if (create && direct && nimaps && imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && !ISUNWRITTEN(&imap)) xfs_reflink_trim_irec_to_next_cow(ip, offset_fsb, &imap); } ASSERT(!need_alloc); if (error) goto out_unlock; /* for DAX, we convert unwritten extents directly */ if (create && (!nimaps || (imap.br_startblock == HOLESTARTBLOCK || imap.br_startblock == DELAYSTARTBLOCK) || (IS_DAX(inode) && ISUNWRITTEN(&imap)))) { /* * xfs_iomap_write_direct() expects the shared lock. It * is unlocked on return. */ if (lockmode == XFS_ILOCK_EXCL) xfs_ilock_demote(ip, lockmode); error = xfs_iomap_write_direct(ip, offset, size, &imap, nimaps); if (error) return error; new = 1; trace_xfs_get_blocks_alloc(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_DELALLOC, &imap); } else if (nimaps) { trace_xfs_get_blocks_found(ip, offset, size, ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN : XFS_IO_OVERWRITE, &imap); xfs_iunlock(ip, lockmode); } else { trace_xfs_get_blocks_notfound(ip, offset, size); goto out_unlock; } if (IS_DAX(inode) && create) { ASSERT(!ISUNWRITTEN(&imap)); /* zeroing is not needed at a higher layer */ new = 0; } /* trim mapping down to size requested */ xfs_map_trim_size(inode, iblock, bh_result, &imap, offset, size); /* * For unwritten extents do not report a disk address in the buffered * read case (treat as if we're reading into a hole). */ if (imap.br_startblock != HOLESTARTBLOCK && imap.br_startblock != DELAYSTARTBLOCK && (create || !ISUNWRITTEN(&imap))) { if (create && direct && !is_cow) { error = xfs_bounce_unaligned_dio_write(ip, offset_fsb, &imap); if (error) return error; } xfs_map_buffer(inode, bh_result, &imap, offset); if (ISUNWRITTEN(&imap)) set_buffer_unwritten(bh_result); /* direct IO needs special help */ if (create) { if (dax_fault) ASSERT(!ISUNWRITTEN(&imap)); else xfs_map_direct(inode, bh_result, &imap, offset, is_cow); } } /* * If this is a realtime file, data may be on a different device. * to that pointed to from the buffer_head b_bdev currently. */ bh_result->b_bdev = xfs_find_bdev_for_inode(inode); /* * If we previously allocated a block out beyond eof and we are now * coming back to use it then we will need to flag it as new even if it * has a disk address. * * With sub-block writes into unwritten extents we also need to mark * the buffer as new so that the unwritten parts of the buffer gets * correctly zeroed. */ if (create && ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) || (offset >= i_size_read(inode)) || (new || ISUNWRITTEN(&imap)))) set_buffer_new(bh_result); BUG_ON(direct && imap.br_startblock == DELAYSTARTBLOCK); return 0; out_unlock: xfs_iunlock(ip, lockmode); return error; } Commit Message: xfs: don't BUG() on mixed direct and mapped I/O We've had reports of generic/095 causing XFS to BUG() in __xfs_get_blocks() due to the existence of delalloc blocks on a direct I/O read. generic/095 issues a mix of various types of I/O, including direct and memory mapped I/O to a single file. This is clearly not supported behavior and is known to lead to such problems. E.g., the lack of exclusion between the direct I/O and write fault paths means that a write fault can allocate delalloc blocks in a region of a file that was previously a hole after the direct read has attempted to flush/inval the file range, but before it actually reads the block mapping. In turn, the direct read discovers a delalloc extent and cannot proceed. While the appropriate solution here is to not mix direct and memory mapped I/O to the same regions of the same file, the current BUG_ON() behavior is probably overkill as it can crash the entire system. Instead, localize the failure to the I/O in question by returning an error for a direct I/O that cannot be handled safely due to delalloc blocks. Be careful to allow the case of a direct write to post-eof delalloc blocks. This can occur due to speculative preallocation and is safe as post-eof blocks are not accompanied by dirty pages in pagecache (conversely, preallocation within eof must have been zeroed, and thus dirtied, before the inode size could have been increased beyond said blocks). Finally, provide an additional warning if a direct I/O write occurs while the file is memory mapped. This may not catch all problematic scenarios, but provides a hint that some known-to-be-problematic I/O methods are in use. Signed-off-by: Brian Foster <[email protected]> Reviewed-by: Dave Chinner <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-362 Target: 1 Example 2: Code: conv_form_encoding(Str val, FormItemList *fi, Buffer *buf) { wc_ces charset = SystemCharset; if (fi->parent->charset) charset = fi->parent->charset; else if (buf->document_charset && buf->document_charset != WC_CES_US_ASCII) charset = buf->document_charset; return wc_Str_conv_strict(val, InnerCharset, charset); } Commit Message: Make temporary directory safely when ~/.w3m is unwritable 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: PHP_FUNCTION(str_split) { zend_string *str; zend_long split_length = 1; char *p; size_t n_reg_segments; if (zend_parse_parameters(ZEND_NUM_ARGS(), "S|l", &str, &split_length) == FAILURE) { return; } if (split_length <= 0) { php_error_docref(NULL, E_WARNING, "The length of each segment must be greater than zero"); RETURN_FALSE; } if (0 == ZSTR_LEN(str) || (size_t)split_length >= ZSTR_LEN(str)) { array_init_size(return_value, 1); add_next_index_stringl(return_value, ZSTR_VAL(str), ZSTR_LEN(str)); return; } array_init_size(return_value, (uint32_t)(((ZSTR_LEN(str) - 1) / split_length) + 1)); n_reg_segments = ZSTR_LEN(str) / split_length; p = ZSTR_VAL(str); while (n_reg_segments-- > 0) { add_next_index_stringl(return_value, p, split_length); p += split_length; } if (p != (ZSTR_VAL(str) + ZSTR_LEN(str))) { add_next_index_stringl(return_value, p, (ZSTR_VAL(str) + ZSTR_LEN(str) - p)); } } Commit Message: CWE ID: CWE-17 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): JBIG2Segment(segNumA) { w = bitmap->w; h = bitmap->h; line = bitmap->line; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); memcpy(data, bitmap->data, h * line); data[h * line] = 0; } Commit Message: CWE ID: CWE-189 Target: 1 Example 2: Code: static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615 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 handle_packet(unsigned char *data, int data_len) { struct mt_mactelnet_hdr pkthdr; /* Minimal size checks (pings are not supported here) */ if (data_len < MT_HEADER_LEN){ return -1; } parse_packet(data, &pkthdr); /* We only care about packets with correct sessionkey */ if (pkthdr.seskey != sessionkey) { return -1; } /* Handle data packets */ if (pkthdr.ptype == MT_PTYPE_DATA) { struct mt_packet odata; struct mt_mactelnet_control_hdr cpkt; int success = 0; /* Always transmit ACKNOWLEDGE packets in response to DATA packets */ init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN)); send_udp(&odata, 0); /* Accept first packet, and all packets greater than incounter, and if counter has wrapped around. */ if (pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) { incounter = pkthdr.counter; } else { /* Ignore double or old packets */ return -1; } /* Parse controlpacket data */ success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt); while (success) { /* If we receive pass_salt, transmit auth data back */ if (cpkt.cptype == MT_CPTYPE_PASSSALT) { memcpy(pass_salt, cpkt.data, cpkt.length); send_auth(username, password); } /* If the (remaining) data did not have a control-packet magic byte sequence, the data is raw terminal data to be outputted to the terminal. */ else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) { fwrite((const void *)cpkt.data, 1, cpkt.length, stdout); } /* END_AUTH means that the user/password negotiation is done, and after this point terminal data may arrive, so we set up the terminal to raw mode. */ else if (cpkt.cptype == MT_CPTYPE_END_AUTH) { /* we have entered "terminal mode" */ terminal_mode = 1; if (is_a_tty) { /* stop input buffering at all levels. Give full control of terminal to RouterOS */ raw_term(); setvbuf(stdin, (char*)NULL, _IONBF, 0); /* Add resize signal handler */ signal(SIGWINCH, sig_winch); } } /* Parse next controlpacket */ success = parse_control_packet(NULL, 0, &cpkt); } } else if (pkthdr.ptype == MT_PTYPE_ACK) { /* Handled elsewhere */ } /* The server wants to terminate the connection, we have to oblige */ else if (pkthdr.ptype == MT_PTYPE_END) { struct mt_packet odata; /* Acknowledge the disconnection by sending a END packet in return */ init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0); send_udp(&odata, 0); if (!quiet_mode) { fprintf(stderr, _("Connection closed.\n")); } /* exit */ running = 0; } else { fprintf(stderr, _("Unhandeled packet type: %d received from server %s\n"), pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac)); return -1; } return pkthdr.ptype; } Commit Message: Merge pull request #20 from eyalitki/master 2nd round security fixes from eyalitki 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: dtls1_hm_fragment_free(hm_fragment *frag) { if (frag->fragment) OPENSSL_free(frag->fragment); if (frag->reassembly) OPENSSL_free(frag->reassembly); OPENSSL_free(frag); int curr_mtu; unsigned int len, frag_off, mac_size, blocksize; /* AHA! Figure out the MTU, and stick to the right size */ if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) { s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); /* I've seen the kernel return bogus numbers when it doesn't know * (initial write), so just make sure we have a reasonable number */ if (s->d1->mtu < dtls1_min_mtu()) { s->d1->mtu = 0; s->d1->mtu = dtls1_guess_mtu(s->d1->mtu); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL); } } #if 0 mtu = s->d1->mtu; fprintf(stderr, "using MTU = %d\n", mtu); mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s)); if ( curr_mtu > 0) mtu = curr_mtu; else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0) return ret; if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu) { ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH); } #endif OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */ if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE) OPENSSL_assert(s->init_num == (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH); if (s->write_hash) mac_size = EVP_MD_CTX_size(s->write_hash); else mac_size = 0; if (s->enc_write_ctx && (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE)) blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher); else blocksize = 0; frag_off = 0; while( s->init_num) { curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH) { /* grr.. we could get an error if MTU picked was wrong */ ret = BIO_flush(SSL_get_wbio(s)); if ( ret <= 0) return ret; curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - mac_size - blocksize; } if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; /* XDTLS: this function is too long. split out the CCS part */ if ( type == SSL3_RT_HANDSHAKE) { if ( s->init_off != 0) { OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH); s->init_off -= DTLS1_HM_HEADER_LENGTH; s->init_num += DTLS1_HM_HEADER_LENGTH; if ( s->init_num > curr_mtu) len = curr_mtu; else len = s->init_num; } dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH); dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]); OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH); } ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off], len); if (ret < 0) { /* might need to update MTU here, but we don't know * which previous packet caused the failure -- so can't * really retransmit anything. continue as if everything * is fine and wait for an alert to handle the * retransmit */ if ( BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 ) s->d1->mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL); else return(-1); } else { /* bad if this assert fails, only part of the handshake * message got sent. but why would this happen? */ OPENSSL_assert(len == (unsigned int)ret); if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting) { /* should not be done for 'Hello Request's, but in that case * we'll ignore the result anyway */ unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off]; const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr; int xlen; if (frag_off == 0 && s->version != DTLS1_BAD_VER) { /* reconstruct message header is if it * is being sent in single fragment */ *p++ = msg_hdr->type; l2n3(msg_hdr->msg_len,p); s2n (msg_hdr->seq,p); l2n3(0,p); l2n3(msg_hdr->msg_len,p); p -= DTLS1_HM_HEADER_LENGTH; xlen = ret; } else { p += DTLS1_HM_HEADER_LENGTH; xlen = ret - DTLS1_HM_HEADER_LENGTH; } ssl3_finish_mac(s, p, xlen); } if (ret == s->init_num) { if (s->msg_callback) s->msg_callback(1, s->version, type, s->init_buf->data, (size_t)(s->init_off + s->init_num), s, s->msg_callback_arg); s->init_off = 0; /* done writing this message */ s->init_num = 0; return(1); } s->init_off+=ret; s->init_num-=ret; frag_off += (ret -= DTLS1_HM_HEADER_LENGTH); } } return(0); } Commit Message: CWE ID: CWE-310 Target: 1 Example 2: Code: static int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; char *byteptr = (char *)wpmd->data; if (bytecnt != 4) return FALSE; wps->float_flags = *byteptr++; wps->float_shift = *byteptr++; wps->float_max_exp = *byteptr++; wps->float_norm_exp = *byteptr; return TRUE; } Commit Message: issue #54: fix potential out-of-bounds heap read 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: std::unique_ptr<TracedValue> InspectorLayerInvalidationTrackingEvent::Data( const PaintLayer* layer, const char* reason) { const LayoutObject& paint_invalidation_container = layer->GetLayoutObject().ContainerForPaintInvalidation(); std::unique_ptr<TracedValue> value = TracedValue::Create(); value->SetString("frame", ToHexString(paint_invalidation_container.GetFrame())); SetGeneratingNodeInfo(value.get(), &paint_invalidation_container, "paintId"); value->SetString("reason", reason); return value; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 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 a2dp_command(struct a2dp_stream_common *common, char cmd) { char ack; DEBUG("A2DP COMMAND %s", dump_a2dp_ctrl_event(cmd)); /* send command */ if (send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL) == -1) { ERROR("cmd failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } /* wait for ack byte */ if (a2dp_ctrl_receive(common, &ack, 1) < 0) return -1; DEBUG("A2DP COMMAND %s DONE STATUS %d", dump_a2dp_ctrl_event(cmd), ack); if (ack == A2DP_CTRL_ACK_INCALL_FAILURE) return ack; if (ack != A2DP_CTRL_ACK_SUCCESS) return -1; return 0; } 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 int setup_hw_addr(char *hwaddr, const char *ifname) { struct sockaddr sockaddr; struct ifreq ifr; int ret, fd; ret = lxc_convert_mac(hwaddr, &sockaddr); if (ret) { ERROR("mac address '%s' conversion failed : %s", hwaddr, strerror(-ret)); return -1; } memcpy(ifr.ifr_name, ifname, IFNAMSIZ); ifr.ifr_name[IFNAMSIZ-1] = '\0'; memcpy((char *) &ifr.ifr_hwaddr, (char *) &sockaddr, sizeof(sockaddr)); fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd < 0) { ERROR("socket failure : %s", strerror(errno)); return -1; } ret = ioctl(fd, SIOCSIFHWADDR, &ifr); close(fd); if (ret) ERROR("ioctl failure : %s", strerror(errno)); DEBUG("mac address '%s' on '%s' has been setup", hwaddr, ifr.ifr_name); return ret; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error) { if (x + 1 > 10) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "x is bigger than 9"); return FALSE; } return x + 1; } Commit Message: CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int pagemap_open(struct inode *inode, struct file *file) { pr_warn_once("Bits 55-60 of /proc/PID/pagemap entries are about " "to stop being page-shift some time soon. See the " "linux/Documentation/vm/pagemap.txt for details.\n"); return 0; } Commit Message: pagemap: do not leak physical addresses to non-privileged userspace As pointed by recent post[1] on exploiting DRAM physical imperfection, /proc/PID/pagemap exposes sensitive information which can be used to do attacks. This disallows anybody without CAP_SYS_ADMIN to read the pagemap. [1] http://googleprojectzero.blogspot.com/2015/03/exploiting-dram-rowhammer-bug-to-gain.html [ Eventually we might want to do anything more finegrained, but for now this is the simple model. - Linus ] Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Konstantin Khlebnikov <[email protected]> Acked-by: Andy Lutomirski <[email protected]> Cc: Pavel Emelyanov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Mark Seaborn <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: void WebPage::releaseBackForwardEntry(BackForwardId id) const { HistoryItem* item = historyItemFromBackForwardId(id); ASSERT(item); item->deref(); } Commit Message: [BlackBerry] Adapt to new BlackBerry::Platform::TouchPoint API https://bugs.webkit.org/show_bug.cgi?id=105143 RIM PR 171941 Reviewed by Rob Buis. Internally reviewed by George Staikos. Source/WebCore: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. Also adapt to new method names and encapsulation of TouchPoint data members. No change in behavior, no new tests. * platform/blackberry/PlatformTouchPointBlackBerry.cpp: (WebCore::PlatformTouchPoint::PlatformTouchPoint): Source/WebKit/blackberry: TouchPoint instances now provide document coordinates for the viewport and content position of the touch event. The pixel coordinates stored in the TouchPoint should no longer be needed in WebKit. One exception is when passing events to a full screen plugin. Also adapt to new method names and encapsulation of TouchPoint data members. * Api/WebPage.cpp: (BlackBerry::WebKit::WebPage::touchEvent): (BlackBerry::WebKit::WebPage::touchPointAsMouseEvent): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchEventToFullScreenPlugin): (BlackBerry::WebKit::WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin): * WebKitSupport/InputHandler.cpp: (BlackBerry::WebKit::InputHandler::shouldRequestSpellCheckingOptionsForPoint): * WebKitSupport/InputHandler.h: (InputHandler): * WebKitSupport/TouchEventHandler.cpp: (BlackBerry::WebKit::TouchEventHandler::doFatFingers): (BlackBerry::WebKit::TouchEventHandler::handleTouchPoint): * WebKitSupport/TouchEventHandler.h: (TouchEventHandler): Tools: Adapt to new method names and encapsulation of TouchPoint data members. * DumpRenderTree/blackberry/EventSender.cpp: (addTouchPointCallback): (updateTouchPointCallback): (touchEndCallback): (releaseTouchPointCallback): (sendTouchEvent): git-svn-id: svn://svn.chromium.org/blink/trunk@137880 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: v8::Handle<v8::Value> V8DataView::getInt8Callback(const v8::Arguments& args) { INC_STATS("DOM.DataView.getInt8"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); DataView* imp = V8DataView::toNative(args.Holder()); ExceptionCode ec = 0; EXCEPTION_BLOCK(unsigned, byteOffset, toUInt32(args[0])); int8_t result = imp->getInt8(byteOffset, ec); if (UNLIKELY(ec)) { V8Proxy::setDOMException(ec, args.GetIsolate()); return v8::Handle<v8::Value>(); } return v8::Integer::New(result); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: 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: SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *, infop, int, options, struct rusage __user *, ru) { struct rusage r; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; } if (!err) { if (ru && copy_to_user(ru, &r, sizeof(struct rusage))) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; } Commit Message: fix infoleak in waitid(2) kernel_waitid() can return a PID, an error or 0. rusage is filled in the first case and waitid(2) rusage should've been copied out exactly in that case, *not* whenever kernel_waitid() has not returned an error. Compat variant shares that braino; none of kernel_wait4() callers do, so the below ought to fix it. Reported-and-tested-by: Alexander Potapenko <[email protected]> Fixes: ce72a16fa705 ("wait4(2)/waitid(2): separate copying rusage to userland") Cc: [email protected] # v4.13 Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-200 Target: 1 Example 2: Code: size_t LayerTreeHost::NumLayers() const { return layer_id_map_.size(); } Commit Message: (Reland) Discard compositor frames from unloaded web content This is a reland of https://codereview.chromium.org/2707243005/ with a small change to fix an uninitialized memory error that fails on MSAN bots. BUG=672847 [email protected], [email protected] CQ_INCLUDE_TRYBOTS=master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2731283003 Cr-Commit-Position: refs/heads/master@{#454954} CWE ID: CWE-362 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message); } } Commit Message: Improve buffer flow sanity check 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 void cs_cmd_flags(sourceinfo_t *si, int parc, char *parv[]) { chanacs_t *ca; mowgli_node_t *n; char *channel = parv[0]; char *target = sstrdup(parv[1]); char *flagstr = parv[2]; const char *str1; unsigned int addflags, removeflags, restrictflags; hook_channel_acl_req_t req; mychan_t *mc; if (parc < 1) { command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "FLAGS"); command_fail(si, fault_needmoreparams, _("Syntax: FLAGS <channel> [target] [flags]")); return; } mc = mychan_find(channel); if (!mc) { command_fail(si, fault_nosuch_target, _("Channel \2%s\2 is not registered."), channel); return; } if (metadata_find(mc, "private:close:closer") && (target || !has_priv(si, PRIV_CHAN_AUSPEX))) { command_fail(si, fault_noprivs, _("\2%s\2 is closed."), channel); return; } if (!target || (target && target[0] == '+' && flagstr == NULL)) { unsigned int flags = (target != NULL) ? flags_to_bitmask(target, 0) : 0; do_list(si, mc, flags); return; } /* * following conditions are for compatibility with Anope just to avoid a whole clusterfuck * of confused users caused by their 'innovation.' yeah, that's a word for it alright. * * anope 1.9's shiny new FLAGS command has: * * FLAGS #channel LIST * FLAGS #channel MODIFY user flagspec * FLAGS #channel CLEAR * * obviously they do not support the atheme syntax, because lets face it, they like to * 'innovate.' this is, of course, hilarious for obvious reasons. never mind that we * *invented* the FLAGS system for channel ACLs, so you would think they would find it * worthwhile to be compatible here. i guess that would have been too obvious or something * about their whole 'stealing our design' thing that they have been doing in 1.9 since the * beginning... or do i mean 'innovating?' * * anyway we rewrite the commands as appropriate in the two if blocks below so that they * are processed by the flags code as the user would intend. obviously, we're not really * capable of handling the anope flag model (which makes honestly zero sense to me, and is * extremely complex which kind of misses the entire point of the flags UI design...) so if * some user tries passing anope flags, it will probably be hilarious. the good news is * most of the anope flags tie up to atheme flags in some weird way anyway (probably because, * i don't know, they copied the entire design and then fucked it up? yeah. probably that.) * * --nenolod */ else if (!strcasecmp(target, "LIST") && myentity_find_ext(target) == NULL) { do_list(si, mc, 0); free(target); return; } else if (!strcasecmp(target, "CLEAR") && myentity_find_ext(target) == NULL) { free(target); if (!chanacs_source_has_flag(mc, si, CA_FOUNDER)) { command_fail(si, fault_noprivs, "You are not authorized to perform this operation."); return; } mowgli_node_t *tn; MOWGLI_ITER_FOREACH_SAFE(n, tn, mc->chanacs.head) { ca = n->data; if (ca->level & CA_FOUNDER) continue; object_unref(ca); } logcommand(si, CMDLOG_DO, "CLEAR:FLAGS: \2%s\2", mc->name); command_success_nodata(si, _("Cleared flags in \2%s\2."), mc->name); return; } else if (!strcasecmp(target, "MODIFY") && myentity_find_ext(target) == NULL) { free(target); if (parc < 3) { command_fail(si, fault_needmoreparams, STR_INSUFFICIENT_PARAMS, "FLAGS"); command_fail(si, fault_needmoreparams, _("Syntax: FLAGS <#channel> MODIFY [target] <flags>")); return; } flagstr = strchr(parv[2], ' '); if (flagstr) *flagstr++ = '\0'; target = strdup(parv[2]); } { myentity_t *mt; if (!si->smu) { command_fail(si, fault_noprivs, _("You are not logged in.")); return; } if (!flagstr) { if (!(mc->flags & MC_PUBACL) && !chanacs_source_has_flag(mc, si, CA_ACLVIEW)) { command_fail(si, fault_noprivs, _("You are not authorized to execute this command.")); return; } if (validhostmask(target)) ca = chanacs_find_host_literal(mc, target, 0); else { if (!(mt = myentity_find_ext(target))) { command_fail(si, fault_nosuch_target, _("\2%s\2 is not registered."), target); return; } free(target); target = sstrdup(mt->name); ca = chanacs_find_literal(mc, mt, 0); } if (ca != NULL) { str1 = bitmask_to_flags2(ca->level, 0); command_success_string(si, str1, _("Flags for \2%s\2 in \2%s\2 are \2%s\2."), target, channel, str1); } else command_success_string(si, "", _("No flags for \2%s\2 in \2%s\2."), target, channel); logcommand(si, CMDLOG_GET, "FLAGS: \2%s\2 on \2%s\2", mc->name, target); return; } /* founder may always set flags -- jilles */ restrictflags = chanacs_source_flags(mc, si); if (restrictflags & CA_FOUNDER) restrictflags = ca_all; else { if (!(restrictflags & CA_FLAGS)) { /* allow a user to remove their own access * even without +f */ if (restrictflags & CA_AKICK || si->smu == NULL || irccasecmp(target, entity(si->smu)->name) || strcmp(flagstr, "-*")) { command_fail(si, fault_noprivs, _("You are not authorized to execute this command.")); return; } } if (irccasecmp(target, entity(si->smu)->name)) restrictflags = allow_flags(mc, restrictflags); else restrictflags |= allow_flags(mc, restrictflags); } if (*flagstr == '+' || *flagstr == '-' || *flagstr == '=') { flags_make_bitmasks(flagstr, &addflags, &removeflags); if (addflags == 0 && removeflags == 0) { command_fail(si, fault_badparams, _("No valid flags given, use /%s%s HELP FLAGS for a list"), ircd->uses_rcommand ? "" : "msg ", chansvs.me->disp); return; } } else { addflags = get_template_flags(mc, flagstr); if (addflags == 0) { /* Hack -- jilles */ if (*target == '+' || *target == '-' || *target == '=') command_fail(si, fault_badparams, _("Usage: FLAGS %s [target] [flags]"), mc->name); else command_fail(si, fault_badparams, _("Invalid template name given, use /%s%s TEMPLATE %s for a list"), ircd->uses_rcommand ? "" : "msg ", chansvs.me->disp, mc->name); return; } removeflags = ca_all & ~addflags; } if (!validhostmask(target)) { if (!(mt = myentity_find_ext(target))) { command_fail(si, fault_nosuch_target, _("\2%s\2 is not registered."), target); return; } free(target); target = sstrdup(mt->name); ca = chanacs_open(mc, mt, NULL, true, entity(si->smu)); if (ca->level & CA_FOUNDER && removeflags & CA_FLAGS && !(removeflags & CA_FOUNDER)) { command_fail(si, fault_noprivs, _("You may not remove a founder's +f access.")); return; } if (ca->level & CA_FOUNDER && removeflags & CA_FOUNDER && mychan_num_founders(mc) == 1) { command_fail(si, fault_noprivs, _("You may not remove the last founder.")); return; } if (!(ca->level & CA_FOUNDER) && addflags & CA_FOUNDER) { if (mychan_num_founders(mc) >= chansvs.maxfounders) { command_fail(si, fault_noprivs, _("Only %d founders allowed per channel."), chansvs.maxfounders); chanacs_close(ca); return; } if (!myentity_can_register_channel(mt)) { command_fail(si, fault_toomany, _("\2%s\2 has too many channels registered."), mt->name); chanacs_close(ca); return; } if (!myentity_allow_foundership(mt)) { command_fail(si, fault_toomany, _("\2%s\2 cannot take foundership of a channel."), mt->name); chanacs_close(ca); return; } } if (addflags & CA_FOUNDER) addflags |= CA_FLAGS, removeflags &= ~CA_FLAGS; /* If NEVEROP is set, don't allow adding new entries * except sole +b. Adding flags if the current level * is +b counts as adding an entry. * -- jilles */ /* XXX: not all entities are users */ if (isuser(mt) && (MU_NEVEROP & user(mt)->flags && addflags != CA_AKICK && addflags != 0 && (ca->level == 0 || ca->level == CA_AKICK))) { command_fail(si, fault_noprivs, _("\2%s\2 does not wish to be added to channel access lists (NEVEROP set)."), mt->name); chanacs_close(ca); return; } if (ca->level == 0 && chanacs_is_table_full(ca)) { command_fail(si, fault_toomany, _("Channel %s access list is full."), mc->name); chanacs_close(ca); return; } req.ca = ca; req.oldlevel = ca->level; if (!chanacs_modify(ca, &addflags, &removeflags, restrictflags)) { command_fail(si, fault_noprivs, _("You are not allowed to set \2%s\2 on \2%s\2 in \2%s\2."), bitmask_to_flags2(addflags, removeflags), mt->name, mc->name); chanacs_close(ca); return; } req.newlevel = ca->level; hook_call_channel_acl_change(&req); chanacs_close(ca); } else { if (addflags & CA_FOUNDER) { command_fail(si, fault_badparams, _("You may not set founder status on a hostmask.")); return; } ca = chanacs_open(mc, NULL, target, true, entity(si->smu)); if (ca->level == 0 && chanacs_is_table_full(ca)) { command_fail(si, fault_toomany, _("Channel %s access list is full."), mc->name); chanacs_close(ca); return; } req.ca = ca; req.oldlevel = ca->level; if (!chanacs_modify(ca, &addflags, &removeflags, restrictflags)) { command_fail(si, fault_noprivs, _("You are not allowed to set \2%s\2 on \2%s\2 in \2%s\2."), bitmask_to_flags2(addflags, removeflags), target, mc->name); chanacs_close(ca); return; } req.newlevel = ca->level; hook_call_channel_acl_change(&req); chanacs_close(ca); } if ((addflags | removeflags) == 0) { command_fail(si, fault_nochange, _("Channel access to \2%s\2 for \2%s\2 unchanged."), channel, target); return; } flagstr = bitmask_to_flags2(addflags, removeflags); command_success_nodata(si, _("Flags \2%s\2 were set on \2%s\2 in \2%s\2."), flagstr, target, channel); logcommand(si, CMDLOG_SET, "FLAGS: \2%s\2 \2%s\2 \2%s\2", mc->name, target, flagstr); verbose(mc, "\2%s\2 set flags \2%s\2 on \2%s\2", get_source_name(si), flagstr, target); } free(target); } Commit Message: chanserv/flags: make Anope FLAGS compatibility an option Previously, ChanServ FLAGS behavior could be modified by registering or dropping the keyword nicks "LIST", "CLEAR", and "MODIFY". Now, a configuration option is available that when turned on (default), disables registration of these keyword nicks and enables this compatibility feature. When turned off, registration of these keyword nicks is possible, and compatibility to Anope's FLAGS command is disabled. Fixes atheme/atheme#397 CWE ID: CWE-284 Target: 1 Example 2: Code: qtdemux_sink_activate (GstPad * sinkpad) { if (gst_pad_check_pull_range (sinkpad)) return gst_pad_activate_pull (sinkpad, TRUE); else return gst_pad_activate_push (sinkpad, TRUE); } 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: nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_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 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 send_event (int fd, uint16_t type, uint16_t code, int32_t value) { struct uinput_event event; BTIF_TRACE_DEBUG("%s type:%u code:%u value:%d", __FUNCTION__, type, code, value); memset(&event, 0, sizeof(event)); event.type = type; event.code = code; event.value = value; return write(fd, &event, sizeof(event)); } 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: String DescendantInvalidationSetToIdString(const InvalidationSet& set) { return ToHexString(&set); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Commit-Queue: Andrey Lushnikov <[email protected]> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int lxcfs_getattr(const char *path, struct stat *sb) { if (strcmp(path, "/") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } if (strncmp(path, "/cgroup", 7) == 0) { return cg_getattr(path, sb); } if (strncmp(path, "/proc", 5) == 0) { return proc_getattr(path, sb); } return -EINVAL; } Commit Message: Implement privilege check when moving tasks When writing pids to a tasks file in lxcfs, lxcfs was checking for privilege over the tasks file but not over the pid being moved. Since the cgm_movepid request is done as root on the host, not with the requestor's credentials, we must copy the check which cgmanager was doing to ensure that the requesting task is allowed to change the victim task's cgroup membership. This is CVE-2015-1344 https://bugs.launchpad.net/ubuntu/+source/lxcfs/+bug/1512854 Signed-off-by: Serge Hallyn <[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: read_gif(Gif_Reader *grr, int read_flags, const char* landmark, Gif_ReadErrorHandler handler) { Gif_Stream *gfs; Gif_Image *gfi; Gif_Context gfc; int unknown_block_type = 0; if (gifgetc(grr) != 'G' || gifgetc(grr) != 'I' || gifgetc(grr) != 'F') return 0; (void)gifgetc(grr); (void)gifgetc(grr); (void)gifgetc(grr); gfs = Gif_NewStream(); gfi = Gif_NewImage(); gfc.stream = gfs; gfc.prefix = Gif_NewArray(Gif_Code, GIF_MAX_CODE); gfc.suffix = Gif_NewArray(uint8_t, GIF_MAX_CODE); gfc.length = Gif_NewArray(uint16_t, GIF_MAX_CODE); gfc.handler = handler; gfc.gfi = gfi; gfc.errors[0] = gfc.errors[1] = 0; if (!gfs || !gfi || !gfc.prefix || !gfc.suffix || !gfc.length) goto done; gfs->landmark = landmark; GIF_DEBUG(("\nGIF ")); if (!read_logical_screen_descriptor(gfs, grr)) goto done; GIF_DEBUG(("logscrdesc ")); while (!gifeof(grr)) { uint8_t block = gifgetbyte(grr); switch (block) { case ',': /* image block */ GIF_DEBUG(("imageread %d ", gfs->nimages)); gfi->identifier = last_name; last_name = 0; if (!Gif_AddImage(gfs, gfi)) goto done; else if (!read_image(grr, &gfc, gfi, read_flags)) { Gif_RemoveImage(gfs, gfs->nimages - 1); gfi = 0; goto done; } gfc.gfi = gfi = Gif_NewImage(); if (!gfi) goto done; break; case ';': /* terminator */ GIF_DEBUG(("term\n")); goto done; case '!': /* extension */ block = gifgetbyte(grr); GIF_DEBUG(("ext(0x%02X) ", block)); switch (block) { case 0xF9: read_graphic_control_extension(&gfc, gfi, grr); break; case 0xCE: last_name = suck_data(last_name, 0, grr); break; case 0xFE: if (!read_comment_extension(gfi, grr)) goto done; break; case 0xFF: read_application_extension(&gfc, grr); break; default: read_unknown_extension(&gfc, grr, block, 0, 0); break; } break; default: if (!unknown_block_type) { char buf[256]; sprintf(buf, "unknown block type %d at file offset %u", block, grr->pos - 1); gif_read_error(&gfc, 1, buf); unknown_block_type = 1; } break; } } done: /* Move comments and extensions after last image into stream. */ if (gfs && gfi) { Gif_Extension* gfex; gfs->end_comment = gfi->comment; gfi->comment = 0; gfs->end_extension_list = gfi->extension_list; gfi->extension_list = 0; for (gfex = gfs->end_extension_list; gfex; gfex = gfex->next) gfex->image = NULL; } Gif_DeleteImage(gfi); Gif_DeleteArray(last_name); Gif_DeleteArray(gfc.prefix); Gif_DeleteArray(gfc.suffix); Gif_DeleteArray(gfc.length); gfc.gfi = 0; if (gfs) gfs->errors = gfc.errors[1]; if (gfs && gfc.errors[1] == 0 && !(read_flags & GIF_READ_TRAILING_GARBAGE_OK) && !grr->eofer(grr)) gif_read_error(&gfc, 0, "trailing garbage after GIF ignored"); /* finally, export last message */ gif_read_error(&gfc, -1, 0); return gfs; } Commit Message: gif_read: Set last_name = NULL unconditionally. With a non-malicious GIF, last_name is set to NULL when a name extension is followed by an image. Reported in #117, via Debian, via a KAIST fuzzing program. CWE ID: CWE-415 Target: 1 Example 2: Code: static void reflectUnsignedShortAttributeAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; TestObjectPythonV8Internal::reflectUnsignedShortAttributeAttributeSetter(jsValue, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: gsicc_set_device_blackptcomp(gx_device *dev, gsicc_blackptcomp_t blackptcomp, gsicc_profile_types_t profile_type) { int code = 0; cmm_dev_profile_t *profile_struct; if (dev->procs.get_profile == NULL) { profile_struct = dev->icc_struct; } else { code = dev_proc(dev, get_profile)(dev, &profile_struct); } if (profile_struct == NULL) return 0; profile_struct->rendercond[profile_type].black_point_comp = blackptcomp; return code; } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: px_crypt_des(const char *key, const char *setting) { int i; uint32 count, salt, l, r0, r1, keybuf[2]; char *p; uint8 *q; static char output[21]; if (!des_initialised) des_init(); /* * Copy the key, shifting each character up by one bit and padding with * zeros. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8) { if ((*q++ = *key << 1)) key++; } if (des_setkey((char *) keybuf)) #ifndef DISABLE_XDES if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: setting - underscore, 4 bytes of count, 4 bytes of * salt key - unlimited characters */ for (i = 1, count = 0L; i < 5; i++) count |= ascii_to_bin(setting[i]) << (i - 1) * 6; for (i = 5, salt = 0L; i < 9; i++) salt |= ascii_to_bin(setting[i]) << (i - 5) * 6; while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1)) return (NULL); /* * And XOR with the next 8 characters of the key. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8 && *key) *q++ ^= *key++ << 1; if (des_setkey((char *) keybuf)) return (NULL); } strncpy(output, setting, 9); /* * Double check that we weren't given a short setting. If we were, the * above code will probably have created weird values for count and * salt, but we don't really care. Just make sure the output string * doesn't have an extra NUL in it. */ output[9] = '\0'; p = output + strlen(output); } else #endif /* !DISABLE_XDES */ { /* * "old"-style: setting - 2 bytes of salt key - up to 8 characters */ count = 25; salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); output[0] = setting[0]; /* * If the encrypted password that the salt was extracted from is only * 1 character long, the salt will be corrupted. We need to ensure * that the output string doesn't have an extra NUL in it! */ output[1] = setting[1] ? setting[1] : output[0]; p = output + 2; } setup_salt(salt); /* * Do it. */ if (do_des(0L, 0L, &r0, &r1, count)) return (NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = r1 << 2; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; *p = 0; return (output); } Commit Message: CWE ID: CWE-310 Target: 1 Example 2: Code: xmlCreateFileParserCtxt(const char *filename) { return(xmlCreateURLParserCtxt(filename, 0)); } Commit Message: DO NOT MERGE: Add validation for eternal enities https://bugzilla.gnome.org/show_bug.cgi?id=780691 Bug: 36556310 Change-Id: I9450743e167c3c73af5e4071f3fc85e81d061648 (cherry picked from commit bef9af3d89d241bcb518c20cba6da2a2fd9ba049) CWE ID: CWE-611 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: setcolor_cont(i_ctx_t *i_ctx_p) { ref arr, *parr = &arr; es_ptr ep = esp; int i=0, code = 0, usealternate, stage, stack_depth, CIESubst = 0, IsICC = 0; unsigned int depth; PS_colour_space_t *obj; stack_depth = (int)ep[-3].value.intval; depth = (unsigned int)ep[-2].value.intval; stage = (int)ep[-1].value.intval; /* If we get a continuation from a sub-procedure, we will want to come back * here afterward, to do any remaining spaces. We need to set up for that now. * so that our continuation is ahead of the sub-proc's continuation. */ check_estack(1); push_op_estack(setcolor_cont); while (code == 0) { ref_assign(&arr, ep); /* Run along the nested color spaces until we get to the first one * that we haven't yet processed (given by 'depth') */ for (i=0;i<=depth;i++) { code = get_space_object(i_ctx_p, parr, &obj); if (code < 0) return code; if (strcmp(obj->name, "ICCBased") == 0) IsICC = 1; if (i < (depth)) { if (!obj->alternateproc) { return_error(gs_error_typecheck); } code = obj->alternateproc(i_ctx_p, parr, &parr, &CIESubst); if (code < 0) return code; } } if (obj->runtransformproc) { code = obj->runtransformproc(i_ctx_p, &istate->colorspace[0].array, &usealternate, &stage, &stack_depth); make_int(&ep[-3], stack_depth); make_int(&ep[-1], stage); if (code != 0) { return code; } make_int(&ep[-2], ++depth); if (!usealternate) break; } else break; } /* Hack to work around broken PDF files in Bug696690 and Bug696120 * We want setcolor to actually exercise the link creation in case * the profile is broken, in whcih case we may choose to use a different * colour space altogether. */ if (IsICC && depth == 0) { code = gx_set_dev_color(i_ctx_p->pgs); if (code < 0) return code; } /* Remove our next continuation and our data */ obj->numcomponents(i_ctx_p, parr, &i); pop(i); esp -= 5; return o_pop_estack; } Commit Message: CWE ID: CWE-704 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_tp_trap(struct pt_regs *regs, unsigned int instr) { int reg = (instr >> 12) & 15; if (reg == 15) return 1; regs->uregs[reg] = current_thread_info()->tp_value; regs->ARM_pc += 4; return 0; } Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to prevent it from being used as a covert channel between two tasks. There are more and more applications coming to Windows RT, Wine could support them, but mostly they expect to have the thread environment block (TEB) in TPIDRURW. This patch preserves that register per thread instead of clearing it. Unlike the TPIDRURO, which is already switched, the TPIDRURW can be updated from userspace so needs careful treatment in the case that we modify TPIDRURW and call fork(). To avoid this we must always read TPIDRURW in copy_thread. Signed-off-by: André Hentschel <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Jonathan Austin <[email protected]> Signed-off-by: Russell King <[email protected]> CWE ID: CWE-264 Target: 1 Example 2: Code: void SplitStringAlongWhitespace(const std::wstring& str, std::vector<std::wstring>* result) { SplitStringAlongWhitespaceT(str, result); } Commit Message: wstring: remove wstring version of SplitString Retry of r84336. BUG=23581 Review URL: http://codereview.chromium.org/6930047 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void GpuProcessHost::OnChannelEstablished( const IPC::ChannelHandle& channel_handle) { DCHECK(gpu_process_); EstablishChannelCallback callback = channel_requests_.front(); channel_requests_.pop(); if (!channel_handle.name.empty() && !GpuDataManagerImpl::GetInstance()->GpuAccessAllowed()) { Send(new GpuMsg_CloseChannel(channel_handle)); EstablishChannelError(callback, IPC::ChannelHandle(), base::kNullProcessHandle, content::GPUInfo()); RouteOnUIThread(GpuHostMsg_OnLogMessage( logging::LOG_WARNING, "WARNING", "Hardware acceleration is unavailable.")); return; } callback.Run(channel_handle, gpu_process_, GpuDataManagerImpl::GetInstance()->GetGPUInfo()); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: TestPaintArtifact& TestPaintArtifact::Chunk( scoped_refptr<const TransformPaintPropertyNode> transform, scoped_refptr<const ClipPaintPropertyNode> clip, scoped_refptr<const EffectPaintPropertyNode> effect) { return Chunk(NewClient(), transform, clip, effect); } 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: 1 Example 2: Code: static void reflectLongAttributeAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); TestObjectPythonV8Internal::reflectLongAttributeAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) { GF_Err e = gf_isom_box_array_read(s, bs, dinf_AddBox); if (e) { return e; } if (!((GF_DataInformationBox *)s)->dref) { GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Missing dref box in dinf\n")); ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); } return GF_OK; } Commit Message: prevent dref memleak on invalid input (#1183) CWE ID: CWE-400 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x <= frameRight && y >= frameTop && y <= frameBottom; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264 Target: 1 Example 2: Code: void JSTestNamedConstructorNamedConstructor::finishCreation(ExecState* exec, JSDOMGlobalObject* globalObject) { Base::finishCreation(globalObject); ASSERT(inherits(&s_info)); putDirect(exec->globalData(), exec->propertyNames().prototype, JSTestNamedConstructorPrototype::self(exec, globalObject), None); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: xsltParseStylesheetAttributeSet(xsltStylesheetPtr style, xmlNodePtr cur) { const xmlChar *ncname; const xmlChar *prefix; xmlChar *value; xmlNodePtr child; xsltAttrElemPtr attrItems; if ((cur == NULL) || (style == NULL) || (cur->type != XML_ELEMENT_NODE)) return; value = xmlGetNsProp(cur, (const xmlChar *)"name", NULL); if (value == NULL) { xsltGenericError(xsltGenericErrorContext, "xsl:attribute-set : name is missing\n"); return; } ncname = xsltSplitQName(style->dict, value, &prefix); xmlFree(value); value = NULL; if (style->attributeSets == NULL) { #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "creating attribute set table\n"); #endif style->attributeSets = xmlHashCreate(10); } if (style->attributeSets == NULL) return; attrItems = xmlHashLookup2(style->attributeSets, ncname, prefix); /* * Parse the content. Only xsl:attribute elements are allowed. */ child = cur->children; while (child != NULL) { /* * Report invalid nodes. */ if ((child->type != XML_ELEMENT_NODE) || (child->ns == NULL) || (! IS_XSLT_ELEM(child))) { if (child->type == XML_ELEMENT_NODE) xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child %s\n", child->name); else xsltTransformError(NULL, style, child, "xsl:attribute-set : child of unexpected type\n"); } else if (!IS_XSLT_NAME(child, "attribute")) { xsltTransformError(NULL, style, child, "xsl:attribute-set : unexpected child xsl:%s\n", child->name); } else { #ifdef XSLT_REFACTORED xsltAttrElemPtr nextAttr, curAttr; /* * Process xsl:attribute * --------------------- */ #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * The following was taken over from * xsltAddAttrElemList(). */ if (attrItems == NULL) { attrItems = xsltNewAttrElem(child); } else { curAttr = attrItems; while (curAttr != NULL) { nextAttr = curAttr->next; if (curAttr->attr == child) { /* * URGENT TODO: Can somebody explain * why attrItems is set to curAttr * here? Is this somehow related to * avoidance of recursions? */ attrItems = curAttr; goto next_child; } if (curAttr->next == NULL) curAttr->next = xsltNewAttrElem(child); curAttr = nextAttr; } } /* * Parse the xsl:attribute and its content. */ xsltParseAnyXSLTElem(XSLT_CCTXT(style), child); #else #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "add attribute to list %s\n", ncname); #endif /* * OLD behaviour: */ attrItems = xsltAddAttrElemList(attrItems, child); #endif } #ifdef XSLT_REFACTORED next_child: #endif child = child->next; } /* * Process attribue "use-attribute-sets". */ /* TODO check recursion */ value = xmlGetNsProp(cur, (const xmlChar *)"use-attribute-sets", NULL); if (value != NULL) { const xmlChar *curval, *endval; curval = value; while (*curval != 0) { while (IS_BLANK(*curval)) curval++; if (*curval == 0) break; endval = curval; while ((*endval != 0) && (!IS_BLANK(*endval))) endval++; curval = xmlDictLookup(style->dict, curval, endval - curval); if (curval) { const xmlChar *ncname2 = NULL; const xmlChar *prefix2 = NULL; xsltAttrElemPtr refAttrItems; #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "xsl:attribute-set : %s adds use %s\n", ncname, curval); #endif ncname2 = xsltSplitQName(style->dict, curval, &prefix2); refAttrItems = xsltNewAttrElem(NULL); if (refAttrItems != NULL) { refAttrItems->set = ncname2; refAttrItems->ns = prefix2; attrItems = xsltMergeAttrElemList(style, attrItems, refAttrItems); xsltFreeAttrElem(refAttrItems); } } curval = endval; } xmlFree(value); value = NULL; } /* * Update the value */ /* * TODO: Why is this dummy entry needed.? */ if (attrItems == NULL) attrItems = xsltNewAttrElem(NULL); xmlHashUpdateEntry2(style->attributeSets, ncname, prefix, attrItems, NULL); #ifdef WITH_XSLT_DEBUG_ATTRIBUTES xsltGenericDebug(xsltGenericDebugContext, "updated attribute list %s\n", ncname); #endif } 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: void grubfs_free (GrubFS *gf) { if (gf) { if (gf->file && gf->file->device) free (gf->file->device->disk); free (gf->file); free (gf); } } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119 Target: 1 Example 2: Code: static int do_raw_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (optname == ICMP_FILTER) { if (inet_sk(sk)->inet_num != IPPROTO_ICMP) return -EOPNOTSUPP; else return raw_geticmpfilter(sk, optval, optlen); } return -ENOPROTOOPT; } 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: const UsbDeviceHandle::TransferCallback& callback() const { return callback_; } Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <[email protected]> Commit-Queue: Taiju Tsuiki <[email protected]> Cr-Commit-Position: refs/heads/master@{#478549} 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 rawv6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name; struct sk_buff *skb; size_t copied; int err; if (flags & MSG_OOB) return -EOPNOTSUPP; if (addr_len) *addr_len=sizeof(*sin6); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (copied > len) { copied = len; msg->msg_flags |= MSG_TRUNC; } if (skb_csum_unnecessary(skb)) { err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else if (msg->msg_flags&MSG_TRUNC) { if (__skb_checksum_complete(skb)) goto csum_copy_err; err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); } else { err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (err) goto out_free; /* Copy the address. */ if (sin6) { sin6->sin6_family = AF_INET6; sin6->sin6_port = 0; sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, IP6CB(skb)->iif); } sock_recv_ts_and_drops(msg, sk, skb); if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); err = copied; if (flags & MSG_TRUNC) err = skb->len; out_free: skb_free_datagram(sk, skb); out: return err; csum_copy_err: skb_kill_datagram(sk, skb, flags); /* Error for blocking case is chosen to masquerade as some normal condition. */ err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH; goto out; } Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls Only update *addr_len when we actually fill in sockaddr, otherwise we can return uninitialized memory from the stack to the caller in the recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL) checks because we only get called with a valid addr_len pointer either from sock_common_recvmsg or inet_recvmsg. If a blocking read waits on a socket which is concurrently shut down we now return zero and set msg_msgnamelen to 0. Reported-by: mpb <[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-200 Target: 1 Example 2: Code: unsigned HTMLSelectElement::length() const { unsigned options = 0; const Vector<HTMLElement*>& items = listItems(); for (unsigned i = 0; i < items.size(); ++i) { if (items[i]->hasTagName(optionTag)) ++options; } return options; } Commit Message: SelectElement should remove an option when null is assigned by indexed setter Fix bug embedded in r151449 see http://src.chromium.org/viewvc/blink?revision=151449&view=revision [email protected], [email protected], [email protected] BUG=262365 TEST=fast/forms/select/select-assign-null.html Review URL: https://chromiumcodereview.appspot.com/19947008 git-svn-id: svn://svn.chromium.org/blink/trunk@154743 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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: extern "C" int EffectCreate(const effect_uuid_t *uuid, int32_t sessionId, int32_t ioId, effect_handle_t *pHandle){ int ret; int i; int length = sizeof(gDescriptors) / sizeof(const effect_descriptor_t *); const effect_descriptor_t *desc; ALOGV("\t\nEffectCreate start"); if (pHandle == NULL || uuid == NULL){ ALOGV("\tLVM_ERROR : EffectCreate() called with NULL pointer"); return -EINVAL; } for (i = 0; i < length; i++) { desc = gDescriptors[i]; if (memcmp(uuid, &desc->uuid, sizeof(effect_uuid_t)) == 0) { ALOGV("\tEffectCreate - UUID matched Reverb type %d, UUID = %x", i, desc->uuid.timeLow); break; } } if (i == length) { return -ENOENT; } ReverbContext *pContext = new ReverbContext; pContext->itfe = &gReverbInterface; pContext->hInstance = NULL; pContext->auxiliary = false; if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY){ pContext->auxiliary = true; ALOGV("\tEffectCreate - AUX"); }else{ ALOGV("\tEffectCreate - INS"); } pContext->preset = false; if (memcmp(&desc->type, SL_IID_PRESETREVERB, sizeof(effect_uuid_t)) == 0) { pContext->preset = true; pContext->curPreset = REVERB_PRESET_LAST + 1; pContext->nextPreset = REVERB_DEFAULT_PRESET; ALOGV("\tEffectCreate - PRESET"); }else{ ALOGV("\tEffectCreate - ENVIRONMENTAL"); } ALOGV("\tEffectCreate - Calling Reverb_init"); ret = Reverb_init(pContext); if (ret < 0){ ALOGV("\tLVM_ERROR : EffectCreate() init failed"); delete pContext; return ret; } *pHandle = (effect_handle_t)pContext; #ifdef LVM_PCM pContext->PcmInPtr = NULL; pContext->PcmOutPtr = NULL; pContext->PcmInPtr = fopen("/data/tmp/reverb_pcm_in.pcm", "w"); pContext->PcmOutPtr = fopen("/data/tmp/reverb_pcm_out.pcm", "w"); if((pContext->PcmInPtr == NULL)|| (pContext->PcmOutPtr == NULL)){ return -EINVAL; } #endif pContext->InFrames32 = (LVM_INT32 *)malloc(LVREV_MAX_FRAME_SIZE * sizeof(LVM_INT32) * 2); pContext->OutFrames32 = (LVM_INT32 *)malloc(LVREV_MAX_FRAME_SIZE * sizeof(LVM_INT32) * 2); ALOGV("\tEffectCreate %p, size %zu", pContext, sizeof(ReverbContext)); ALOGV("\tEffectCreate end\n"); return 0; } /* end EffectCreate */ 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 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 AppCacheDispatcherHost::OnChannelConnected(int32 peer_pid) { if (appcache_service_.get()) { backend_impl_.Initialize( appcache_service_.get(), &frontend_proxy_, process_id_); get_status_callback_ = base::Bind(&AppCacheDispatcherHost::GetStatusCallback, base::Unretained(this)); start_update_callback_ = base::Bind(&AppCacheDispatcherHost::StartUpdateCallback, base::Unretained(this)); swap_cache_callback_ = base::Bind(&AppCacheDispatcherHost::SwapCacheCallback, base::Unretained(this)); } } Commit Message: AppCache: Use WeakPtr<> to fix a potential uaf bug. BUG=554908 Review URL: https://codereview.chromium.org/1441683004 Cr-Commit-Position: refs/heads/master@{#359930} CWE ID: Target: 1 Example 2: Code: static int btrfs_unlink(struct inode *dir, struct dentry *dentry) { struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; struct inode *inode = d_inode(dentry); int ret; trans = __unlink_start_trans(dir); if (IS_ERR(trans)) return PTR_ERR(trans); btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0); ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry), dentry->d_name.name, dentry->d_name.len); if (ret) goto out; if (inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, inode); if (ret) goto out; } out: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); return ret; } 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: static void logi_dj_recv_add_djhid_device(struct dj_receiver_dev *djrcv_dev, struct dj_report *dj_report) { /* Called in delayed work context */ struct hid_device *djrcv_hdev = djrcv_dev->hdev; struct usb_interface *intf = to_usb_interface(djrcv_hdev->dev.parent); struct usb_device *usbdev = interface_to_usbdev(intf); struct hid_device *dj_hiddev; struct dj_device *dj_dev; /* Device index goes from 1 to 6, we need 3 bytes to store the * semicolon, the index, and a null terminator */ unsigned char tmpstr[3]; if (dj_report->report_params[DEVICE_PAIRED_PARAM_SPFUNCTION] & SPFUNCTION_DEVICE_LIST_EMPTY) { dbg_hid("%s: device list is empty\n", __func__); djrcv_dev->querying_devices = false; return; } if ((dj_report->device_index < DJ_DEVICE_INDEX_MIN) || (dj_report->device_index > DJ_DEVICE_INDEX_MAX)) { dev_err(&djrcv_hdev->dev, "%s: invalid device index:%d\n", __func__, dj_report->device_index); return; } if (djrcv_dev->paired_dj_devices[dj_report->device_index]) { /* The device is already known. No need to reallocate it. */ dbg_hid("%s: device is already known\n", __func__); return; } dj_hiddev = hid_allocate_device(); if (IS_ERR(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: hid_allocate_device failed\n", __func__); return; } dj_hiddev->ll_driver = &logi_dj_ll_driver; dj_hiddev->dev.parent = &djrcv_hdev->dev; dj_hiddev->bus = BUS_USB; dj_hiddev->vendor = le16_to_cpu(usbdev->descriptor.idVendor); dj_hiddev->product = le16_to_cpu(usbdev->descriptor.idProduct); snprintf(dj_hiddev->name, sizeof(dj_hiddev->name), "Logitech Unifying Device. Wireless PID:%02x%02x", dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_MSB], dj_report->report_params[DEVICE_PAIRED_PARAM_EQUAD_ID_LSB]); usb_make_path(usbdev, dj_hiddev->phys, sizeof(dj_hiddev->phys)); snprintf(tmpstr, sizeof(tmpstr), ":%d", dj_report->device_index); strlcat(dj_hiddev->phys, tmpstr, sizeof(dj_hiddev->phys)); dj_dev = kzalloc(sizeof(struct dj_device), GFP_KERNEL); if (!dj_dev) { dev_err(&djrcv_hdev->dev, "%s: failed allocating dj_device\n", __func__); goto dj_device_allocate_fail; } dj_dev->reports_supported = get_unaligned_le32( dj_report->report_params + DEVICE_PAIRED_RF_REPORT_TYPE); dj_dev->hdev = dj_hiddev; dj_dev->dj_receiver_dev = djrcv_dev; dj_dev->device_index = dj_report->device_index; dj_hiddev->driver_data = dj_dev; djrcv_dev->paired_dj_devices[dj_report->device_index] = dj_dev; if (hid_add_device(dj_hiddev)) { dev_err(&djrcv_hdev->dev, "%s: failed adding dj_device\n", __func__); goto hid_add_device_fail; } return; hid_add_device_fail: djrcv_dev->paired_dj_devices[dj_report->device_index] = NULL; kfree(dj_dev); dj_device_allocate_fail: hid_destroy_device(dj_hiddev); } Commit Message: HID: logitech: perform bounds checking on device_id early enough device_index is a char type and the size of paired_dj_deivces is 7 elements, therefore proper bounds checking has to be applied to device_index before it is used. We are currently performing the bounds checking in logi_dj_recv_add_djhid_device(), which is too late, as malicious device could send REPORT_TYPE_NOTIF_DEVICE_UNPAIRED early enough and trigger the problem in one of the report forwarding functions called from logi_dj_raw_event(). Fix this by performing the check at the earliest possible ocasion in logi_dj_raw_event(). Cc: [email protected] Reported-by: Ben Hawkes <[email protected]> Reviewed-by: Benjamin Tissoires <[email protected]> Signed-off-by: Jiri Kosina <[email protected]> CWE ID: CWE-119 Output:
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: telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print) { int i, x; u_int c; const u_char *osp, *p; #define FETCH(c, sp, length) \ do { \ if (length < 1) \ goto pktend; \ ND_TCHECK(*sp); \ c = *sp++; \ length--; \ } while (0) osp = sp; FETCH(c, sp, length); if (c != IAC) goto pktend; FETCH(c, sp, length); if (c == IAC) { /* <IAC><IAC>! */ if (print) ND_PRINT((ndo, "IAC IAC")); goto done; } i = c - TELCMD_FIRST; if (i < 0 || i > IAC - TELCMD_FIRST) goto pktend; switch (c) { case DONT: case DO: case WONT: case WILL: case SB: /* DONT/DO/WONT/WILL x */ FETCH(x, sp, length); if (x >= 0 && x < NTELOPTS) { if (print) ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x])); } else { if (print) ND_PRINT((ndo, "%s %#x", telcmds[i], x)); } if (c != SB) break; /* IAC SB .... IAC SE */ p = sp; while (length > (u_int)(p + 1 - sp)) { ND_TCHECK2(*p, 2); if (p[0] == IAC && p[1] == SE) break; p++; } if (*p != IAC) goto pktend; switch (x) { case TELOPT_AUTHENTICATION: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype))); break; case TELOPT_ENCRYPT: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd))); if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype))); break; default: if (p <= sp) break; FETCH(c, sp, length); if (print) ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds))); break; } while (p > sp) { FETCH(x, sp, length); if (print) ND_PRINT((ndo, " %#x", x)); } /* terminating IAC SE */ if (print) ND_PRINT((ndo, " SE")); sp += 2; break; default: if (print) ND_PRINT((ndo, "%s", telcmds[i])); goto done; } done: return sp - osp; trunc: ND_PRINT((ndo, "%s", tstr)); pktend: return -1; #undef FETCH } Commit Message: CVE-2017-12988/TELNET: Add a missing bounds check. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: static int des3_ede_set_key(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct des3_ede_sparc64_ctx *dctx = crypto_tfm_ctx(tfm); const u32 *K = (const u32 *)key; u32 *flags = &tfm->crt_flags; u64 k1[DES_EXPKEY_WORDS / 2]; u64 k2[DES_EXPKEY_WORDS / 2]; u64 k3[DES_EXPKEY_WORDS / 2]; if (unlikely(!((K[0] ^ K[2]) | (K[1] ^ K[3])) || !((K[2] ^ K[4]) | (K[3] ^ K[5]))) && (*flags & CRYPTO_TFM_REQ_WEAK_KEY)) { *flags |= CRYPTO_TFM_RES_WEAK_KEY; return -EINVAL; } des_sparc64_key_expand((const u32 *)key, k1); key += DES_KEY_SIZE; des_sparc64_key_expand((const u32 *)key, k2); key += DES_KEY_SIZE; des_sparc64_key_expand((const u32 *)key, k3); memcpy(&dctx->encrypt_expkey[0], &k1[0], sizeof(k1)); encrypt_to_decrypt(&dctx->encrypt_expkey[DES_EXPKEY_WORDS / 2], &k2[0]); memcpy(&dctx->encrypt_expkey[(DES_EXPKEY_WORDS / 2) * 2], &k3[0], sizeof(k3)); encrypt_to_decrypt(&dctx->decrypt_expkey[0], &k3[0]); memcpy(&dctx->decrypt_expkey[DES_EXPKEY_WORDS / 2], &k2[0], sizeof(k2)); encrypt_to_decrypt(&dctx->decrypt_expkey[(DES_EXPKEY_WORDS / 2) * 2], &k1[0]); return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int res_unpack(vorbis_info_residue *info, vorbis_info *vi,oggpack_buffer *opb){ int j,k; codec_setup_info *ci=(codec_setup_info *)vi->codec_setup; memset(info,0,sizeof(*info)); info->type=oggpack_read(opb,16); if(info->type>2 || info->type<0)goto errout; info->begin=oggpack_read(opb,24); info->end=oggpack_read(opb,24); info->grouping=oggpack_read(opb,24)+1; info->partitions=(char)(oggpack_read(opb,6)+1); info->groupbook=(unsigned char)oggpack_read(opb,8); if(info->groupbook>=ci->books)goto errout; info->stagemasks=_ogg_malloc(info->partitions*sizeof(*info->stagemasks)); info->stagebooks=_ogg_malloc(info->partitions*8*sizeof(*info->stagebooks)); for(j=0;j<info->partitions;j++){ int cascade=oggpack_read(opb,3); if(oggpack_read(opb,1)) cascade|=(oggpack_read(opb,5)<<3); info->stagemasks[j]=cascade; } for(j=0;j<info->partitions;j++){ for(k=0;k<8;k++){ if((info->stagemasks[j]>>k)&1){ unsigned char book=(unsigned char)oggpack_read(opb,8); if(book>=ci->books)goto errout; info->stagebooks[j*8+k]=book; if(k+1>info->stages)info->stages=k+1; }else info->stagebooks[j*8+k]=0xff; } } if(oggpack_eop(opb))goto errout; return 0; errout: res_clear_info(info); return 1; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) 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: void MockDownloadController::CreateGETDownload( const content::ResourceRequestInfo::WebContentsGetter& wc_getter, bool must_download, const DownloadInfo& info) { } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254 Target: 1 Example 2: Code: static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg, int byteop) { void *p; int highbyte_regs = (ctxt->rex_prefix == 0) && byteop; if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8) p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1; else p = reg_rmw(ctxt, modrm_reg); return p; } Commit Message: KVM: emulate: avoid accessing NULL ctxt->memopp A failure to decode the instruction can cause a NULL pointer access. This is fixed simply by moving the "done" label as close as possible to the return. This fixes CVE-2014-8481. Reported-by: Andy Lutomirski <[email protected]> Cc: [email protected] Fixes: 41061cdb98a0bec464278b4db8e894a3121671f5 Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int vp9_alloc_context_buffers(VP9_COMMON *cm, int width, int height) { int new_mi_size; vp9_set_mb_mi(cm, width, height); new_mi_size = cm->mi_stride * calc_mi_size(cm->mi_rows); if (cm->mi_alloc_size < new_mi_size) { cm->free_mi(cm); if (cm->alloc_mi(cm, new_mi_size)) goto fail; } if (cm->seg_map_alloc_size < cm->mi_rows * cm->mi_cols) { free_seg_map(cm); if (alloc_seg_map(cm, cm->mi_rows * cm->mi_cols)) goto fail; } if (cm->above_context_alloc_cols < cm->mi_cols) { vpx_free(cm->above_context); cm->above_context = (ENTROPY_CONTEXT *)vpx_calloc( 2 * mi_cols_aligned_to_sb(cm->mi_cols) * MAX_MB_PLANE, sizeof(*cm->above_context)); if (!cm->above_context) goto fail; vpx_free(cm->above_seg_context); cm->above_seg_context = (PARTITION_CONTEXT *)vpx_calloc( mi_cols_aligned_to_sb(cm->mi_cols), sizeof(*cm->above_seg_context)); if (!cm->above_seg_context) goto fail; cm->above_context_alloc_cols = cm->mi_cols; } return 0; fail: vp9_free_context_buffers(cm); return 1; } Commit Message: DO NOT MERGE libvpx: Cherry-pick 8b4c315 from upstream Description from upstream: vp9_alloc_context_buffers: clear cm->mi* on failure this fixes a crash in vp9_dec_setup_mi() via vp9_init_context_buffers() should decoding continue and the decoder resyncs on a smaller frame Bug: 30593752 Change-Id: Iafbf1c4114062bf796f51a6b03be71328f7bcc69 (cherry picked from commit 737c8493693243838128788fe9c3abc51f17338e) (cherry picked from commit 3e88ffac8c80b76e15286ef8a7b3bd8fa246c761) CWE ID: CWE-20 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 tcos_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out) { sc_context_t *ctx; sc_apdu_t apdu; sc_file_t *file=NULL; u8 buf[SC_MAX_APDU_BUFFER_SIZE], pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf; unsigned int i; int r, pathlen; assert(card != NULL && in_path != NULL); ctx=card->ctx; memcpy(path, in_path->value, in_path->len); pathlen = in_path->len; sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0x04); switch (in_path->type) { case SC_PATH_TYPE_FILE_ID: if (pathlen != 2) return SC_ERROR_INVALID_ARGUMENTS; /* fall through */ case SC_PATH_TYPE_FROM_CURRENT: apdu.p1 = 9; break; case SC_PATH_TYPE_DF_NAME: apdu.p1 = 4; break; case SC_PATH_TYPE_PATH: apdu.p1 = 8; if (pathlen >= 2 && memcmp(path, "\x3F\x00", 2) == 0) path += 2, pathlen -= 2; if (pathlen == 0) apdu.p1 = 0; break; case SC_PATH_TYPE_PARENT: apdu.p1 = 3; pathlen = 0; break; default: SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_ARGUMENTS); } if( pathlen == 0 ) apdu.cse = SC_APDU_CASE_2_SHORT; apdu.lc = pathlen; apdu.data = path; apdu.datalen = pathlen; if (file_out != NULL) { apdu.resp = buf; apdu.resplen = sizeof(buf); apdu.le = 256; } else { apdu.resplen = 0; apdu.le = 0; apdu.p2 = 0x0C; apdu.cse = (pathlen == 0) ? SC_APDU_CASE_1 : SC_APDU_CASE_3_SHORT; } r = sc_transmit_apdu(card, &apdu); SC_TEST_RET(ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); r = sc_check_sw(card, apdu.sw1, apdu.sw2); if (r || file_out == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, r); if (apdu.resplen < 1 || apdu.resp[0] != 0x62){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "received invalid template %02X\n", apdu.resp[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } file = sc_file_new(); if (file == NULL) SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_OUT_OF_MEMORY); *file_out = file; file->path = *in_path; for(i=2; i+1<apdu.resplen && i+1+apdu.resp[i+1]<apdu.resplen; i+=2+apdu.resp[i+1]){ int j, len=apdu.resp[i+1]; unsigned char type=apdu.resp[i], *d=apdu.resp+i+2; switch (type) { case 0x80: case 0x81: file->size=0; for(j=0; j<len; ++j) file->size = (file->size<<8) | d[j]; break; case 0x82: file->shareable = (d[0] & 0x40) ? 1 : 0; file->ef_structure = d[0] & 7; switch ((d[0]>>3) & 7) { case 0: file->type = SC_FILE_TYPE_WORKING_EF; break; case 7: file->type = SC_FILE_TYPE_DF; break; default: sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "invalid file type %02X in file descriptor\n", d[0]); SC_FUNC_RETURN(ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_UNKNOWN_DATA_RECEIVED); } break; case 0x83: file->id = (d[0]<<8) | d[1]; break; case 0x84: memcpy(file->name, d, len); file->namelen = len; break; case 0x86: sc_file_set_sec_attr(file, d, len); break; default: if (len>0) sc_file_set_prop_attr(file, d, len); } } file->magic = SC_FILE_MAGIC; parse_sec_attr(card, file, file->sec_attr, file->sec_attr_len); return 0; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415 Target: 1 Example 2: Code: ChromeContentBrowserClient::CheckDesktopNotificationPermission( const GURL& source_origin, content::ResourceContext* context, int render_process_id) { #if defined(ENABLE_NOTIFICATIONS) DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); ProfileIOData* io_data = ProfileIOData::FromResourceContext(context); if (io_data->GetExtensionInfoMap()->SecurityOriginHasAPIPermission( source_origin, render_process_id, APIPermission::kNotification)) return WebKit::WebNotificationPresenter::PermissionAllowed; return io_data->GetNotificationService() ? io_data->GetNotificationService()->HasPermission(source_origin) : WebKit::WebNotificationPresenter::PermissionNotAllowed; #else return WebKit::WebNotificationPresenter::PermissionAllowed; #endif } Commit Message: Ensure extensions and the Chrome Web Store are loaded in new BrowsingInstances. BUG=174943 TEST=Can't post message to CWS. See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/12301013 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184208 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry, DropReason* dropReason, nsecs_t* nextWakeupTime) { if (! entry->dispatchInProgress) { if (entry->repeatCount == 0 && entry->action == AKEY_EVENT_ACTION_DOWN && (entry->policyFlags & POLICY_FLAG_TRUSTED) && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) { if (mKeyRepeatState.lastKeyEntry && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) { entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1; resetKeyRepeatLocked(); mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves } else { resetKeyRepeatLocked(); mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout; } mKeyRepeatState.lastKeyEntry = entry; entry->refCount += 1; } else if (! entry->syntheticRepeat) { resetKeyRepeatLocked(); } if (entry->repeatCount == 1) { entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS; } else { entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS; } entry->dispatchInProgress = true; logOutboundKeyDetailsLocked("dispatchKey - ", entry); } if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) { if (currentTime < entry->interceptKeyWakeupTime) { if (entry->interceptKeyWakeupTime < *nextWakeupTime) { *nextWakeupTime = entry->interceptKeyWakeupTime; } return false; // wait until next wakeup } entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN; entry->interceptKeyWakeupTime = 0; } if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) { if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) { CommandEntry* commandEntry = postCommandLocked( & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible); if (mFocusedWindowHandle != NULL) { commandEntry->inputWindowHandle = mFocusedWindowHandle; } commandEntry->keyEntry = entry; entry->refCount += 1; return false; // wait for the command to run } else { entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE; } } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) { if (*dropReason == DROP_REASON_NOT_DROPPED) { *dropReason = DROP_REASON_POLICY; } } if (*dropReason != DROP_REASON_NOT_DROPPED) { setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED); return true; } Vector<InputTarget> inputTargets; int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime, entry, inputTargets, nextWakeupTime); if (injectionResult == INPUT_EVENT_INJECTION_PENDING) { return false; } setInjectionResultLocked(entry, injectionResult); if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) { return true; } addMonitoringTargetsLocked(inputTargets); dispatchEventLocked(currentTime, entry, inputTargets); return true; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264 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 ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData()) return; dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz). git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125 Target: 1 Example 2: Code: WebURL BlinkTestRunner::LocalFileToDataURL(const WebURL& file_url) { base::FilePath local_path; if (!net::FileURLToFilePath(file_url, &local_path)) return WebURL(); std::string contents; Send(new LayoutTestHostMsg_ReadFileToString( routing_id(), local_path, &contents)); std::string contents_base64; base::Base64Encode(contents, &contents_base64); const char data_url_prefix[] = "data:text/css:charset=utf-8;base64,"; return WebURL(GURL(data_url_prefix + contents_base64)); } Commit Message: content: Rename webkit_test_helpers.{cc,h} to blink_test_helpers.{cc,h} Now that webkit/ is gone, we are preparing ourselves for the merge of third_party/WebKit into //blink. BUG=None BUG=content_shell && content_unittests [email protected] Review URL: https://codereview.chromium.org/1118183003 Cr-Commit-Position: refs/heads/master@{#328202} 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: gs_main_alloc_instance(gs_memory_t *mem) { gs_main_instance *minst; if (mem == NULL) return NULL; minst = (gs_main_instance *)gs_alloc_bytes_immovable(mem, sizeof(gs_main_instance), "init_main_instance"); if (minst == NULL) return NULL; memcpy(minst, &gs_main_instance_init_values, sizeof(gs_main_instance_init_values)); minst->heap = mem; # ifndef PSI_INCLUDED mem->gs_lib_ctx->top_of_system = minst; /* else top of system is pl_universe */ # endif return minst; } Commit Message: CWE ID: CWE-20 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: dtls1_process_record(SSL *s) { int i,al; int enc_err; SSL_SESSION *sess; SSL3_RECORD *rr; unsigned int mac_size; unsigned char md[EVP_MAX_MD_SIZE]; rr= &(s->s3->rrec); sess = s->session; /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, * and we have that many bytes in s->packet */ rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]); /* ok, we can now read from 's->packet' data into 'rr' * rr->input points at rr->length bytes, which * need to be copied into rr->data by either * the decryption or by the decompression * When the data is 'copied' into the rr->data buffer, * rr->input will be pointed at the new buffer */ /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] * rr->length bytes of encrypted compressed stuff. */ /* check is not needed I believe */ if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG); goto f_err; } /* decrypt in place in 'rr->input' */ rr->data=rr->input; rr->orig_len=rr->length; enc_err = s->method->ssl3_enc->enc(s,0); /* enc_err is: * 0: (in non-constant time) if the record is publically invalid. * 1: if the padding is valid * -1: if the padding is invalid */ if (enc_err == 0) { /* For DTLS we simply ignore bad packets. */ rr->length = 0; s->packet_length = 0; goto err; } #ifdef TLS_DEBUG printf("dec %d\n",rr->length); { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); } printf("\n"); #endif /* r->length is now the compressed data plus mac */ if ((sess != NULL) && (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) { /* s->read_hash != NULL => mac_size != -1 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_CTX_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size) enc_err = -1; } if (enc_err < 0) { /* decryption failed, silently discard message */ rr->length = 0; s->packet_length = 0; goto err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } rr->off=0; /*- * So at this point the following is true * ssl->s3->rrec.type is the type of record * ssl->s3->rrec.length == number of bytes in record * ssl->s3->rrec.off == offset to first valid byte * ssl->s3->rrec.data == where to take bytes from, increment * after use :-). */ /* we have pulled in a full packet so zero things */ s->packet_length=0; dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */ return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(0); } Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a malloc failure, whilst the latter will fail if attempting to add a duplicate record to the queue. This should never happen because duplicate records should be detected and dropped before any attempt to add them to the queue. Unfortunately records that arrive that are for the next epoch are not being recorded correctly, and therefore replays are not being detected. Additionally, these "should not happen" failures that can occur in dtls1_buffer_record are not being treated as fatal and therefore an attacker could exploit this by sending repeated replay records for the next epoch, eventually causing a DoS through memory exhaustion. Thanks to Chris Mueller for reporting this issue and providing initial analysis and a patch. Further analysis and the final patch was performed by Matt Caswell from the OpenSSL development team. CVE-2015-0206 Reviewed-by: Dr Stephen Henson <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: lvs_netlink_monitor_rcv_bufs_force_handler(vector_t *strvec) { int res = true; if (!strvec) return; if (vector_size(strvec) >= 2) { res = check_true_false(strvec_slot(strvec,1)); if (res < 0) { report_config_error(CONFIG_GENERAL_ERROR, "Invalid value '%s' for global lvs_netlink_monitor_rcv_bufs_force specified", FMT_STR_VSLOT(strvec, 1)); return; } } global_data->lvs_netlink_monitor_rcv_bufs_force = res; } Commit Message: Add command line and configuration option to set umask Issue #1048 identified that files created by keepalived are created with mode 0666. This commit changes the default to 0644, and also allows the umask to be specified in the configuration or as a command line option. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: void CoordinatorImpl::GetVmRegionsForHeapProfiler( const std::vector<base::ProcessId>& pids, GetVmRegionsForHeapProfilerCallback callback) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); uint64_t dump_guid = ++next_dump_id_; std::unique_ptr<QueuedVmRegionRequest> request = std::make_unique<QueuedVmRegionRequest>(dump_guid, std::move(callback)); in_progress_vm_region_requests_[dump_guid] = std::move(request); std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } QueuedVmRegionRequest* request_ptr = in_progress_vm_region_requests_[dump_guid].get(); auto os_callback = base::BindRepeating(&CoordinatorImpl::OnOSMemoryDumpForVMRegions, base::Unretained(this), dump_guid); QueuedRequestDispatcher::SetUpAndDispatchVmRegionRequest(request_ptr, clients, pids, os_callback); FinalizeVmRegionDumpIfAllManagersReplied(dump_guid); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} 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: _asn1_ltostr (long v, char *str) { long d, r; char temp[LTOSTR_MAX_SIZE]; int count, k, start; if (v < 0) { str[0] = '-'; start = 1; v = -v; } else start = 0; count = 0; do { d = v / 10; r = v - d * 10; temp[start + count] = '0' + (char) r; count++; v = d; } while (v); for (k = 0; k < count; k++) str[k + start] = temp[start + count - k - 1]; str[count + start] = 0; return str; } Commit Message: CWE ID: CWE-119 Target: 1 Example 2: Code: static struct packet *packet_alloc(const uint8_t *data, uint32_t len) { struct packet *p = osi_calloc(sizeof(*p)); uint8_t *buf = osi_malloc(len); if (p && buf) { p->data = buf; p->len = len; memcpy(p->data, data, len); return p; } else if (p) osi_free(p); else if (buf) osi_free(buf); return NULL; } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 TestingAutomationProvider::UpdateCheck( DictionaryValue* args, IPC::Message* reply_message) { AutomationJSONReply* reply = new AutomationJSONReply(this, reply_message); DBusThreadManager::Get()->GetUpdateEngineClient() ->RequestUpdateCheck(base::Bind(UpdateCheckCallback, reply)); } Commit Message: chromeos: Move audio, power, and UI files into subdirs. This moves more files from chrome/browser/chromeos/ into subdirectories. BUG=chromium-os:22896 TEST=did chrome os builds both with and without aura TBR=sky Review URL: http://codereview.chromium.org/9125006 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 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: sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option) { ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option); Mutex::Autolock lock(mLock); Mutex::Autolock glock(sLock); mThumbnail.clear(); if (mRetriever == NULL) { ALOGE("retriever is not initialized"); return NULL; } VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option); if (frame == NULL) { ALOGE("failed to capture a video frame"); return NULL; } size_t size = sizeof(VideoFrame) + frame->mSize; sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient"); if (heap == NULL) { ALOGE("failed to create MemoryDealer"); delete frame; return NULL; } mThumbnail = new MemoryBase(heap, 0, size); if (mThumbnail == NULL) { ALOGE("not enough memory for VideoFrame size=%u", size); delete frame; return NULL; } VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer()); frameCopy->mWidth = frame->mWidth; frameCopy->mHeight = frame->mHeight; frameCopy->mDisplayWidth = frame->mDisplayWidth; frameCopy->mDisplayHeight = frame->mDisplayHeight; frameCopy->mSize = frame->mSize; frameCopy->mRotationAngle = frame->mRotationAngle; ALOGV("rotation: %d", frameCopy->mRotationAngle); frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame); memcpy(frameCopy->mData, frame->mData, frame->mSize); delete frame; // Fix memory leakage return mThumbnail; } Commit Message: Clear unused pointer field when sending across binder Bug: 28377502 Change-Id: Iad5ebfb0a9ef89f09755bb332579dbd3534f9c98 CWE ID: CWE-20 Target: 1 Example 2: Code: static MagickBooleanType IsDPX(const unsigned char *magick,const size_t extent) { if (extent < 4) return(MagickFalse); if (memcmp(magick,"SDPX",4) == 0) return(MagickTrue); if (memcmp(magick,"XPDS",4) == 0) return(MagickTrue); return(MagickFalse); } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void regulator_ena_gpio_free(struct regulator_dev *rdev) { struct regulator_enable_gpio *pin, *n; if (!rdev->ena_pin) return; /* Free the GPIO only in case of no use */ list_for_each_entry_safe(pin, n, &regulator_ena_gpio_list, list) { if (pin->gpiod == rdev->ena_pin->gpiod) { if (pin->request_count <= 1) { pin->request_count = 0; gpiod_put(pin->gpiod); list_del(&pin->list); kfree(pin); } else { pin->request_count--; } } } } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[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 void ext4_free_io_end(ext4_io_end_t *io) { BUG_ON(!io); iput(io->inode); kfree(io); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID: Target: 1 Example 2: Code: request_set_user_header (struct request *req, const char *header) { char *name; const char *p = strchr (header, ':'); if (!p) return; BOUNDED_TO_ALLOCA (header, p, name); ++p; while (c_isspace (*p)) ++p; request_set_header (req, xstrdup (name), (char *) p, rel_name); } 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: void *atomic_thread(void *context) { struct atomic_test_s32_s *at = (struct atomic_test_s32_s *)context; for (int i = 0; i < at->max_val; i++) { usleep(1); atomic_inc_prefix_s32(&at->data[i]); } return NULL; } 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 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: ExtensionTtsController::ExtensionTtsController() : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), current_utterance_(NULL), platform_impl_(NULL) { } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20 Target: 1 Example 2: Code: void MSG_WriteDeltaKeyFloat( msg_t *msg, int key, float oldV, float newV ) { floatint_t fi; if ( oldV == newV ) { MSG_WriteBits( msg, 0, 1 ); return; } fi.f = newV; MSG_WriteBits( msg, 1, 1 ); MSG_WriteBits( msg, fi.i ^ key, 32 ); } Commit Message: Fix/improve buffer overflow in MSG_ReadBits/MSG_WriteBits Prevent reading past end of message in MSG_ReadBits. If read past end of msg->data buffer (16348 bytes) the engine could SEGFAULT. Make MSG_WriteBits use an exact buffer overflow check instead of possibly failing with a few bytes left. CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb); struct hstate *h = hstate_inode(dentry->d_inode); buf->f_type = HUGETLBFS_MAGIC; buf->f_bsize = huge_page_size(h); if (sbinfo) { spin_lock(&sbinfo->stat_lock); /* If no limits set, just report 0 for max/free/used * blocks, like simple_statfs() */ if (sbinfo->max_blocks >= 0) { buf->f_blocks = sbinfo->max_blocks; buf->f_bavail = buf->f_bfree = sbinfo->free_blocks; buf->f_files = sbinfo->max_inodes; buf->f_ffree = sbinfo->free_inodes; } spin_unlock(&sbinfo->stat_lock); } buf->f_namelen = NAME_MAX; return 0; } Commit Message: hugepages: fix use after free bug in "quota" handling hugetlbfs_{get,put}_quota() are badly named. They don't interact with the general quota handling code, and they don't much resemble its behaviour. Rather than being about maintaining limits on on-disk block usage by particular users, they are instead about maintaining limits on in-memory page usage (including anonymous MAP_PRIVATE copied-on-write pages) associated with a particular hugetlbfs filesystem instance. Worse, they work by having callbacks to the hugetlbfs filesystem code from the low-level page handling code, in particular from free_huge_page(). This is a layering violation of itself, but more importantly, if the kernel does a get_user_pages() on hugepages (which can happen from KVM amongst others), then the free_huge_page() can be delayed until after the associated inode has already been freed. If an unmount occurs at the wrong time, even the hugetlbfs superblock where the "quota" limits are stored may have been freed. Andrew Barry proposed a patch to fix this by having hugepages, instead of storing a pointer to their address_space and reaching the superblock from there, had the hugepages store pointers directly to the superblock, bumping the reference count as appropriate to avoid it being freed. Andrew Morton rejected that version, however, on the grounds that it made the existing layering violation worse. This is a reworked version of Andrew's patch, which removes the extra, and some of the existing, layering violation. It works by introducing the concept of a hugepage "subpool" at the lower hugepage mm layer - that is a finite logical pool of hugepages to allocate from. hugetlbfs now creates a subpool for each filesystem instance with a page limit set, and a pointer to the subpool gets added to each allocated hugepage, instead of the address_space pointer used now. The subpool has its own lifetime and is only freed once all pages in it _and_ all other references to it (i.e. superblocks) are gone. subpools are optional - a NULL subpool pointer is taken by the code to mean that no subpool limits are in effect. Previous discussion of this bug found in: "Fix refcounting in hugetlbfs quota handling.". See: https://lkml.org/lkml/2011/8/11/28 or http://marc.info/?l=linux-mm&m=126928970510627&w=1 v2: Fixed a bug spotted by Hillf Danton, and removed the extra parameter to alloc_huge_page() - since it already takes the vma, it is not necessary. Signed-off-by: Andrew Barry <[email protected]> Signed-off-by: David Gibson <[email protected]> Cc: Hugh Dickins <[email protected]> Cc: Mel Gorman <[email protected]> Cc: Minchan Kim <[email protected]> Cc: Hillf Danton <[email protected]> Cc: Paul Mackerras <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static v8::Handle<v8::Value> overloadedMethod4Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.overloadedMethod4"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(int, intArg, toInt32(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))); imp->overloadedMethod(intArg); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: Target: 1 Example 2: Code: int HttpProxyClientSocket::DoTCPRestart() { next_state_ = STATE_TCP_RESTART_COMPLETE; return transport_->socket()->Connect( base::Bind(&HttpProxyClientSocket::OnIOComplete, base::Unretained(this))); } Commit Message: Sanitize headers in Proxy Authentication Required responses BUG=431504 Review URL: https://codereview.chromium.org/769043003 Cr-Commit-Position: refs/heads/master@{#310014} CWE ID: CWE-19 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: usage(const char *program, const char *reason) { fprintf(stderr, "pngunknown: %s: usage:\n %s [--strict] " "--default|{(CHNK|default|all)=(default|discard|if-safe|save)} " "testfile.png\n", reason, program); exit(99); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: _PUBLIC_ bool ldap_encode(struct ldap_message *msg, DATA_BLOB *result, TALLOC_CTX *mem_ctx) { struct asn1_data *data = asn1_init(mem_ctx); int i, j; if (!data) return false; asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_Integer(data, msg->messageid); switch (msg->type) { case LDAP_TAG_BindRequest: { struct ldap_BindRequest *r = &msg->r.BindRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_Integer(data, r->version); asn1_write_OctetString(data, r->dn, (r->dn != NULL) ? strlen(r->dn) : 0); switch (r->mechanism) { case LDAP_AUTH_MECH_SIMPLE: /* context, primitive */ asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write(data, r->creds.password, strlen(r->creds.password)); asn1_pop_tag(data); break; case LDAP_AUTH_MECH_SASL: /* context, constructed */ asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, r->creds.SASL.mechanism, strlen(r->creds.SASL.mechanism)); if (r->creds.SASL.secblob) { asn1_write_OctetString(data, r->creds.SASL.secblob->data, r->creds.SASL.secblob->length); } asn1_pop_tag(data); break; default: return false; } asn1_pop_tag(data); break; } case LDAP_TAG_BindResponse: { struct ldap_BindResponse *r = &msg->r.BindResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, &r->response); if (r->SASL.secblob) { asn1_write_ContextSimple(data, 7, r->SASL.secblob); } asn1_pop_tag(data); break; } case LDAP_TAG_UnbindRequest: { /* struct ldap_UnbindRequest *r = &msg->r.UnbindRequest; */ asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); asn1_pop_tag(data); break; } case LDAP_TAG_SearchRequest: { struct ldap_SearchRequest *r = &msg->r.SearchRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->basedn, strlen(r->basedn)); asn1_write_enumerated(data, r->scope); asn1_write_enumerated(data, r->deref); asn1_write_Integer(data, r->sizelimit); asn1_write_Integer(data, r->timelimit); asn1_write_BOOLEAN(data, r->attributesonly); if (!ldap_push_filter(data, r->tree)) { return false; } asn1_push_tag(data, ASN1_SEQUENCE(0)); for (i=0; i<r->num_attributes; i++) { asn1_write_OctetString(data, r->attributes[i], strlen(r->attributes[i])); } asn1_pop_tag(data); asn1_pop_tag(data); break; } case LDAP_TAG_SearchResultEntry: { struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->dn, strlen(r->dn)); asn1_push_tag(data, ASN1_SEQUENCE(0)); for (i=0; i<r->num_attributes; i++) { struct ldb_message_element *attr = &r->attributes[i]; asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_OctetString(data, attr->name, strlen(attr->name)); asn1_push_tag(data, ASN1_SEQUENCE(1)); for (j=0; j<attr->num_values; j++) { asn1_write_OctetString(data, attr->values[j].data, attr->values[j].length); } asn1_pop_tag(data); asn1_pop_tag(data); } asn1_pop_tag(data); asn1_pop_tag(data); break; } case LDAP_TAG_SearchResultDone: { struct ldap_Result *r = &msg->r.SearchResultDone; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_ModifyRequest: { struct ldap_ModifyRequest *r = &msg->r.ModifyRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->dn, strlen(r->dn)); asn1_push_tag(data, ASN1_SEQUENCE(0)); for (i=0; i<r->num_mods; i++) { struct ldb_message_element *attrib = &r->mods[i].attrib; asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_enumerated(data, r->mods[i].type); asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_OctetString(data, attrib->name, strlen(attrib->name)); asn1_push_tag(data, ASN1_SET); for (j=0; j<attrib->num_values; j++) { asn1_write_OctetString(data, attrib->values[j].data, attrib->values[j].length); } asn1_pop_tag(data); asn1_pop_tag(data); asn1_pop_tag(data); } asn1_pop_tag(data); asn1_pop_tag(data); break; } case LDAP_TAG_ModifyResponse: { struct ldap_Result *r = &msg->r.ModifyResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_AddRequest: { struct ldap_AddRequest *r = &msg->r.AddRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->dn, strlen(r->dn)); asn1_push_tag(data, ASN1_SEQUENCE(0)); for (i=0; i<r->num_attributes; i++) { struct ldb_message_element *attrib = &r->attributes[i]; asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_OctetString(data, attrib->name, strlen(attrib->name)); asn1_push_tag(data, ASN1_SET); for (j=0; j<r->attributes[i].num_values; j++) { asn1_write_OctetString(data, attrib->values[j].data, attrib->values[j].length); } asn1_pop_tag(data); asn1_pop_tag(data); } asn1_pop_tag(data); asn1_pop_tag(data); break; } case LDAP_TAG_AddResponse: { struct ldap_Result *r = &msg->r.AddResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_DelRequest: { struct ldap_DelRequest *r = &msg->r.DelRequest; asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); asn1_write(data, r->dn, strlen(r->dn)); asn1_pop_tag(data); break; } case LDAP_TAG_DelResponse: { struct ldap_Result *r = &msg->r.DelResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_ModifyDNRequest: { struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->dn, strlen(r->dn)); asn1_write_OctetString(data, r->newrdn, strlen(r->newrdn)); asn1_write_BOOLEAN(data, r->deleteolddn); if (r->newsuperior) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write(data, r->newsuperior, strlen(r->newsuperior)); asn1_pop_tag(data); } asn1_pop_tag(data); break; } case LDAP_TAG_ModifyDNResponse: { struct ldap_Result *r = &msg->r.ModifyDNResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_CompareRequest: { struct ldap_CompareRequest *r = &msg->r.CompareRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->dn, strlen(r->dn)); asn1_push_tag(data, ASN1_SEQUENCE(0)); asn1_write_OctetString(data, r->attribute, strlen(r->attribute)); asn1_write_OctetString(data, r->value.data, r->value.length); asn1_pop_tag(data); asn1_pop_tag(data); break; } case LDAP_TAG_CompareResponse: { struct ldap_Result *r = &msg->r.ModifyDNResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, r); asn1_pop_tag(data); break; } case LDAP_TAG_AbandonRequest: { struct ldap_AbandonRequest *r = &msg->r.AbandonRequest; asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); asn1_write_implicit_Integer(data, r->messageid); asn1_pop_tag(data); break; } case LDAP_TAG_SearchResultReference: { struct ldap_SearchResRef *r = &msg->r.SearchResultReference; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_write_OctetString(data, r->referral, strlen(r->referral)); asn1_pop_tag(data); break; } case LDAP_TAG_ExtendedRequest: { struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); asn1_write(data, r->oid, strlen(r->oid)); asn1_pop_tag(data); if (r->value) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); asn1_write(data, r->value->data, r->value->length); asn1_pop_tag(data); } asn1_pop_tag(data); break; } case LDAP_TAG_ExtendedResponse: { struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse; asn1_push_tag(data, ASN1_APPLICATION(msg->type)); ldap_encode_response(data, &r->response); if (r->oid) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(10)); asn1_write(data, r->oid, strlen(r->oid)); asn1_pop_tag(data); } if (r->value) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(11)); asn1_write(data, r->value->data, r->value->length); asn1_pop_tag(data); } asn1_pop_tag(data); break; } default: return false; } if (msg->controls != NULL) { asn1_push_tag(data, ASN1_CONTEXT(0)); for (i = 0; msg->controls[i] != NULL; i++) { if (!ldap_encode_control(mem_ctx, data, msg->controls[i])) { msg->controls[i])) { DEBUG(0,("Unable to encode control %s\n", msg->controls[i]->oid)); return false; } } asn1_pop_tag(data); } asn1_pop_tag(data); if (data->has_error) { asn1_free(data); return false; } *result = data_blob_talloc(mem_ctx, data->data, data->length); asn1_free(data); return true; } static const char *blob2string_talloc(TALLOC_CTX *mem_ctx, char *result = talloc_array(mem_ctx, char, blob.length+1); memcpy(result, blob.data, blob.length); result[blob.length] = '\0'; return result; } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static int aes_t4_gcm_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,ctx); if (!iv && !key) return 1; if (key) { int bits = EVP_CIPHER_CTX_key_length(ctx) * 8; aes_t4_set_encrypt_key(key, bits, &gctx->ks.ks); CRYPTO_gcm128_init(&gctx->gcm, &gctx->ks, (block128_f) aes_t4_encrypt); switch (bits) { case 128: gctx->ctr = (ctr128_f) aes128_t4_ctr32_encrypt; break; case 192: gctx->ctr = (ctr128_f) aes192_t4_ctr32_encrypt; break; case 256: gctx->ctr = (ctr128_f) aes256_t4_ctr32_encrypt; break; default: return 0; } /* * If we have an iv can set it directly, otherwise use saved IV. */ if (iv == NULL && gctx->iv_set) iv = gctx->iv; if (iv) { CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); gctx->iv_set = 1; } gctx->key_set = 1; } else { /* If key set use IV, otherwise copy */ if (gctx->key_set) CRYPTO_gcm128_setiv(&gctx->gcm, iv, gctx->ivlen); else memcpy(gctx->iv, iv, gctx->ivlen); gctx->iv_set = 1; gctx->iv_gen = 0; } return 1; } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-125 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.add(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538 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 char *create_output_name(unsigned char *fname, unsigned char *dir, int lower, int isunix, int utf8) { unsigned char *p, *name, c, *fe, sep, slash; unsigned int x; sep = (isunix) ? '/' : '\\'; /* the path-seperator */ slash = (isunix) ? '\\' : '/'; /* the other slash */ /* length of filename */ x = strlen((char *) fname); /* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes */ if (utf8) x *= 3; /* length of output directory */ if (dir) x += strlen((char *) dir); if (!(name = (unsigned char *) malloc(x + 2))) { fprintf(stderr, "out of memory!\n"); return NULL; } /* start with blank name */ *name = '\0'; /* add output directory if needed */ if (dir) { strcpy((char *) name, (char *) dir); strcat((char *) name, "/"); } /* remove leading slashes */ while (*fname == sep) fname++; /* copy from fi->filename to new name, converting MS-DOS slashes to UNIX * slashes as we go. Also lowercases characters if needed. */ p = &name[strlen((char *)name)]; fe = &fname[strlen((char *)fname)]; if (utf8) { /* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes. * %000000000xxxxxxx -> %0xxxxxxx * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz * * Therefore, the inverse is as follows: * First char: * 0x00 - 0x7F = one byte char * 0x80 - 0xBF = invalid * 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid) * 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid) * 0xF0 - 0xFF = invalid */ do { if (fname >= fe) { free(name); return NULL; } /* get next UTF8 char */ if ((c = *fname++) < 0x80) x = c; else { if ((c >= 0xC0) && (c < 0xE0)) { x = (c & 0x1F) << 6; x |= *fname++ & 0x3F; } else if ((c >= 0xE0) && (c < 0xF0)) { x = (c & 0xF) << 12; x |= (*fname++ & 0x3F) << 6; x |= *fname++ & 0x3F; } else x = '?'; } /* whatever is the path seperator -> '/' * whatever is the other slash -> '\\' * otherwise, if lower is set, the lowercase version */ if (x == sep) x = '/'; else if (x == slash) x = '\\'; else if (lower) x = (unsigned int) tolower((int) x); /* integer back to UTF8 */ if (x < 0x80) { *p++ = (unsigned char) x; } else if (x < 0x800) { *p++ = 0xC0 | (x >> 6); *p++ = 0x80 | (x & 0x3F); } else { *p++ = 0xE0 | (x >> 12); *p++ = 0x80 | ((x >> 6) & 0x3F); *p++ = 0x80 | (x & 0x3F); } } while (x); } else { /* regular non-utf8 version */ do { c = *fname++; if (c == sep) c = '/'; else if (c == slash) c = '\\'; else if (lower) c = (unsigned char) tolower((int) c); } while ((*p++ = c)); } return (char *) name; } Commit Message: add anti "../" and leading slash protection to chmextract CWE ID: CWE-22 Target: 1 Example 2: Code: static HB_Error Load_MarkLigPos( HB_GPOS_SubTable* st, HB_Stream stream ) { HB_Error error; HB_MarkLigPos* mlp = &st->marklig; HB_UInt cur_offset, new_offset, base_offset; base_offset = FILE_Pos(); if ( ACCESS_Frame( 4L ) ) return error; mlp->PosFormat = GET_UShort(); new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &mlp->MarkCoverage, stream ) ) != HB_Err_Ok ) return error; (void)FILE_Seek( cur_offset ); if ( ACCESS_Frame( 2L ) ) goto Fail3; new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = _HB_OPEN_Load_Coverage( &mlp->LigatureCoverage, stream ) ) != HB_Err_Ok ) goto Fail3; (void)FILE_Seek( cur_offset ); if ( ACCESS_Frame( 4L ) ) goto Fail2; mlp->ClassCount = GET_UShort(); new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = Load_MarkArray( &mlp->MarkArray, stream ) ) != HB_Err_Ok ) goto Fail2; (void)FILE_Seek( cur_offset ); if ( ACCESS_Frame( 2L ) ) goto Fail1; new_offset = GET_UShort() + base_offset; FORGET_Frame(); cur_offset = FILE_Pos(); if ( FILE_Seek( new_offset ) || ( error = Load_LigatureArray( &mlp->LigatureArray, mlp->ClassCount, stream ) ) != HB_Err_Ok ) goto Fail1; return HB_Err_Ok; Fail1: Free_MarkArray( &mlp->MarkArray ); Fail2: _HB_OPEN_Free_Coverage( &mlp->LigatureCoverage ); Fail3: _HB_OPEN_Free_Coverage( &mlp->MarkCoverage ); return error; } Commit Message: CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: int regulator_can_change_voltage(struct regulator *regulator) { struct regulator_dev *rdev = regulator->rdev; if (rdev->constraints && (rdev->constraints->valid_ops_mask & REGULATOR_CHANGE_VOLTAGE)) { if (rdev->desc->n_voltages - rdev->desc->linear_min_sel > 1) return 1; if (rdev->desc->continuous_voltage_range && rdev->constraints->min_uV && rdev->constraints->max_uV && rdev->constraints->min_uV != rdev->constraints->max_uV) return 1; } return 0; } Commit Message: regulator: core: Fix regualtor_ena_gpio_free not to access pin after freeing After freeing pin from regulator_ena_gpio_free, loop can access the pin. So this patch fixes not to access pin after freeing. Signed-off-by: Seung-Woo Kim <[email protected]> Signed-off-by: Mark Brown <[email protected]> CWE ID: CWE-416 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static sk_sp<SkImage> unPremulSkImageToPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kPremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } 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 Target: 1 Example 2: Code: int rand() { rand_m_z = 36969 * (rand_m_z & 65535) + (rand_m_z >> 16); rand_m_w = 18000 * (rand_m_w & 65535) + (rand_m_w >> 16); return (int)RAND_MAX & (int)((rand_m_z << 16) + rand_m_w); /* 32-bit result */ } Commit Message: Fix stack size detection on Linux (fix #1427) 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 plist_t parse_string_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); data->type = PLIST_STRING; data->strval = (char *) malloc(sizeof(char) * (size + 1)); memcpy(data->strval, *bnode, size); data->strval[size] = '\0'; data->length = strlen(data->strval); return node_create(NULL, data); } Commit Message: bplist: Make sure to bail out if malloc() fails in parse_string_node() Credit to Wang Junjie <[email protected]> (#93) 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: Accelerator GetAccelerator(KeyboardCode code, int mask) { return Accelerator(code, mask & (1 << 0), mask & (1 << 1), mask & (1 << 2)); } Commit Message: accelerators: Remove deprecated Accelerator ctor that takes booleans. BUG=128242 [email protected] Review URL: https://chromiumcodereview.appspot.com/10399085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137957 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399 Target: 1 Example 2: Code: static bool tcp_try_undo_recovery(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_may_undo(tp)) { int mib_idx; /* Happy end! We did not retransmit anything * or our original transmission succeeded. */ DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans"); tcp_undo_cwnd_reduction(sk, false); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss) mib_idx = LINUX_MIB_TCPLOSSUNDO; else mib_idx = LINUX_MIB_TCPFULLUNDO; NET_INC_STATS_BH(sock_net(sk), mib_idx); } if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) { /* Hold old state until something *above* high_seq * is ACKed. For Reno it is MUST to prevent false * fast retransmits (RFC2582). SACK TCP is safe. */ tcp_moderate_cwnd(tp); if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; return true; } tcp_set_ca_state(sk, TCP_CA_Open); return false; } Commit Message: tcp: fix zero cwnd in tcp_cwnd_reduction Patch 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally") introduced a bug that cwnd may become 0 when both inflight and sndcnt are 0 (cwnd = inflight + sndcnt). This may lead to a div-by-zero if the connection starts another cwnd reduction phase by setting tp->prior_cwnd to the current cwnd (0) in tcp_init_cwnd_reduction(). To prevent this we skip PRR operation when nothing is acked or sacked. Then cwnd must be positive in all cases as long as ssthresh is positive: 1) The proportional reduction mode inflight > ssthresh > 0 2) The reduction bound mode a) inflight == ssthresh > 0 b) inflight < ssthresh sndcnt > 0 since newly_acked_sacked > 0 and inflight < ssthresh Therefore in all cases inflight and sndcnt can not both be 0. We check invalid tp->prior_cwnd to avoid potential div0 bugs. In reality this bug is triggered only with a sequence of less common events. For example, the connection is terminating an ECN-triggered cwnd reduction with an inflight 0, then it receives reordered/old ACKs or DSACKs from prior transmission (which acks nothing). Or the connection is in fast recovery stage that marks everything lost, but fails to retransmit due to local issues, then receives data packets from other end which acks nothing. Fixes: 3759824da87b ("tcp: PRR uses CRB mode by default and SS mode conditionally") Reported-by: Oleksandr Natalenko <[email protected]> Signed-off-by: Yuchung Cheng <[email protected]> Signed-off-by: Neal Cardwell <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[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: static MagickBooleanType load_hierarchy(Image *image,XCFDocInfo *inDocInfo, XCFLayerInfo *inLayer, ExceptionInfo *exception) { MagickOffsetType saved_pos, offset, junk; size_t width, height, bytes_per_pixel; width=ReadBlobMSBLong(image); (void) width; height=ReadBlobMSBLong(image); (void) height; bytes_per_pixel=inDocInfo->bytes_per_pixel=ReadBlobMSBLong(image); (void) bytes_per_pixel; /* load in the levels...we make sure that the number of levels * calculated when the TileManager was created is the same * as the number of levels found in the file. */ offset=(MagickOffsetType) ReadBlobMSBLong(image); /* top level */ /* discard offsets for layers below first, if any. */ do { junk=(MagickOffsetType) ReadBlobMSBLong(image); } while (junk != 0); /* save the current position as it is where the * next level offset is stored. */ saved_pos=TellBlob(image); /* seek to the level offset */ offset=SeekBlob(image, offset, SEEK_SET); /* read in the level */ if (load_level (image, inDocInfo, inLayer, exception) == 0) return(MagickFalse); /* restore the saved position so we'll be ready to * read the next offset. */ offset=SeekBlob(image, saved_pos, SEEK_SET); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/104 CWE ID: CWE-125 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } Commit Message: index: fix out-of-bounds read with invalid index entry prefix length The index format in version 4 has prefix-compressed entries, where every index entry can compress its path by using a path prefix of the previous entry. Since implmenting support for this index format version in commit 5625d86b9 (index: support index v4, 2016-05-17), though, we do not correctly verify that the prefix length that we want to reuse is actually smaller or equal to the amount of characters than the length of the previous index entry's path. This can lead to a an integer underflow and subsequently to an out-of-bounds read. Fix this by verifying that the prefix is actually smaller than the previous entry's path length. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-190 Target: 1 Example 2: Code: void WebRuntimeFeatures::EnableCSSFragmentIdentifiers(bool enable) { RuntimeEnabledFeatures::SetCSSFragmentIdentifiersEnabled(enable); } Commit Message: Remove RequireCSSExtensionForFile runtime enabled flag. The feature has long since been stable (since M64) and doesn't seem to be a need for this flag. BUG=788936 Change-Id: I666390b869289c328acb4a2daa5bf4154e1702c0 Reviewed-on: https://chromium-review.googlesource.com/c/1324143 Reviewed-by: Mike West <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Dave Tapuska <[email protected]> Cr-Commit-Position: refs/heads/master@{#607329} CWE ID: CWE-254 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int wp512_update(struct shash_desc *desc, const u8 *source, unsigned int len) { struct wp512_ctx *wctx = shash_desc_ctx(desc); int sourcePos = 0; unsigned int bits_len = len * 8; // convert to number of bits int sourceGap = (8 - ((int)bits_len & 7)) & 7; int bufferRem = wctx->bufferBits & 7; int i; u32 b, carry; u8 *buffer = wctx->buffer; u8 *bitLength = wctx->bitLength; int bufferBits = wctx->bufferBits; int bufferPos = wctx->bufferPos; u64 value = bits_len; for (i = 31, carry = 0; i >= 0 && (carry != 0 || value != 0ULL); i--) { carry += bitLength[i] + ((u32)value & 0xff); bitLength[i] = (u8)carry; carry >>= 8; value >>= 8; } while (bits_len > 8) { b = ((source[sourcePos] << sourceGap) & 0xff) | ((source[sourcePos + 1] & 0xff) >> (8 - sourceGap)); buffer[bufferPos++] |= (u8)(b >> bufferRem); bufferBits += 8 - bufferRem; if (bufferBits == WP512_BLOCK_SIZE * 8) { wp512_process_buffer(wctx); bufferBits = bufferPos = 0; } buffer[bufferPos] = b << (8 - bufferRem); bufferBits += bufferRem; bits_len -= 8; sourcePos++; } if (bits_len > 0) { b = (source[sourcePos] << sourceGap) & 0xff; buffer[bufferPos] |= b >> bufferRem; } else { b = 0; } if (bufferRem + bits_len < 8) { bufferBits += bits_len; } else { bufferPos++; bufferBits += 8 - bufferRem; bits_len -= 8 - bufferRem; if (bufferBits == WP512_BLOCK_SIZE * 8) { wp512_process_buffer(wctx); bufferBits = bufferPos = 0; } buffer[bufferPos] = b << (8 - bufferRem); bufferBits += (int)bits_len; } wctx->bufferBits = bufferBits; wctx->bufferPos = bufferPos; return 0; } Commit Message: crypto: prefix module autoloading with "crypto-" This prefixes all crypto module loading with "crypto-" so we never run the risk of exposing module auto-loading to userspace via a crypto API, as demonstrated by Mathias Krause: https://lkml.org/lkml/2013/3/4/70 Signed-off-by: Kees Cook <[email protected]> Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: long long BlockGroup::GetDurationTimeCode() const { return m_duration; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119 Target: 1 Example 2: Code: static void vp78_reset_probability_tables(VP8Context *s) { int i, j; for (i = 0; i < 4; i++) for (j = 0; j < 16; j++) memcpy(s->prob->token[i][j], vp8_token_default_probs[i][vp8_coeff_band[j]], sizeof(s->prob->token[i][j])); } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[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: int GetDirFilesRecursive(const std::string &DirPath, std::map<std::string, int> &_Files) { DIR* dir; if ((dir = opendir(DirPath.c_str())) != NULL) { struct dirent *ent; while ((ent = readdir(dir)) != NULL) { if (dirent_is_directory(DirPath, ent)) { if ((strcmp(ent->d_name, ".") != 0) && (strcmp(ent->d_name, "..") != 0) && (strcmp(ent->d_name, ".svn") != 0)) { std::string nextdir = DirPath + ent->d_name + "/"; if (GetDirFilesRecursive(nextdir.c_str(), _Files)) { closedir(dir); return 1; } } } else { std::string fname = DirPath + ent->d_name; _Files[fname] = 1; } } } closedir(dir); return 0; } Commit Message: Do not allow enters/returns in arguments (thanks to Fabio Carretto) CWE ID: CWE-93 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 InputConnectionImpl::CommitText(const base::string16& text, int new_cursor_pos) { StartStateUpdateTimer(); std::string error; if (!ime_engine_->ClearComposition(input_context_id_, &error)) LOG(ERROR) << "ClearComposition failed: error=\"" << error << "\""; if (IsControlChar(text)) { SendControlKeyEvent(text); return; } if (!ime_engine_->CommitText(input_context_id_, base::UTF16ToUTF8(text).c_str(), &error)) LOG(ERROR) << "CommitText failed: error=\"" << error << "\""; } Commit Message: Clear |composing_text_| after CommitText() is called. |composing_text_| of InputConnectionImpl should be cleared after CommitText() is called. Otherwise, FinishComposingText() will commit the same text twice. Bug: 899736 Test: unit_tests Change-Id: Idb22d968ffe95d946789fbe62454e8e79cb0b384 Reviewed-on: https://chromium-review.googlesource.com/c/1304773 Commit-Queue: Yusuke Sato <[email protected]> Reviewed-by: Yusuke Sato <[email protected]> Cr-Commit-Position: refs/heads/master@{#603518} CWE ID: CWE-119 Target: 1 Example 2: Code: static void cryp_dma_out_callback(void *data) { struct cryp_ctx *ctx = (struct cryp_ctx *) data; dev_dbg(ctx->device->dev, "[%s]: ", __func__); complete(&ctx->device->dma.cryp_dma_complete); } 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 HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition) { ASSERT(m_document); ASSERT(!hasParserBlockingScript()); { ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script); ASSERT(scriptLoader); if (!scriptLoader) return; ASSERT(scriptLoader->isParserInserted()); if (!isExecutingScript()) Microtask::performCheckpoint(); InsertionPointRecord insertionPointRecord(m_host->inputStream()); NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel); scriptLoader->prepareScript(scriptStartPosition); if (!scriptLoader->willBeParserExecuted()) return; if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) { requestDeferredScript(script); } else if (scriptLoader->readyToBeParserExecuted()) { if (m_scriptNestingLevel == 1) { m_parserBlockingScript.setElement(script); m_parserBlockingScript.setStartingPosition(scriptStartPosition); } else { ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition); scriptLoader->executeScript(sourceCode); } } else { requestParsingBlockingScript(script); } } } Commit Message: Correctly keep track of isolates for microtask execution BUG=487155 [email protected] Review URL: https://codereview.chromium.org/1161823002 git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-254 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 get_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg) { /* * Because the kvm_regs structure is a mix of 32, 64 and * 128bit fields, we index it as if it was a 32bit * array. Hence below, nr_regs is the number of entries, and * off the index in the "array". */ __u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr; struct kvm_regs *regs = vcpu_gp_regs(vcpu); int nr_regs = sizeof(*regs) / sizeof(__u32); u32 off; /* Our ID is an index into the kvm_regs struct. */ off = core_reg_offset_from_id(reg->id); if (off >= nr_regs || (off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs) return -ENOENT; if (copy_to_user(uaddr, ((u32 *)regs) + off, KVM_REG_SIZE(reg->id))) return -EFAULT; return 0; } Commit Message: arm64: KVM: Tighten guest core register access from userspace We currently allow userspace to access the core register file in about any possible way, including straddling multiple registers and doing unaligned accesses. This is not the expected use of the ABI, and nobody is actually using it that way. Let's tighten it by explicitly checking the size and alignment for each field of the register file. Cc: <[email protected]> Fixes: 2f4a07c5f9fe ("arm64: KVM: guest one-reg interface") Reviewed-by: Christoffer Dall <[email protected]> Reviewed-by: Mark Rutland <[email protected]> Signed-off-by: Dave Martin <[email protected]> [maz: rewrote Dave's initial patch to be more easily backported] Signed-off-by: Marc Zyngier <[email protected]> Signed-off-by: Will Deacon <[email protected]> CWE ID: CWE-20 Target: 1 Example 2: Code: usage( char* execname ) { fprintf( stderr, "\n" ); fprintf( stderr, "ftgrid: simple glyph grid viewer -- part of the FreeType project\n" ); fprintf( stderr, "-----------------------------------------------------------\n" ); fprintf( stderr, "\n" ); fprintf( stderr, "Usage: %s [status below] ppem fontname[.ttf|.ttc] ...\n", execname ); fprintf( stderr, "\n" ); fprintf( stderr, " -r R use resolution R dpi (default: 72 dpi)\n" ); fprintf( stderr, " -f index specify first index to display\n" ); fprintf( stderr, "\n" ); exit( 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: init_ext2_xattr(void) { ext2_xattr_cache = mb_cache_create("ext2_xattr", 6); if (!ext2_xattr_cache) return -ENOMEM; return 0; } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: accept_ice_connection (GIOChannel *source, GIOCondition condition, GsmIceConnectionData *data) { IceListenObj listener; IceConn ice_conn; IceAcceptStatus status; GsmClient *client; GsmXsmpServer *server; listener = data->listener; server = data->server; g_debug ("GsmXsmpServer: accept_ice_connection()"); ice_conn = IceAcceptConnection (listener, &status); if (status != IceAcceptSuccess) { g_debug ("GsmXsmpServer: IceAcceptConnection returned %d", status); return TRUE; } client = gsm_xsmp_client_new (ice_conn); ice_conn->context = client; gsm_store_add (server->priv->client_store, gsm_client_peek_id (client), G_OBJECT (client)); /* the store will own the ref */ g_object_unref (client); return TRUE; } 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: FontFileSortDir(FontDirectoryPtr dir) { FontFileSortTable (&dir->scalable); FontFileSortTable (&dir->nonScalable); /* now that the table is fixed in size, swizzle the pointers */ FontFileSwitchStringsToBitmapPointers (dir); } Commit Message: 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: RenderProcessHost* RenderProcessHost::FromID(int render_process_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_all_hosts.Get().Lookup(render_process_id); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: 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 inline int accept_server_socket(int s) { struct sockaddr_un client_address; socklen_t clen; int fd = accept(s, (struct sockaddr*)&client_address, &clen); APPL_TRACE_DEBUG("accepted fd:%d for server fd:%d", fd, s); return fd; } 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: MagickExport Image *TrimImage(const Image *image,ExceptionInfo *exception) { RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); geometry=GetImageBoundingBox(image,exception); if ((geometry.width == 0) || (geometry.height == 0)) { Image *crop_image; crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.alpha=(Quantum) TransparentAlpha; crop_image->alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(crop_image,exception); crop_image->page=image->page; crop_image->page.x=(-1); crop_image->page.y=(-1); return(crop_image); } geometry.x+=image->page.x; geometry.y+=image->page.y; return(CropImage(image,&geometry,exception)); } Commit Message: Fixed out of bounds error in SpliceImage. 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 bool cgm_bind_dir(const char *root, const char *dirname) { nih_local char *cgpath = NULL; /* /sys should have been mounted by now */ cgpath = NIH_MUST( nih_strdup(NULL, root) ); NIH_MUST( nih_strcat(&cgpath, NULL, "/sys/fs/cgroup") ); if (!dir_exists(cgpath)) { ERROR("%s does not exist", cgpath); return false; } /* mount a tmpfs there so we can create subdirs */ if (mount("cgroup", cgpath, "tmpfs", 0, "size=10000,mode=755")) { SYSERROR("Failed to mount tmpfs at %s", cgpath); return false; } NIH_MUST( nih_strcat(&cgpath, NULL, "/cgmanager") ); if (mkdir(cgpath, 0755) < 0) { SYSERROR("Failed to create %s", cgpath); return false; } if (mount(dirname, cgpath, "none", MS_BIND, 0)) { SYSERROR("Failed to bind mount %s to %s", dirname, cgpath); return false; } return true; } Commit Message: CVE-2015-1335: Protect container mounts against symlinks When a container starts up, lxc sets up the container's inital fstree by doing a bunch of mounting, guided by the container configuration file. The container config is owned by the admin or user on the host, so we do not try to guard against bad entries. However, since the mount target is in the container, it's possible that the container admin could divert the mount with symbolic links. This could bypass proper container startup (i.e. confinement of a root-owned container by the restrictive apparmor policy, by diverting the required write to /proc/self/attr/current), or bypass the (path-based) apparmor policy by diverting, say, /proc to /mnt in the container. To prevent this, 1. do not allow mounts to paths containing symbolic links 2. do not allow bind mounts from relative paths containing symbolic links. Details: Define safe_mount which ensures that the container has not inserted any symbolic links into any mount targets for mounts to be done during container setup. The host's mount path may contain symbolic links. As it is under the control of the administrator, that's ok. So safe_mount begins the check for symbolic links after the rootfs->mount, by opening that directory. It opens each directory along the path using openat() relative to the parent directory using O_NOFOLLOW. When the target is reached, it mounts onto /proc/self/fd/<targetfd>. Use safe_mount() in mount_entry(), when mounting container proc, and when needed. In particular, safe_mount() need not be used in any case where: 1. the mount is done in the container's namespace 2. the mount is for the container's rootfs 3. the mount is relative to a tmpfs or proc/sysfs which we have just safe_mount()ed ourselves Since we were using proc/net as a temporary placeholder for /proc/sys/net during container startup, and proc/net is a symbolic link, use proc/tty instead. Update the lxc.container.conf manpage with details about the new restrictions. Finally, add a testcase to test some symbolic link possibilities. Reported-by: Roman Fiedler Signed-off-by: Serge Hallyn <[email protected]> Acked-by: Stéphane Graber <[email protected]> CWE ID: CWE-59 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry *pce; zval obj; /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp((char *)name, EL_STRING) || !strcmp((char *)name, EL_NUMBER) || !strcmp((char *)name, EL_BOOLEAN) || !strcmp((char *)name, EL_NULL) || !strcmp((char *)name, EL_ARRAY) || !strcmp((char *)name, EL_STRUCT) || !strcmp((char *)name, EL_RECORDSET) || !strcmp((char *)name, EL_BINARY) || !strcmp((char *)name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (Z_TYPE(ent1->data) == IS_UNDEF) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp((char *)name, EL_BINARY)) { zend_string *new_str = NULL; if (ZSTR_EMPTY_ALLOC() != Z_STR(ent1->data)) { new_str = php_base64_decode( (unsigned char *)Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } zval_ptr_dtor(&ent1->data); if (new_str) { ZVAL_STR(&ent1->data, new_str); } else { ZVAL_EMPTY_STRING(&ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE(ent1->data) == IS_OBJECT) { zval fname, retval; ZVAL_STRING(&fname, "__wakeup"); call_user_function_ex(NULL, &ent1->data, &fname, &retval, 0, 0, 0, NULL); zval_ptr_dtor(&fname); zval_ptr_dtor(&retval); } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (Z_ISUNDEF(ent2->data)) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE(ent2->data) == IS_ARRAY || Z_TYPE(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(&ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE(ent1->data) == IS_STRING && Z_STRLEN(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); zend_string_forget_hash_val(Z_STR(ent1->data)); if ((pce = zend_hash_find_ptr(EG(class_table), Z_STR(ent1->data))) == NULL) { incomplete_class = 1; pce = PHP_IC_ENTRY; } if (pce != PHP_IC_ENTRY && (pce->serialize || pce->unserialize)) { zval_ptr_dtor(&ent2->data); ZVAL_UNDEF(&ent2->data); php_error_docref(NULL, E_WARNING, "Class %s can not be unserialized", Z_STRVAL(ent1->data)); } else { /* Initialize target object */ object_init_ex(&obj, pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP(obj), Z_ARRVAL(ent2->data), zval_add_ref, 0); if (incomplete_class) { php_store_class_name(&obj, Z_STRVAL(ent1->data), Z_STRLEN(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ZVAL_COPY_VALUE(&ent2->data, &obj); } /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE(ent2->data); add_property_zval(&ent2->data, ent1->varname, &ent1->data); if Z_REFCOUNTED(ent1->data) Z_DELREF(ent1->data); EG(scope) = old_scope; } else { zend_symtable_str_update(target_hash, ent1->varname, strlen(ent1->varname), &ent1->data); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp((char *)name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp((char *)name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: Fix bug #73831 - NULL Pointer Dereference while unserialize php object CWE ID: CWE-476 Target: 1 Example 2: Code: void DownloadFilesCheckErrorsSetup() { embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory()); ASSERT_TRUE(embedded_test_server()->Start()); std::vector<DownloadItem*> download_items; GetDownloads(browser(), &download_items); ASSERT_TRUE(download_items.empty()); EnableFileChooser(true); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: FilePath ExtensionPrefs::GetExtensionPath(const std::string& extension_id) { const DictionaryValue* dict = GetExtensionPref(extension_id); std::string path; if (!dict->GetString(kPrefPath, &path)) return FilePath(); return install_directory_.Append(FilePath::FromWStringHack(UTF8ToWide(path))); } Commit Message: Coverity: Add a missing NULL check. BUG=none TEST=none CID=16813 Review URL: http://codereview.chromium.org/7216034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89991 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: static int cma_req_handler(struct ib_cm_id *cm_id, struct ib_cm_event *ib_event) { struct rdma_id_private *listen_id, *conn_id; struct rdma_cm_event event; int offset, ret; u8 smac[ETH_ALEN]; u8 alt_smac[ETH_ALEN]; u8 *psmac = smac; u8 *palt_smac = alt_smac; int is_iboe = ((rdma_node_get_transport(cm_id->device->node_type) == RDMA_TRANSPORT_IB) && (rdma_port_get_link_layer(cm_id->device, ib_event->param.req_rcvd.port) == IB_LINK_LAYER_ETHERNET)); listen_id = cm_id->context; if (!cma_check_req_qp_type(&listen_id->id, ib_event)) return -EINVAL; if (cma_disable_callback(listen_id, RDMA_CM_LISTEN)) return -ECONNABORTED; memset(&event, 0, sizeof event); offset = cma_user_data_offset(listen_id); event.event = RDMA_CM_EVENT_CONNECT_REQUEST; if (ib_event->event == IB_CM_SIDR_REQ_RECEIVED) { conn_id = cma_new_udp_id(&listen_id->id, ib_event); event.param.ud.private_data = ib_event->private_data + offset; event.param.ud.private_data_len = IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE - offset; } else { conn_id = cma_new_conn_id(&listen_id->id, ib_event); cma_set_req_event_data(&event, &ib_event->param.req_rcvd, ib_event->private_data, offset); } if (!conn_id) { ret = -ENOMEM; goto err1; } mutex_lock_nested(&conn_id->handler_mutex, SINGLE_DEPTH_NESTING); ret = cma_acquire_dev(conn_id, listen_id); if (ret) goto err2; conn_id->cm_id.ib = cm_id; cm_id->context = conn_id; cm_id->cm_handler = cma_ib_handler; /* * Protect against the user destroying conn_id from another thread * until we're done accessing it. */ atomic_inc(&conn_id->refcount); ret = conn_id->id.event_handler(&conn_id->id, &event); if (ret) goto err3; if (is_iboe) { if (ib_event->param.req_rcvd.primary_path != NULL) rdma_addr_find_smac_by_sgid( &ib_event->param.req_rcvd.primary_path->sgid, psmac, NULL); else psmac = NULL; if (ib_event->param.req_rcvd.alternate_path != NULL) rdma_addr_find_smac_by_sgid( &ib_event->param.req_rcvd.alternate_path->sgid, palt_smac, NULL); else palt_smac = NULL; } /* * Acquire mutex to prevent user executing rdma_destroy_id() * while we're accessing the cm_id. */ mutex_lock(&lock); if (is_iboe) ib_update_cm_av(cm_id, psmac, palt_smac); if (cma_comp(conn_id, RDMA_CM_CONNECT) && (conn_id->id.qp_type != IB_QPT_UD)) ib_send_cm_mra(cm_id, CMA_CM_MRA_SETTING, NULL, 0); mutex_unlock(&lock); mutex_unlock(&conn_id->handler_mutex); mutex_unlock(&listen_id->handler_mutex); cma_deref_id(conn_id); return 0; err3: cma_deref_id(conn_id); /* Destroy the CM ID by returning a non-zero value. */ conn_id->cm_id.ib = NULL; err2: cma_exch(conn_id, RDMA_CM_DESTROYING); mutex_unlock(&conn_id->handler_mutex); err1: mutex_unlock(&listen_id->handler_mutex); if (conn_id) rdma_destroy_id(&conn_id->id); return ret; } 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: SkBitmap BrowserNonClientFrameViewAura::GetFaviconForTabIconView() { views::WidgetDelegate* delegate = frame()->widget_delegate(); if (!delegate) return SkBitmap(); return delegate->GetWindowIcon(); } Commit Message: Ash: Fix fullscreen window bounds I was computing the non-client frame top border height incorrectly for fullscreen windows, so it was trying to draw a few pixels of transparent non-client border. BUG=118774 TEST=visual Review URL: http://codereview.chromium.org/9810014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@128014 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: RenderThreadImpl::PendingFrameCreate::PendingFrameCreate( const service_manager::BindSourceInfo& browser_info, int routing_id, mojom::FrameRequest frame_request) : browser_info_(browser_info), routing_id_(routing_id), frame_request_(std::move(frame_request)) {} Commit Message: Roll src/third_party/boringssl/src 664e99a64..696c13bd6 https://boringssl.googlesource.com/boringssl/+log/664e99a6486c293728097c661332f92bf2d847c6..696c13bd6ab78011adfe7b775519c8b7cc82b604 BUG=778101 Change-Id: I8dda4f3db952597148e3c7937319584698d00e1c Reviewed-on: https://chromium-review.googlesource.com/747941 Reviewed-by: Avi Drissman <[email protected]> Reviewed-by: David Benjamin <[email protected]> Commit-Queue: Steven Valdez <[email protected]> Cr-Commit-Position: refs/heads/master@{#513774} CWE ID: CWE-310 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; unsigned char* cp = (unsigned char*) cp0; assert((cc%stride)==0); if (cc > stride) { /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; cc -= 3; cp += 3; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cc -= 3; cp += 3; } } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; cc -= 4; cp += 4; while (cc>0) { cp[0] = (unsigned char) ((cr += cp[0]) & 0xff); cp[1] = (unsigned char) ((cg += cp[1]) & 0xff); cp[2] = (unsigned char) ((cb += cp[2]) & 0xff); cp[3] = (unsigned char) ((ca += cp[3]) & 0xff); cc -= 4; cp += 4; } } else { cc -= stride; do { REPEAT4(stride, cp[stride] = (unsigned char) ((cp[stride] + *cp) & 0xff); cp++) cc -= stride; } while (cc>0); } } } 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: PanelSettingsMenuModel::~PanelSettingsMenuModel() { } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID: 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 yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476 Target: 1 Example 2: Code: IW_IMPL(int) iw_write_jpeg_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { int retval=0; struct jpeg_compress_struct cinfo; struct my_error_mgr jerr; J_COLOR_SPACE in_colortype; // Color type of the data we give to libjpeg int jpeg_cmpts; int compress_created = 0; int compress_started = 0; JSAMPROW *row_pointers = NULL; int is_grayscale; int j; struct iw_image img; int jpeg_quality; int samp_factor_h, samp_factor_v; int disable_subsampling = 0; struct iwjpegwcontext wctx; const char *optv; int ret; iw_zeromem(&cinfo,sizeof(struct jpeg_compress_struct)); iw_zeromem(&jerr,sizeof(struct my_error_mgr)); iw_zeromem(&wctx,sizeof(struct iwjpegwcontext)); iw_get_output_image(ctx,&img); if(IW_IMGTYPE_HAS_ALPHA(img.imgtype)) { iw_set_error(ctx,"Internal: Transparency not supported with JPEG output"); goto done; } if(img.bit_depth!=8) { iw_set_errorf(ctx,"Internal: Precision %d not supported with JPEG output",img.bit_depth); goto done; } is_grayscale = IW_IMGTYPE_IS_GRAY(img.imgtype); if(is_grayscale) { in_colortype=JCS_GRAYSCALE; jpeg_cmpts=1; } else { in_colortype=JCS_RGB; jpeg_cmpts=3; } cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = my_error_exit; if (setjmp(jerr.setjmp_buffer)) { char buffer[JMSG_LENGTH_MAX]; (*cinfo.err->format_message) ((j_common_ptr)&cinfo, buffer); iw_set_errorf(ctx,"libjpeg reports write error: %s",buffer); goto done; } jpeg_create_compress(&cinfo); compress_created=1; wctx.pub.init_destination = my_init_destination_fn; wctx.pub.empty_output_buffer = my_empty_output_buffer_fn; wctx.pub.term_destination = my_term_destination_fn; wctx.ctx = ctx; wctx.iodescr = iodescr; wctx.buffer_len = 32768; wctx.buffer = iw_malloc(ctx,wctx.buffer_len); if(!wctx.buffer) goto done; cinfo.dest = (struct jpeg_destination_mgr*)&wctx; cinfo.image_width = img.width; cinfo.image_height = img.height; cinfo.input_components = jpeg_cmpts; cinfo.in_color_space = in_colortype; jpeg_set_defaults(&cinfo); optv = iw_get_option(ctx, "jpeg:block"); if(optv) { #if (JPEG_LIB_VERSION_MAJOR>=9 || \ (JPEG_LIB_VERSION_MAJOR==8 && JPEG_LIB_VERSION_MINOR>=3)) cinfo.block_size = iw_parse_int(optv); #else iw_warning(ctx, "Setting block size is not supported by this version of libjpeg"); #endif } optv = iw_get_option(ctx, "jpeg:arith"); if(optv) cinfo.arith_code = iw_parse_int(optv) ? TRUE : FALSE; else cinfo.arith_code = FALSE; optv = iw_get_option(ctx, "jpeg:colortype"); if(optv) { if(!strcmp(optv, "rgb")) { if(in_colortype==JCS_RGB) { jpeg_set_colorspace(&cinfo,JCS_RGB); disable_subsampling = 1; } } else if(!strcmp(optv, "rgb1")) { if(in_colortype==JCS_RGB) { #if JPEG_LIB_VERSION_MAJOR >= 9 cinfo.color_transform = JCT_SUBTRACT_GREEN; #else iw_warning(ctx, "Color type rgb1 is not supported by this version of libjpeg"); #endif jpeg_set_colorspace(&cinfo,JCS_RGB); disable_subsampling = 1; } } } optv = iw_get_option(ctx, "jpeg:bgycc"); if(optv && iw_parse_int(optv)) { #if (JPEG_LIB_VERSION_MAJOR>9 || \ (JPEG_LIB_VERSION_MAJOR==9 && JPEG_LIB_VERSION_MINOR>=1)) jpeg_set_colorspace(&cinfo, JCS_BG_YCC); #else iw_warning(ctx, "Big gamut YCC is not supported by this version of libjpeg"); #endif } iwjpg_set_density(ctx,&cinfo,&img); optv = iw_get_option(ctx, "jpeg:quality"); if(optv) jpeg_quality = iw_parse_int(optv); else jpeg_quality = 0; if(jpeg_quality>0) { jpeg_set_quality(&cinfo,jpeg_quality,0); } if(jpeg_cmpts>1 && !disable_subsampling) { samp_factor_h = 0; samp_factor_v = 0; optv = iw_get_option(ctx, "jpeg:sampling-x"); if(optv) samp_factor_h = iw_parse_int(optv); optv = iw_get_option(ctx, "jpeg:sampling-y"); if(optv) samp_factor_v = iw_parse_int(optv); optv = iw_get_option(ctx, "jpeg:sampling"); if(optv) { double tmpsamp[2]; tmpsamp[0] = 1.0; tmpsamp[1] = 1.0; ret = iw_parse_number_list(optv, 2, tmpsamp); samp_factor_h = iw_round_to_int(tmpsamp[0]); if(ret==1) { samp_factor_v = samp_factor_h; } else { samp_factor_v = iw_round_to_int(tmpsamp[1]); } } if(samp_factor_h>0) { if(samp_factor_h>4) samp_factor_h=4; cinfo.comp_info[0].h_samp_factor = samp_factor_h; } if(samp_factor_v>0) { if(samp_factor_v>4) samp_factor_v=4; cinfo.comp_info[0].v_samp_factor = samp_factor_v; } } if(iw_get_value(ctx,IW_VAL_OUTPUT_INTERLACED)) { jpeg_simple_progression(&cinfo); } row_pointers = (JSAMPROW*)iw_malloc(ctx, img.height * sizeof(JSAMPROW)); if(!row_pointers) goto done; for(j=0;j<img.height;j++) { row_pointers[j] = &img.pixels[j*img.bpr]; } jpeg_start_compress(&cinfo, TRUE); compress_started=1; jpeg_write_scanlines(&cinfo, row_pointers, img.height); retval=1; done: if(compress_started) jpeg_finish_compress(&cinfo); if(compress_created) jpeg_destroy_compress(&cinfo); if(row_pointers) iw_free(ctx,row_pointers); if(wctx.buffer) iw_free(ctx,wctx.buffer); return retval; } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 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 RenderViewImpl::OnCopy() { if (!webview()) return; base::AutoReset<bool> handling_select_range(&handling_select_range_, true); webview()->focusedFrame()->executeCommand(WebString::fromUTF8("Copy"), context_menu_node_); } Commit Message: Let the browser handle external navigations from DevTools. BUG=180555 Review URL: https://chromiumcodereview.appspot.com/12531004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@186793 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int UDPSocketWin::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_ADDRESS_INVALID; int rv = bind(socket_, storage.addr, storage.addr_len); if (rv == 0) return OK; int last_error = WSAGetLastError(); UMA_HISTOGRAM_SPARSE_SLOWLY("Net.UdpSocketBindErrorFromWinOS", last_error); if (last_error == WSAEACCES || last_error == WSAEINVAL) return ERR_ADDRESS_IN_USE; return MapSystemError(last_error); } Commit Message: Map posix error codes in bind better, and fix one windows mapping. r=wtc BUG=330233 Review URL: https://codereview.chromium.org/101193008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@242224 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416 Target: 1 Example 2: Code: const base::string16& MediaControlsHeaderView::app_name_for_testing() const { return app_name_view_->GetText(); } 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: int try_to_free_swap(struct page *page) { VM_BUG_ON(!PageLocked(page)); if (!PageSwapCache(page)) return 0; if (PageWriteback(page)) return 0; if (page_swapcount(page)) return 0; /* * Once hibernation has begun to create its image of memory, * there's a danger that one of the calls to try_to_free_swap() * - most probably a call from __try_to_reclaim_swap() while * hibernation is allocating its own swap pages for the image, * but conceivably even a call from memory reclaim - will free * the swap from a page which has already been recorded in the * image as a clean swapcache page, and then reuse its swap for * another page of the image. On waking from hibernation, the * original page might be freed under memory pressure, then * later read back in from swap, now with the wrong data. * * Hibration suspends storage while it is writing the image * to disk so check that here. */ if (pm_suspended_storage()) return 0; delete_from_swap_cache(page); SetPageDirty(page); return 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 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: ftp_loop_internal (struct url *u, struct fileinfo *f, ccon *con, char **local_file, bool force_full_retrieve) { int count, orig_lp; wgint restval, len = 0, qtyread = 0; const char *tmrate = NULL; uerr_t err; struct_stat st; /* Declare WARC variables. */ bool warc_enabled = (opt.warc_filename != NULL); FILE *warc_tmp = NULL; ip_address *warc_ip = NULL; wgint last_expected_bytes = 0; /* Get the target, and set the name for the message accordingly. */ if ((f == NULL) && (con->target)) { /* Explicit file (like ".listing"). */ locf = con->target; } else { { /* URL-derived file. Consider "-O file" name. */ xfree (con->target); con->target = url_file_name (u, NULL); if (!opt.output_document) locf = con->target; else } /* If the output_document was given, then this check was already done and the file didn't exist. Hence the !opt.output_document */ /* If we receive .listing file it is necessary to determine system type of the ftp server even if opn.noclobber is given. Thus we must ignore opt.noclobber in order to establish connection with the server and get system type. */ if (opt.noclobber && !opt.output_document && file_exists_p (con->target) && !((con->cmd & DO_LIST) && !(con->cmd & DO_RETR))) { logprintf (LOG_VERBOSE, _("File %s already there; not retrieving.\n"), quote (con->target)); /* If the file is there, we suppose it's retrieved OK. */ return RETROK; } /* Remove it if it's a link. */ remove_link (con->target); count = 0; if (con->st & ON_YOUR_OWN) con->st = ON_YOUR_OWN; orig_lp = con->cmd & LEAVE_PENDING ? 1 : 0; /* THE loop. */ do { /* Increment the pass counter. */ ++count; sleep_between_retrievals (count); if (con->st & ON_YOUR_OWN) { con->cmd = 0; con->cmd |= (DO_RETR | LEAVE_PENDING); if (con->csock != -1) con->cmd &= ~ (DO_LOGIN | DO_CWD); else con->cmd |= (DO_LOGIN | DO_CWD); } else /* not on your own */ { if (con->csock != -1) con->cmd &= ~DO_LOGIN; else con->cmd |= DO_LOGIN; if (con->st & DONE_CWD) con->cmd &= ~DO_CWD; else con->cmd |= DO_CWD; } /* For file RETR requests, we can write a WARC record. We record the file contents to a temporary file. */ if (warc_enabled && (con->cmd & DO_RETR) && warc_tmp == NULL) { warc_tmp = warc_tempfile (); if (warc_tmp == NULL) return WARC_TMP_FOPENERR; if (!con->proxy && con->csock != -1) { warc_ip = (ip_address *) alloca (sizeof (ip_address)); socket_ip_address (con->csock, warc_ip, ENDPOINT_PEER); } } /* Decide whether or not to restart. */ if (con->cmd & DO_LIST) restval = 0; else if (force_full_retrieve) restval = 0; else if (opt.start_pos >= 0) restval = opt.start_pos; else if (opt.always_rest && stat (locf, &st) == 0 && S_ISREG (st.st_mode)) /* When -c is used, continue from on-disk size. (Can't use hstat.len even if count>1 because we don't want a failed first attempt to clobber existing data.) */ restval = st.st_size; else if (count > 1) restval = qtyread; /* start where the previous run left off */ else restval = 0; /* Get the current time string. */ tms = datetime_str (time (NULL)); /* Print fetch message, if opt.verbose. */ if (opt.verbose) { char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); char tmp[256]; strcpy (tmp, " "); if (count > 1) sprintf (tmp, _("(try:%2d)"), count); logprintf (LOG_VERBOSE, "--%s-- %s\n %s => %s\n", tms, hurl, tmp, quote (locf)); #ifdef WINDOWS ws_changetitle (hurl); #endif xfree (hurl); } /* Send getftp the proper length, if fileinfo was provided. */ if (f && f->type != FT_SYMLINK) len = f->size; else len = 0; /* If we are working on a WARC record, getftp should also write to the warc_tmp file. */ err = getftp (u, len, &qtyread, restval, con, count, &last_expected_bytes, warc_tmp); if (con->csock == -1) con->st &= ~DONE_CWD; con->st |= DONE_CWD; switch (err) { case HOSTERR: case CONIMPOSSIBLE: case FWRITEERR: case FOPENERR: case FTPNSFOD: case FTPLOGINC: case FTPNOPASV: case FTPNOAUTH: case FTPNOPBSZ: case FTPNOPROT: case UNLINKERR: case WARC_TMP_FWRITEERR: case CONSSLERR: case CONTNOTSUPPORTED: #ifdef HAVE_SSL if (err == FTPNOAUTH) logputs (LOG_NOTQUIET, "Server does not support AUTH TLS.\n"); if (opt.ftps_implicit) logputs (LOG_NOTQUIET, "Server does not like implicit FTPS connections.\n"); #endif /* Fatal errors, give up. */ if (warc_tmp != NULL) fclose (warc_tmp); return err; case CONSOCKERR: case CONERROR: case FTPSRVERR: case FTPRERR: case WRITEFAILED: case FTPUNKNOWNTYPE: case FTPSYSERR: case FTPPORTERR: case FTPLOGREFUSED: case FTPINVPASV: case FOPEN_EXCL_ERR: printwhat (count, opt.ntry); /* non-fatal errors */ if (err == FOPEN_EXCL_ERR) { /* Re-determine the file name. */ xfree (con->target); con->target = url_file_name (u, NULL); locf = con->target; } continue; case FTPRETRINT: /* If the control connection was closed, the retrieval will be considered OK if f->size == len. */ if (!f || qtyread != f->size) { printwhat (count, opt.ntry); continue; } break; case RETRFINISHED: /* Great! */ break; default: /* Not as great. */ abort (); } tms = datetime_str (time (NULL)); if (!opt.spider) tmrate = retr_rate (qtyread - restval, con->dltime); /* If we get out of the switch above without continue'ing, we've successfully downloaded a file. Remember this fact. */ downloaded_file (FILE_DOWNLOADED_NORMALLY, locf); if (con->st & ON_YOUR_OWN) { fd_close (con->csock); con->csock = -1; } if (!opt.spider) { bool write_to_stdout = (opt.output_document && HYPHENP (opt.output_document)); logprintf (LOG_VERBOSE, write_to_stdout ? _("%s (%s) - written to stdout %s[%s]\n\n") : _("%s (%s) - %s saved [%s]\n\n"), tms, tmrate, write_to_stdout ? "" : quote (locf), number_to_static_string (qtyread)); } if (!opt.verbose && !opt.quiet) { /* Need to hide the password from the URL. The `if' is here so that we don't do the needless allocation every time. */ char *hurl = url_string (u, URL_AUTH_HIDE_PASSWD); logprintf (LOG_NONVERBOSE, "%s URL: %s [%s] -> \"%s\" [%d]\n", tms, hurl, number_to_static_string (qtyread), locf, count); xfree (hurl); } if (warc_enabled && (con->cmd & DO_RETR)) { /* Create and store a WARC resource record for the retrieved file. */ bool warc_res; warc_res = warc_write_resource_record (NULL, u->url, NULL, NULL, warc_ip, NULL, warc_tmp, -1); if (! warc_res) return WARC_ERR; /* warc_write_resource_record has also closed warc_tmp. */ warc_tmp = NULL; } if (con->cmd & DO_LIST) /* This is a directory listing file. */ { if (!opt.remove_listing) /* --dont-remove-listing was specified, so do count this towards the number of bytes and files downloaded. */ { total_downloaded_bytes += qtyread; numurls++; } /* Deletion of listing files is not controlled by --delete-after, but by the more specific option --dont-remove-listing, and the code to do this deletion is in another function. */ } else if (!opt.spider) /* This is not a directory listing file. */ { /* Unlike directory listing files, don't pretend normal files weren't downloaded if they're going to be deleted. People seeding proxies, for instance, may want to know how many bytes and files they've downloaded through it. */ total_downloaded_bytes += qtyread; numurls++; if (opt.delete_after && !input_file_url (opt.input_filename)) { DEBUGP (("\ Removing file due to --delete-after in ftp_loop_internal():\n")); logprintf (LOG_VERBOSE, _("Removing %s.\n"), locf); if (unlink (locf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); } } /* Restore the original leave-pendingness. */ if (orig_lp) con->cmd |= LEAVE_PENDING; else con->cmd &= ~LEAVE_PENDING; if (local_file) *local_file = xstrdup (locf); if (warc_tmp != NULL) fclose (warc_tmp); return RETROK; } while (!opt.ntry || (count < opt.ntry)); if (con->csock != -1 && (con->st & ON_YOUR_OWN)) { fd_close (con->csock); con->csock = -1; } if (warc_tmp != NULL) fclose (warc_tmp); return TRYLIMEXC; } /* Return the directory listing in a reusable format. The directory /* Return the directory listing in a reusable format. The directory is specifed in u->dir. */ static uerr_t ftp_get_listing (struct url *u, ccon *con, struct fileinfo **f) { uerr_t err; char *uf; /* url file name */ con->st &= ~ON_YOUR_OWN; con->cmd |= (DO_LIST | LEAVE_PENDING); con->cmd &= ~DO_RETR; /* Find the listing file name. We do it by taking the file name of the URL and replacing the last component with the listing file name. */ uf = url_file_name (u, NULL); lf = file_merge (uf, LIST_FILENAME); xfree (uf); DEBUGP ((_("Using %s as listing tmp file.\n"), quote (lf))); con->target = xstrdup (lf); con->target = xstrdup (lf); xfree (lf); err = ftp_loop_internal (u, NULL, con, NULL, false); lf = xstrdup (con->target); xfree (con->target); con->target = old_target; { *f = ftp_parse_ls (lf, con->rs); if (opt.remove_listing) { if (unlink (lf)) logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno)); else logprintf (LOG_VERBOSE, _("Removed %s.\n"), quote (lf)); } } else *f = NULL; xfree (lf); con->cmd &= ~DO_LIST; return err; } return err; } Commit Message: CWE ID: CWE-254 Target: 1 Example 2: Code: static void on_ring_buffer_data(char *ring_name, char *buffer, int buffer_size, wifi_ring_buffer_status *status) { if (!ring_name || !buffer || !status || (unsigned int)buffer_size <= sizeof(wifi_ring_buffer_entry)) { ALOGE("Error input for on_ring_buffer_data!"); return; } JNIHelper helper(mVM); /* ALOGD("on_ring_buffer_data called, vm = %p, obj = %p, env = %p buffer size = %d", mVM, mCls, env, buffer_size); */ JNIObject<jobject> ringStatus = helper.createObject( "com/android/server/wifi/WifiNative$RingBufferStatus"); if (status == NULL) { ALOGE("Error in creating ringBufferStatus"); return; } helper.setStringField(ringStatus, "name", ring_name); helper.setIntField(ringStatus, "flag", status->flags); helper.setIntField(ringStatus, "ringBufferId", status->ring_id); helper.setIntField(ringStatus, "ringBufferByteSize", status->ring_buffer_byte_size); helper.setIntField(ringStatus, "verboseLevel", status->verbose_level); helper.setIntField(ringStatus, "writtenBytes", status->written_bytes); helper.setIntField(ringStatus, "readBytes", status->read_bytes); helper.setIntField(ringStatus, "writtenRecords", status->written_records); JNIObject<jbyteArray> bytes = helper.newByteArray(buffer_size); helper.setByteArrayRegion(bytes, 0, buffer_size, (jbyte*)buffer); helper.reportEvent(mCls,"onRingBufferData", "(Lcom/android/server/wifi/WifiNative$RingBufferStatus;[B)V", ringStatus.get(), bytes.get()); } Commit Message: Deal correctly with short strings The parseMacAddress function anticipates only properly formed MAC addresses (6 hexadecimal octets separated by ":"). This change properly deals with situations where the string is shorter than expected, making sure that the passed in char* reference in parseHexByte never exceeds the end of the string. BUG: 28164077 TEST: Added a main function: int main(int argc, char **argv) { unsigned char addr[6]; if (argc > 1) { memset(addr, 0, sizeof(addr)); parseMacAddress(argv[1], addr); printf("Result: %02x:%02x:%02x:%02x:%02x:%02x\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]); } } Tested with "", "a" "ab" "ab:c" "abxc". Change-Id: I0db8d0037e48b62333d475296a45b22ab0efe386 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: PlatformSensorAccelerometerMac::GetDefaultConfiguration() { return PlatformSensorConfiguration( SensorTraits<SensorType::ACCELEROMETER>::kDefaultFrequency); } Commit Message: android: Fix sensors in device service. This patch fixes a bug that prevented more than one sensor data to be available at once when using the device motion/orientation API. The issue was introduced by this other patch [1] which fixed some security-related issues in the way shared memory region handles are managed throughout Chromium (more details at https://crbug.com/789959). The device service´s sensor implementation doesn´t work correctly because it assumes it is possible to create a writable mapping of a given shared memory region at any time. This assumption is not correct on Android, once an Ashmem region has been turned read-only, such mappings are no longer possible. To fix the implementation, this CL changes the following: - PlatformSensor used to require moving a mojo::ScopedSharedBufferMapping into the newly-created instance. Said mapping being owned by and destroyed with the PlatformSensor instance. With this patch, the constructor instead takes a single pointer to the corresponding SensorReadingSharedBuffer, i.e. the area in memory where the sensor-specific reading data is located, and can be either updated or read-from. Note that the PlatformSensor does not own the mapping anymore. - PlatformSensorProviderBase holds the *single* writable mapping that is used to store all SensorReadingSharedBuffer buffers. It is created just after the region itself, and thus can be used even after the region's access mode has been changed to read-only. Addresses within the mapping will be passed to PlatformSensor constructors, computed from the mapping's base address plus a sensor-specific offset. The mapping is now owned by the PlatformSensorProviderBase instance. Note that, security-wise, nothing changes, because all mojo::ScopedSharedBufferMapping before the patch actually pointed to the same writable-page in memory anyway. Since unit or integration tests didn't catch the regression when [1] was submitted, this patch was tested manually by running a newly-built Chrome apk in the Android emulator and on a real device running Android O. [1] https://chromium-review.googlesource.com/c/chromium/src/+/805238 BUG=805146 [email protected],[email protected],[email protected],[email protected] Change-Id: I7d60a1cad278f48c361d2ece5a90de10eb082b44 Reviewed-on: https://chromium-review.googlesource.com/891180 Commit-Queue: David Turner <[email protected]> Reviewed-by: Reilly Grant <[email protected]> Reviewed-by: Matthew Cary <[email protected]> Reviewed-by: Alexandr Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532607} CWE ID: CWE-732 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: native_handle* Parcel::readNativeHandle() const { int numFds, numInts; status_t err; err = readInt32(&numFds); if (err != NO_ERROR) return 0; err = readInt32(&numInts); if (err != NO_ERROR) return 0; native_handle* h = native_handle_create(numFds, numInts); if (!h) { return 0; } for (int i=0 ; err==NO_ERROR && i<numFds ; i++) { h->data[i] = dup(readFileDescriptor()); if (h->data[i] < 0) err = BAD_VALUE; } err = read(h->data + numFds, sizeof(int)*numInts); if (err != NO_ERROR) { native_handle_close(h); native_handle_delete(h); h = 0; } return h; } Commit Message: Correctly handle dup() failure in Parcel::readNativeHandle bail out if dup() fails, instead of creating an invalid native_handle_t Bug: 28395952 Change-Id: Ia1a6198c0f45165b9c6a55a803e5f64d8afa0572 CWE ID: CWE-20 Target: 1 Example 2: Code: rdpsnd_process_negotiate(STREAM in) { uint16 in_format_count, i; uint8 pad; uint16 version; RD_WAVEFORMATEX *format; STREAM out; RD_BOOL device_available = False; int readcnt; int discardcnt; in_uint8s(in, 14); /* initial bytes not valid from server */ in_uint16_le(in, in_format_count); in_uint8(in, pad); in_uint16_le(in, version); in_uint8s(in, 1); /* padding */ logger(Sound, Debug, "rdpsnd_process_negotiate(), formats = %d, pad = 0x%02x, version = 0x%x", (int) in_format_count, (unsigned) pad, (unsigned) version); if (rdpsnd_negotiated) { /* Do a complete reset of the sound state */ rdpsnd_reset_state(); } if (!current_driver && g_rdpsnd) device_available = rdpsnd_auto_select(); if (current_driver && !device_available && current_driver->wave_out_open()) { current_driver->wave_out_close(); device_available = True; } format_count = 0; if (s_check_rem(in, 18 * in_format_count)) { for (i = 0; i < in_format_count; i++) { format = &formats[format_count]; in_uint16_le(in, format->wFormatTag); in_uint16_le(in, format->nChannels); in_uint32_le(in, format->nSamplesPerSec); in_uint32_le(in, format->nAvgBytesPerSec); in_uint16_le(in, format->nBlockAlign); in_uint16_le(in, format->wBitsPerSample); in_uint16_le(in, format->cbSize); /* read in the buffer of unknown use */ readcnt = format->cbSize; discardcnt = 0; if (format->cbSize > MAX_CBSIZE) { logger(Sound, Debug, "rdpsnd_process_negotiate(), cbSize too large for buffer: %d", format->cbSize); readcnt = MAX_CBSIZE; discardcnt = format->cbSize - MAX_CBSIZE; } in_uint8a(in, format->cb, readcnt); in_uint8s(in, discardcnt); if (current_driver && current_driver->wave_out_format_supported(format)) { format_count++; if (format_count == MAX_FORMATS) break; } } } out = rdpsnd_init_packet(SNDC_FORMATS, 20 + 18 * format_count); uint32 flags = TSSNDCAPS_VOLUME; /* if sound is enabled, set snd caps to alive to enable transmission of audio from server */ if (g_rdpsnd) { flags |= TSSNDCAPS_ALIVE; } out_uint32_le(out, flags); /* TSSNDCAPS flags */ out_uint32(out, 0xffffffff); /* volume */ out_uint32(out, 0); /* pitch */ out_uint16(out, 0); /* UDP port */ out_uint16_le(out, format_count); out_uint8(out, 0); /* padding */ out_uint16_le(out, 2); /* version */ out_uint8(out, 0); /* padding */ for (i = 0; i < format_count; i++) { format = &formats[i]; out_uint16_le(out, format->wFormatTag); out_uint16_le(out, format->nChannels); out_uint32_le(out, format->nSamplesPerSec); out_uint32_le(out, format->nAvgBytesPerSec); out_uint16_le(out, format->nBlockAlign); out_uint16_le(out, format->wBitsPerSample); out_uint16(out, 0); /* cbSize */ } s_mark_end(out); logger(Sound, Debug, "rdpsnd_process_negotiate(), %d formats available", (int) format_count); rdpsnd_send(out); rdpsnd_negotiated = True; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 ChromeClientImpl::AttachCompositorAnimationTimeline( CompositorAnimationTimeline* compositor_timeline, LocalFrame* local_frame) { WebLocalFrameImpl* web_frame = WebLocalFrameImpl::FromFrame(local_frame)->LocalRoot(); if (CompositorAnimationHost* animation_host = web_frame->FrameWidget()->AnimationHost()) animation_host->AddTimeline(*compositor_timeline); } 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: 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 ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125 Target: 1 Example 2: Code: void mk_vhost_set_single(char *path) { struct host *host; struct host_alias *halias; struct stat checkdir; unsigned long len = 0; /* Set the default host */ host = mk_mem_malloc_z(sizeof(struct host)); mk_list_init(&host->error_pages); mk_list_init(&host->server_names); /* Prepare the unique alias */ halias = mk_mem_malloc_z(sizeof(struct host_alias)); halias->name = mk_string_dup("127.0.0.1"); mk_list_add(&halias->_head, &host->server_names); host->documentroot.data = mk_string_dup(path); host->documentroot.len = strlen(path); host->header_redirect.data = NULL; /* Validate document root configured */ if (stat(host->documentroot.data, &checkdir) == -1) { mk_err("Invalid path to DocumentRoot in %s", path); exit(EXIT_FAILURE); } else if (!(checkdir.st_mode & S_IFDIR)) { mk_err("DocumentRoot variable in %s has an invalid directory path", path); exit(EXIT_FAILURE); } /* Server Signature */ if (config->hideversion == MK_FALSE) { mk_string_build(&host->host_signature, &len, "Monkey/%s", VERSION); } else { mk_string_build(&host->host_signature, &len, "Monkey"); } mk_string_build(&host->header_host_signature.data, &host->header_host_signature.len, "Server: %s", host->host_signature); mk_list_add(&host->_head, &config->hosts); } Commit Message: Request: new request session flag to mark those files opened by FDT This patch aims to fix a potential DDoS problem that can be caused in the server quering repetitive non-existent resources. When serving a static file, the core use Vhost FDT mechanism, but if it sends a static error page it does a direct open(2). When closing the resources for the same request it was just calling mk_vhost_close() which did not clear properly the file descriptor. This patch adds a new field on the struct session_request called 'fd_is_fdt', which contains MK_TRUE or MK_FALSE depending of how fd_file was opened. Thanks to Matthew Daley <[email protected]> for report and troubleshoot this problem. Signed-off-by: Eduardo Silva <[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: int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk, __be32 saddr, __be32 daddr, struct ip_options *opt) { struct inet_sock *inet = inet_sk(sk); struct rtable *rt = skb_rtable(skb); struct iphdr *iph; /* Build the IP header. */ skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0)); skb_reset_network_header(skb); iph = ip_hdr(skb); iph->version = 4; iph->ihl = 5; iph->tos = inet->tos; if (ip_dont_fragment(sk, &rt->dst)) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->ttl = ip_select_ttl(inet, &rt->dst); iph->daddr = rt->rt_dst; iph->saddr = rt->rt_src; iph->protocol = sk->sk_protocol; ip_select_ident(iph, &rt->dst, sk); if (opt && opt->optlen) { iph->ihl += opt->optlen>>2; ip_options_build(skb, opt, daddr, rt, 0); } skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; /* Send it out. */ return ip_local_out(skb); } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: int kvm_iommu_map_pages(struct kvm *kvm, struct kvm_memory_slot *slot) { gfn_t gfn, end_gfn; pfn_t pfn; int r = 0; struct iommu_domain *domain = kvm->arch.iommu_domain; int flags; /* check if iommu exists and in use */ if (!domain) return 0; gfn = slot->base_gfn; end_gfn = gfn + slot->npages; flags = IOMMU_READ; if (!(slot->flags & KVM_MEM_READONLY)) flags |= IOMMU_WRITE; if (!kvm->arch.iommu_noncoherent) flags |= IOMMU_CACHE; while (gfn < end_gfn) { unsigned long page_size; /* Check if already mapped */ if (iommu_iova_to_phys(domain, gfn_to_gpa(gfn))) { gfn += 1; continue; } /* Get the page size we could use to map */ page_size = kvm_host_page_size(kvm, gfn); /* Make sure the page_size does not exceed the memslot */ while ((gfn + (page_size >> PAGE_SHIFT)) > end_gfn) page_size >>= 1; /* Make sure gfn is aligned to the page size we want to map */ while ((gfn << PAGE_SHIFT) & (page_size - 1)) page_size >>= 1; /* Make sure hva is aligned to the page size we want to map */ while (__gfn_to_hva_memslot(slot, gfn) & (page_size - 1)) page_size >>= 1; /* * Pin all pages we are about to map in memory. This is * important because we unmap and unpin in 4kb steps later. */ pfn = kvm_pin_pages(slot, gfn, page_size); if (is_error_noslot_pfn(pfn)) { gfn += 1; continue; } /* Map into IO address space */ r = iommu_map(domain, gfn_to_gpa(gfn), pfn_to_hpa(pfn), page_size, flags); if (r) { printk(KERN_ERR "kvm_iommu_map_address:" "iommu failed to map pfn=%llx\n", pfn); kvm_unpin_pages(kvm, pfn, page_size); goto unmap_pages; } gfn += page_size >> PAGE_SHIFT; } return 0; unmap_pages: kvm_iommu_put_pages(kvm, slot->base_gfn, gfn - slot->base_gfn); return r; } Commit Message: kvm: fix excessive pages un-pinning in kvm_iommu_map error path. The third parameter of kvm_unpin_pages() when called from kvm_iommu_map_pages() is wrong, it should be the number of pages to un-pin and not the page size. This error was facilitated with an inconsistent API: kvm_pin_pages() takes a size, but kvn_unpin_pages() takes a number of pages, so fix the problem by matching the two. This was introduced by commit 350b8bd ("kvm: iommu: fix the third parameter of kvm_iommu_put_pages (CVE-2014-3601)"), which fixes the lack of un-pinning for pages intended to be un-pinned (i.e. memory leak) but unfortunately potentially aggravated the number of pages we un-pin that should have stayed pinned. As far as I understand though, the same practical mitigations apply. This issue was found during review of Red Hat 6.6 patches to prepare Ksplice rebootless updates. Thanks to Vegard for his time on a late Friday evening to help me in understanding this code. Fixes: 350b8bd ("kvm: iommu: fix the third parameter of... (CVE-2014-3601)") Cc: [email protected] Signed-off-by: Quentin Casasnovas <[email protected]> Signed-off-by: Vegard Nossum <[email protected]> Signed-off-by: Jamie Iles <[email protected]> Reviewed-by: Sasha Levin <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: ScriptValue WebGLRenderingContextBase::getBufferParameter( ScriptState* script_state, GLenum target, GLenum pname) { if (isContextLost() || !ValidateBufferTarget("getBufferParameter", target)) return ScriptValue::CreateNull(script_state); switch (pname) { case GL_BUFFER_USAGE: { GLint value = 0; ContextGL()->GetBufferParameteriv(target, pname, &value); return WebGLAny(script_state, static_cast<unsigned>(value)); } case GL_BUFFER_SIZE: { GLint value = 0; ContextGL()->GetBufferParameteriv(target, pname, &value); if (!IsWebGL2OrHigher()) return WebGLAny(script_state, value); return WebGLAny(script_state, static_cast<GLint64>(value)); } default: SynthesizeGLError(GL_INVALID_ENUM, "getBufferParameter", "invalid parameter name"); return ScriptValue::CreateNull(script_state); } } 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: void ChromeContentBrowserClient::RegisterInProcessServices( StaticServiceMap* services, content::ServiceManagerConnection* connection) { connection->AddServiceRequestHandler( chrome::mojom::kServiceName, ChromeService::GetInstance()->CreateChromeServiceRequestHandler()); if (!g_browser_process || g_browser_process->pref_service_factory()) { service_manager::EmbeddedServiceInfo info; info.factory = base::BindRepeating( &CreatePrefService, base::BindRepeating([]() -> prefs::InProcessPrefServiceFactory* { return g_browser_process ? g_browser_process->pref_service_factory() : nullptr; })); info.task_runner = base::ThreadTaskRunnerHandle::Get(); services->insert( std::make_pair(prefs::mojom::kLocalStateServiceName, info)); } #if defined(OS_ANDROID) { service_manager::EmbeddedServiceInfo info; info.factory = base::Bind(&proxy_resolver::ProxyResolverService::CreateService); services->insert( std::make_pair(proxy_resolver::mojom::kProxyResolverServiceName, info)); } { service_manager::EmbeddedServiceInfo info; info.factory = base::BindRepeating(&StartDownloadManager); services->emplace("download_manager", info); } #endif #if defined(OS_CHROMEOS) if (base::FeatureList::IsEnabled(chromeos::features::kMultiDeviceApi)) { service_manager::EmbeddedServiceInfo info; info.factory = base::Bind( &chromeos::secure_channel::SecureChannelService::CreateService); info.task_runner = base::ThreadTaskRunnerHandle::Get(); services->emplace(chromeos::secure_channel::mojom::kServiceName, info); } #endif #if defined(OS_CHROMEOS) ash_service_registry::RegisterInProcessServices(services, connection); #endif #if BUILDFLAG(ENABLE_SIMPLE_BROWSER_SERVICE_IN_PROCESS) if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kLaunchInProcessSimpleBrowserSwitch)) { service_manager::EmbeddedServiceInfo info; info.factory = base::BindRepeating([]() -> std::unique_ptr<service_manager::Service> { return std::make_unique<simple_browser::SimpleBrowserService>( simple_browser::SimpleBrowserService::UIInitializationMode:: kUseEnvironmentUI); }); info.task_runner = base::SequencedTaskRunnerHandle::Get(); services->emplace(simple_browser::mojom::kServiceName, std::move(info)); } #endif } Commit Message: service worker: Make navigate/openWindow go through more security checks. WindowClient.navigate() and Clients.openWindow() were implemented in a way that directly navigated to the URL without going through some checks that the normal navigation path goes through. This CL attempts to fix that: - WindowClient.navigate() now goes through Navigator::RequestOpenURL() instead of directly through WebContents::OpenURL(). - Clients.openWindow() now calls more ContentBrowserClient functions for manipulating the navigation before invoking ContentBrowserClient::OpenURL(). Bug: 904219 Change-Id: Ic38978aee98c09834fdbbc240164068faa3fd4f5 Reviewed-on: https://chromium-review.googlesource.com/c/1345686 Commit-Queue: Matt Falkenhagen <[email protected]> Reviewed-by: Arthur Sonzogni <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Cr-Commit-Position: refs/heads/master@{#610753} CWE ID: CWE-264 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) { CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); header->MessageType = MessageType; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125 Target: 1 Example 2: Code: static u64 sys_reg_to_index(const struct sys_reg_desc *reg) { return (KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM64_SYSREG | (reg->Op0 << KVM_REG_ARM64_SYSREG_OP0_SHIFT) | (reg->Op1 << KVM_REG_ARM64_SYSREG_OP1_SHIFT) | (reg->CRn << KVM_REG_ARM64_SYSREG_CRN_SHIFT) | (reg->CRm << KVM_REG_ARM64_SYSREG_CRM_SHIFT) | (reg->Op2 << KVM_REG_ARM64_SYSREG_OP2_SHIFT)); } Commit Message: arm64: KVM: pmu: Fix AArch32 cycle counter access We're missing the handling code for the cycle counter accessed from a 32bit guest, leading to unexpected results. Cc: [email protected] # 4.6+ Signed-off-by: Wei Huang <[email protected]> Signed-off-by: Marc Zyngier <[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: SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } Commit Message: Fix bug #72262 - do not overflow int 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: static Image *ReadOneJNGImage(MngInfo *mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { Image *alpha_image, *color_image, *image, *jng_image; ImageInfo *alpha_image_info, *color_image_info; MagickBooleanType logging; int unique_filenames; ssize_t y; MagickBooleanType status; png_uint_32 jng_height, jng_width; png_byte jng_color_type, jng_image_sample_depth, jng_image_compression_method, jng_image_interlace_method, jng_alpha_sample_depth, jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method; register const PixelPacket *s; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; unsigned int read_JSEP, reading_idat; size_t length; jng_alpha_compression_method=0; jng_alpha_sample_depth=8; jng_color_type=0; jng_height=0; jng_width=0; alpha_image=(Image *) NULL; color_image=(Image *) NULL; alpha_image_info=(ImageInfo *) NULL; color_image_info=(ImageInfo *) NULL; unique_filenames=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneJNGImage()"); image=mng_info->image; if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) { /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " AcquireNextImage()"); AcquireNextImage(image_info,image); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; /* Signature bytes have already been read. */ read_JSEP=MagickFalse; reading_idat=MagickFalse; for (;;) { char type[MaxTextExtent]; unsigned char *chunk; unsigned int count; /* Read a new JNG chunk. */ status=SetImageProgress(image,LoadImagesTag,TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) break; type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MaxTextExtent); length=(size_t) ReadBlobMSBLong(image); count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading JNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if (length > PNG_UINT_31_MAX || count == 0) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"CorruptImage"); } p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { if (length > GetBlobSize(image)) { DestroyJNG(NULL,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) break; chunk[i]=(unsigned char) c; } for ( ; i < (ssize_t) length; i++) chunk[i]='\0'; p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ if (memcmp(type,mng_JHDR,4) == 0) { if (length == 16) { jng_width=(png_uint_32)mng_get_long(p); jng_height=(png_uint_32)mng_get_long(&p[4]); if ((jng_width == 0) || (jng_height == 0)) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); } jng_color_type=p[8]; jng_image_sample_depth=p[9]; jng_image_compression_method=p[10]; jng_image_interlace_method=p[11]; image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : NoInterlace; jng_alpha_sample_depth=p[12]; jng_alpha_compression_method=p[13]; jng_alpha_filter_method=p[14]; jng_alpha_interlace_method=p[15]; if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_width: %16lu, jng_height: %16lu\n" " jng_color_type: %16d, jng_image_sample_depth: %3d\n" " jng_image_compression_method:%3d", (unsigned long) jng_width, (unsigned long) jng_height, jng_color_type, jng_image_sample_depth, jng_image_compression_method); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_image_interlace_method: %3d" " jng_alpha_sample_depth: %3d", jng_image_interlace_method, jng_alpha_sample_depth); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " jng_alpha_compression_method:%3d\n" " jng_alpha_filter_method: %3d\n" " jng_alpha_interlace_method: %3d", jng_alpha_compression_method, jng_alpha_filter_method, jng_alpha_interlace_method); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (jng_width > 65535 || jng_height > 65535 || (long) jng_width > GetMagickResourceLimit(WidthResource) || (long) jng_height > GetMagickResourceLimit(HeightResource)) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " JNG width or height too large: (%lu x %lu)", (long) jng_width, (long) jng_height); DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } continue; } if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) { /* o create color_image o open color_blob, attached to color_image o if (color type has alpha) open alpha_blob, attached to alpha_image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating color_blob."); color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); if (color_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } GetImageInfo(color_image_info); color_image=AcquireImage(color_image_info); if (color_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } (void) AcquireUniqueFilename(color_image->filename); unique_filenames++; status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { alpha_image_info=(ImageInfo *) AcquireMagickMemory(sizeof(ImageInfo)); if (alpha_image_info == (ImageInfo *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } GetImageInfo(alpha_image_info); alpha_image=AcquireImage(alpha_image_info); if (alpha_image == (Image *) NULL) { DestroyJNG(chunk,&color_image,&color_image_info, &alpha_image,&alpha_image_info); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Creating alpha_blob."); (void) AcquireUniqueFilename(alpha_image->filename); unique_filenames++; status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, exception); if (status == MagickFalse) { alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); color_image=DestroyImage(color_image); return(DestroyImageList(image)); } if (jng_alpha_compression_method == 0) { unsigned char data[18]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing IHDR chunk to alpha_blob."); (void) WriteBlob(alpha_image,8,(const unsigned char *) "\211PNG\r\n\032\n"); (void) WriteBlobMSBULong(alpha_image,13L); PNGType(data,mng_IHDR); LogPNGChunk(logging,mng_IHDR,13L); PNGLong(data+4,jng_width); PNGLong(data+8,jng_height); data[12]=jng_alpha_sample_depth; data[13]=0; /* color_type gray */ data[14]=0; /* compression method 0 */ data[15]=0; /* filter_method 0 */ data[16]=0; /* interlace_method 0 */ (void) WriteBlob(alpha_image,17,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); } } reading_idat=MagickTrue; } if (memcmp(type,mng_JDAT,4) == 0) { /* Copy chunk to color_image->blob */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAT chunk data to color_blob."); if (length != 0) { (void) WriteBlob(color_image,length,chunk); chunk=(unsigned char *) RelinquishMagickMemory(chunk); } continue; } if (memcmp(type,mng_IDAT,4) == 0) { png_byte data[5]; /* Copy IDAT header and chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying IDAT chunk data to alpha_blob."); (void) WriteBlobMSBULong(alpha_image,(size_t) length); PNGType(data,mng_IDAT); LogPNGChunk(logging,mng_IDAT,length); (void) WriteBlob(alpha_image,4,data); (void) WriteBlob(alpha_image,length,chunk); (void) WriteBlobMSBULong(alpha_image, crc32(crc32(0,data,4),chunk,(uInt) length)); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) { /* Copy chunk data to alpha_image->blob */ if (alpha_image != NULL && image_info->ping == MagickFalse) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying JDAA chunk data to alpha_blob."); (void) WriteBlob(alpha_image,length,chunk); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_JSEP,4) == 0) { read_JSEP=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { if (length == 2) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=image->background_color.red; image->background_color.blue=image->background_color.red; } if (length == 6) { image->background_color.red=ScaleCharToQuantum(p[1]); image->background_color.green=ScaleCharToQuantum(p[3]); image->background_color.blue=ScaleCharToQuantum(p[5]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) image->gamma=((float) mng_get_long(p))*0.00001; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { if (length == 32) { image->chromaticity.white_point.x=0.00001*mng_get_long(p); image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { if (length == 1) { image->rendering_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); image->gamma=1.000f/2.200f; image->chromaticity.red_primary.x=0.6400f; image->chromaticity.red_primary.y=0.3300f; image->chromaticity.green_primary.x=0.3000f; image->chromaticity.green_primary.y=0.6000f; image->chromaticity.blue_primary.x=0.1500f; image->chromaticity.blue_primary.y=0.0600f; image->chromaticity.white_point.x=0.3127f; image->chromaticity.white_point.y=0.3290f; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_oFFs,4) == 0) { if (length > 8) { image->page.x=(ssize_t) mng_get_long(p); image->page.y=(ssize_t) mng_get_long(&p[4]); if ((int) p[8] != 0) { image->page.x/=10000; image->page.y/=10000; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { image->x_resolution=(double) mng_get_long(p); image->y_resolution=(double) mng_get_long(&p[4]); if ((int) p[8] == PNG_RESOLUTION_METER) { image->units=PixelsPerCentimeterResolution; image->x_resolution=image->x_resolution/100.0f; image->y_resolution=image->y_resolution/100.0f; } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if 0 if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (memcmp(type,mng_IEND,4)) continue; break; } /* IEND found */ /* Finish up reading image data: o read main image from color_blob. o close color_blob. o if (color_type has alpha) if alpha_encoding is PNG read secondary image from alpha_blob via ReadPNG if alpha_encoding is JPEG read secondary image from alpha_blob via ReadJPEG o close alpha_blob. o copy intensity of secondary image into opacity samples of main image. o destroy the secondary image. */ if (color_image_info == (ImageInfo *) NULL) { assert(color_image == (Image *) NULL); assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } if (color_image == (Image *) NULL) { assert(alpha_image == (Image *) NULL); return(DestroyImageList(image)); } (void) SeekBlob(color_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading jng_image from color_blob."); assert(color_image_info != (ImageInfo *) NULL); (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s", color_image->filename); color_image_info->ping=MagickFalse; /* To do: avoid this */ jng_image=ReadImage(color_image_info,exception); (void) RelinquishUniqueFileResource(color_image->filename); unique_filenames--; color_image=DestroyImage(color_image); color_image_info=DestroyImageInfo(color_image_info); if (jng_image == (Image *) NULL) { DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Copying jng_image pixels to main image."); image->columns=jng_width; image->rows=jng_height; length=image->columns*sizeof(PixelPacket); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jng_image=DestroyImageList(jng_image); DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((image->columns != jng_image->columns) || (image->rows != jng_image->rows)) { jng_image=DestroyImageList(jng_image); DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, &alpha_image_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; (void) memcpy(q,s,length); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } jng_image=DestroyImage(jng_image); if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) { if (jng_alpha_compression_method == 0) { png_byte data[5]; (void) WriteBlobMSBULong(alpha_image,0x00000000L); PNGType(data,mng_IEND); LogPNGChunk(logging,mng_IEND,0L); (void) WriteBlob(alpha_image,4,data); (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); } (void) SeekBlob(alpha_image,0,SEEK_SET); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading opacity from alpha_blob."); (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, "%s",alpha_image->filename); jng_image=ReadImage(alpha_image_info,exception); if (jng_image != (Image *) NULL) for (y=0; y < (ssize_t) image->rows; y++) { s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if ((s == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; if (image->matte != MagickFalse) for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) SetPixelOpacity(q,QuantumRange-GetPixelRed(s)); else for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) { SetPixelAlpha(q,GetPixelRed(s)); if (GetPixelOpacity(q) != OpaqueOpacity) image->matte=MagickTrue; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } (void) RelinquishUniqueFileResource(alpha_image->filename); unique_filenames--; alpha_image=DestroyImage(alpha_image); alpha_image_info=DestroyImageInfo(alpha_image_info); if (jng_image != (Image *) NULL) jng_image=DestroyImage(jng_image); } /* Read the JNG image. */ if (mng_info->mng_type == 0) { mng_info->mng_width=jng_width; mng_info->mng_height=jng_height; } if (image->page.width == 0 && image->page.height == 0) { image->page.width=jng_width; image->page.height=jng_height; } if (image->page.x == 0 && image->page.y == 0) { image->page.x=mng_info->x_off[mng_info->object_id]; image->page.y=mng_info->y_off[mng_info->object_id]; } else { image->page.y=mng_info->y_off[mng_info->object_id]; } mng_info->image_found++; status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), 2*GetBlobSize(image)); if (status == MagickFalse) return(DestroyImageList(image)); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames); return(image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1119 CWE ID: CWE-617 Target: 1 Example 2: Code: static void perf_event_context_sched_in(struct perf_event_context *ctx, struct task_struct *task) { struct perf_cpu_context *cpuctx; cpuctx = __get_cpu_context(ctx); if (cpuctx->task_ctx == ctx) return; perf_ctx_lock(cpuctx, ctx); perf_pmu_disable(ctx->pmu); /* * We want to keep the following priority order: * cpu pinned (that don't need to move), task pinned, * cpu flexible, task flexible. */ cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); if (ctx->nr_events) cpuctx->task_ctx = ctx; perf_event_sched_in(cpuctx, cpuctx->task_ctx, task); perf_pmu_enable(ctx->pmu); perf_ctx_unlock(cpuctx, ctx); /* * Since these rotations are per-cpu, we need to ensure the * cpu-context we got scheduled on is actually rotating. */ perf_pmu_rotate_start(ctx->pmu); } Commit Message: perf: Treat attr.config as u64 in perf_swevent_init() Trinity discovered that we fail to check all 64 bits of attr.config passed by user space, resulting to out-of-bounds access of the perf_swevent_enabled array in sw_perf_event_destroy(). Introduced in commit b0a873ebb ("perf: Register PMU implementations"). Signed-off-by: Tommi Rantala <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: [email protected] Cc: Paul Mackerras <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Link: http://lkml.kernel.org/r/[email protected] 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: PHP_FUNCTION(imagecolorsforindex) { zval *IM; long index; int col; gdImagePtr im; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &IM, &index) == FAILURE) { return; } ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd); col = index; if ((col >= 0 && gdImageTrueColor(im)) || (!gdImageTrueColor(im) && col >= 0 && col < gdImageColorsTotal(im))) { array_init(return_value); add_assoc_long(return_value,"red", gdImageRed(im,col)); add_assoc_long(return_value,"green", gdImageGreen(im,col)); add_assoc_long(return_value,"blue", gdImageBlue(im,col)); add_assoc_long(return_value,"alpha", gdImageAlpha(im,col)); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Color index %d out of range", col); RETURN_FALSE; } } Commit Message: CWE ID: CWE-254 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind) : host_id_(host_id), gpu_process_(base::kNullProcessHandle), in_process_(false), software_rendering_(false), kind_(kind), process_launched_(false) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) || CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) in_process_ = true; DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL); g_gpu_process_hosts[kind] = this; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id)); process_.reset( new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Target: 1 Example 2: Code: event_signal(void *eventhdl) { uint64_t u = 1; int evhdl, s; if (!eventhdl) { /* error */ return 0; } evhdl = *(int *)eventhdl; s = (int)write(evhdl, &u, sizeof(u)); if (s != sizeof(u)) { /* error */ return 0; } return 1; } Commit Message: Check length of memcmp 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: size_t PaintController::FindOutOfOrderCachedItemForward( const DisplayItem::Id& id) { for (size_t i = next_item_to_index_; i < current_paint_artifact_.GetDisplayItemList().size(); ++i) { const DisplayItem& item = current_paint_artifact_.GetDisplayItemList()[i]; if (item.IsTombstone()) continue; if (id == item.GetId()) { #if DCHECK_IS_ON() ++num_sequential_matches_; #endif return i; } if (item.IsCacheable()) { #if DCHECK_IS_ON() ++num_indexed_items_; #endif AddToIndicesByClientMap(item.Client(), i, out_of_order_item_indices_); } } if (RuntimeEnabledFeatures::PaintUnderInvalidationCheckingEnabled()) { #if DCHECK_IS_ON() ShowDebugData(); #endif LOG(WARNING) << "Can't find cached display item: " << id.client.DebugName() << " " << id.ToString(); } return kNotFound; } 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: 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 FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = fill_constant; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void addranges_W(struct cstate *g) { addrange(g, 0, '0'-1); addrange(g, '9'+1, 'A'-1); addrange(g, 'Z'+1, '_'-1); addrange(g, '_'+1, 'a'-1); addrange(g, 'z'+1, 0xFFFF); } 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: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: my_object_async_increment (MyObject *obj, gint32 x, DBusGMethodInvocation *context) { IncrementData *data = g_new0 (IncrementData, 1); data->x = x; data->context = context; g_idle_add ((GSourceFunc)do_async_increment, data); } Commit Message: CWE ID: CWE-264 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env) { YYUSE (yyvaluep); YYUSE (yyscanner); YYUSE (lex_env); if (!yymsg) yymsg = "Deleting"; YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp); YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN switch (yytype) { case 16: /* tokens */ #line 94 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1023 "hex_grammar.c" /* yacc.c:1257 */ break; case 17: /* token_sequence */ #line 95 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1029 "hex_grammar.c" /* yacc.c:1257 */ break; case 18: /* token_or_range */ #line 96 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1035 "hex_grammar.c" /* yacc.c:1257 */ break; case 19: /* token */ #line 97 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1041 "hex_grammar.c" /* yacc.c:1257 */ break; case 21: /* range */ #line 100 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1047 "hex_grammar.c" /* yacc.c:1257 */ break; case 22: /* alternatives */ #line 99 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1053 "hex_grammar.c" /* yacc.c:1257 */ break; case 23: /* byte */ #line 98 "hex_grammar.y" /* yacc.c:1257 */ { yr_re_node_destroy(((*yyvaluep).re_node)); } #line 1059 "hex_grammar.c" /* yacc.c:1257 */ break; default: break; } YY_IGNORE_MAYBE_UNINITIALIZED_END } Commit Message: Fix issue #674 for hex strings. CWE ID: CWE-674 Target: 1 Example 2: Code: void OxideQQuickWebView::setContextMenu(QQmlComponent* contextMenu) { Q_D(OxideQQuickWebView); if (d->contents_view_->contextMenu() == contextMenu) { return; } d->contents_view_->setContextMenu(contextMenu); emit contextMenuChanged(); } 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: OMX_ERRORTYPE SoftAVC::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitRate = (OMX_VIDEO_PARAM_BITRATETYPE *)params; if (bitRate->nPortIndex != 1) { return OMX_ErrorUndefined; } bitRate->eControlRate = OMX_Video_ControlRateVariable; bitRate->nTargetBitrate = mBitrate; return OMX_ErrorNone; } case OMX_IndexParamVideoAvc: { OMX_VIDEO_PARAM_AVCTYPE *avcParams = (OMX_VIDEO_PARAM_AVCTYPE *)params; if (avcParams->nPortIndex != 1) { return OMX_ErrorUndefined; } OMX_VIDEO_AVCLEVELTYPE omxLevel = OMX_VIDEO_AVCLevel41; if (OMX_ErrorNone != ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) { return OMX_ErrorUndefined; } avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline; avcParams->eLevel = omxLevel; avcParams->nRefFrames = 1; avcParams->bUseHadamard = OMX_TRUE; avcParams->nAllowedPictureTypes = (OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP | OMX_VIDEO_PictureTypeB); avcParams->nRefIdx10ActiveMinus1 = 0; avcParams->nRefIdx11ActiveMinus1 = 0; avcParams->bWeightedPPrediction = OMX_FALSE; avcParams->bconstIpred = OMX_FALSE; avcParams->bDirect8x8Inference = OMX_FALSE; avcParams->bDirectSpatialTemporal = OMX_FALSE; avcParams->nCabacInitIdc = 0; return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: static int perf_swevent_init(struct perf_event *event) { int event_id = event->attr.config; if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; switch (event_id) { case PERF_COUNT_SW_CPU_CLOCK: case PERF_COUNT_SW_TASK_CLOCK: return -ENOENT; default: break; } if (event_id >= PERF_COUNT_SW_MAX) return -ENOENT; if (!event->parent) { int err; err = swevent_hlist_get(event); if (err) return err; static_key_slow_inc(&perf_swevent_enabled[event_id]); event->destroy = sw_perf_event_destroy; } return 0; } Commit Message: perf: Treat attr.config as u64 in perf_swevent_init() Trinity discovered that we fail to check all 64 bits of attr.config passed by user space, resulting to out-of-bounds access of the perf_swevent_enabled array in sw_perf_event_destroy(). Introduced in commit b0a873ebb ("perf: Register PMU implementations"). Signed-off-by: Tommi Rantala <[email protected]> Cc: Peter Zijlstra <[email protected]> Cc: [email protected] Cc: Paul Mackerras <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-189 Target: 1 Example 2: Code: int BlackPreservingGrayOnlySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo) { GrayOnlyParams* bp = (GrayOnlyParams*) Cargo; if (In[0] == 0 && In[1] == 0 && In[2] == 0) { Out[0] = Out[1] = Out[2] = 0; Out[3] = cmsEvalToneCurve16(bp->KTone, In[3]); return TRUE; } bp ->cmyk2cmyk ->Eval16Fn(In, Out, bp ->cmyk2cmyk->Data); return TRUE; } Commit Message: Fix a double free on error recovering 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: krb5_gss_process_context_token(minor_status, context_handle, token_buffer) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_buffer_t token_buffer; { krb5_gss_ctx_id_rec *ctx; OM_uint32 majerr; ctx = (krb5_gss_ctx_id_t) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } /* "unseal" the token */ if (GSS_ERROR(majerr = kg_unseal(minor_status, context_handle, token_buffer, GSS_C_NO_BUFFER, NULL, NULL, KG_TOK_DEL_CTX))) return(majerr); /* that's it. delete the context */ return(krb5_gss_delete_sec_context(minor_status, &context_handle, GSS_C_NO_BUFFER)); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID: Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void ContainerNode::removeChildren() { if (!m_firstChild) return; RefPtr<ContainerNode> protect(this); if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&document())) fullscreen->removeFullScreenElementOfSubtree(this, true); willRemoveChildren(protect.get()); { SubframeLoadingDisabler disabler(this); document().removeFocusedElementOfSubtree(this, true); } NodeVector removedChildren; { RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates; { NoEventDispatchAssertion assertNoEventDispatch; removedChildren.reserveInitialCapacity(childNodeCount()); while (m_firstChild) { removedChildren.append(m_firstChild); removeBetween(0, m_firstChild->nextSibling(), m_firstChild); } } childrenChanged(false, 0, 0, -static_cast<int>(removedChildren.size())); for (size_t i = 0; i < removedChildren.size(); ++i) ChildNodeRemovalNotifier(this).notify(removedChildren[i].get()); } dispatchSubtreeModifiedEvent(); } Commit Message: Notify nodes removal to Range/Selection after dispatching blur and mutation event This patch changes notifying nodes removal to Range/Selection after dispatching blur and mutation event. In willRemoveChildren(), like willRemoveChild(); r115686 did same change, although it didn't change willRemoveChildren(). The issue 295010, use-after-free, is caused by setting removed node to Selection in mutation event handler. BUG=295010 TEST=LayoutTests/fast/dom/Range/range-created-during-remove-children.html, LayoutTests/editing/selection/selection-change-in-mutation-event-by-remove-children.html, LayoutTests/editing/selection/selection-change-in-blur-event-by-remove-children.html [email protected] Review URL: https://codereview.chromium.org/25389004 git-svn-id: svn://svn.chromium.org/blink/trunk@159007 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399 Target: 1 Example 2: Code: lvm2_lv_create_device_added_cb (Daemon *daemon, const char *object_path, gpointer user_data) { CreateLvm2LVData *data = user_data; Device *device; g_debug ("added %s", object_path); device = lvm2_lv_create_has_lv (data); if (device != NULL) { /* yay! it is.. now create the file system if requested */ lvm2_lv_create_found_device (device, data); g_signal_handler_disconnect (daemon, data->device_added_signal_handler_id); g_signal_handler_disconnect (daemon, data->device_changed_signal_handler_id); g_source_remove (data->device_added_timeout_id); lvm2_lv_create_data_unref (data); } } Commit Message: CWE ID: CWE-200 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: void SandboxIPCHandler::HandleLocaltime( int fd, base::PickleIterator iter, const std::vector<base::ScopedFD>& fds) { std::string time_string; if (!iter.ReadString(&time_string) || time_string.size() != sizeof(time_t)) return; time_t time; memcpy(&time, time_string.data(), sizeof(time)); const struct tm* expanded_time = localtime(&time); std::string result_string; const char* time_zone_string = ""; if (expanded_time) { result_string = std::string(reinterpret_cast<const char*>(expanded_time), sizeof(struct tm)); time_zone_string = expanded_time->tm_zone; } base::Pickle reply; reply.WriteString(result_string); reply.WriteString(time_zone_string); SendRendererReply(fds, reply, -1); } 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: 1 Example 2: Code: const struct user_regset_view *task_user_regset_view(struct task_struct *task) { #ifdef CONFIG_COMPAT if (test_tsk_thread_flag(task, TIF_31BIT)) return &user_s390_compat_view; #endif return &user_s390_view; } Commit Message: s390/ptrace: fix PSW mask check The PSW mask check of the PTRACE_POKEUSR_AREA command is incorrect. The PSW_MASK_USER define contains the PSW_MASK_ASC bits, the ptrace interface accepts all combinations for the address-space-control bits. To protect the kernel space the PSW mask check in ptrace needs to reject the address-space-control bit combination for home space. Fixes CVE-2014-3534 Cc: [email protected] Signed-off-by: Martin Schwidefsky <[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 __nfs4_close(struct path *path, struct nfs4_state *state, mode_t mode, int wait) { struct nfs4_state_owner *owner = state->owner; int call_close = 0; int newstate; atomic_inc(&owner->so_count); /* Protect against nfs4_find_state() */ spin_lock(&owner->so_lock); switch (mode & (FMODE_READ | FMODE_WRITE)) { case FMODE_READ: state->n_rdonly--; break; case FMODE_WRITE: state->n_wronly--; break; case FMODE_READ|FMODE_WRITE: state->n_rdwr--; } newstate = FMODE_READ|FMODE_WRITE; if (state->n_rdwr == 0) { if (state->n_rdonly == 0) { newstate &= ~FMODE_READ; call_close |= test_bit(NFS_O_RDONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (state->n_wronly == 0) { newstate &= ~FMODE_WRITE; call_close |= test_bit(NFS_O_WRONLY_STATE, &state->flags); call_close |= test_bit(NFS_O_RDWR_STATE, &state->flags); } if (newstate == 0) clear_bit(NFS_DELEGATED_STATE, &state->flags); } nfs4_state_set_mode_locked(state, newstate); spin_unlock(&owner->so_lock); if (!call_close) { nfs4_put_open_state(state); nfs4_put_state_owner(owner); } else nfs4_do_close(path, state, wait); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[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: void RunAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); uint32_t max_error = 0; int64_t total_error = 0; const int count_test_block = 10000; for (int i = 0; i < count_test_block; ++i) { DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); test_input_block[j] = src[j] - dst[j]; } REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block, test_temp_block, pitch_)); REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; if (max_error < error) max_error = error; total_error += error; } } EXPECT_GE(1u, max_error) << "Error: 4x4 FHT/IHT has an individual round trip error > 1"; EXPECT_GE(count_test_block , total_error) << "Error: 4x4 FHT/IHT has average round trip error > 1 per block"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119 Target: 1 Example 2: Code: static void netlink_update_socket_mc(struct netlink_sock *nlk, unsigned int group, int is_new) { int old, new = !!is_new, subscriptions; old = test_bit(group - 1, nlk->groups); subscriptions = nlk->subscriptions - old + new; if (new) __set_bit(group - 1, nlk->groups); else __clear_bit(group - 1, nlk->groups); netlink_update_subscriptions(&nlk->sk, subscriptions); netlink_update_listeners(&nlk->sk); } Commit Message: af_netlink: force credentials passing [CVE-2012-3520] Pablo Neira Ayuso discovered that avahi and potentially NetworkManager accept spoofed Netlink messages because of a kernel bug. The kernel passes all-zero SCM_CREDENTIALS ancillary data to the receiver if the sender did not provide such data, instead of not including any such data at all or including the correct data from the peer (as it is the case with AF_UNIX). This bug was introduced in commit 16e572626961 (af_unix: dont send SCM_CREDENTIALS by default) This patch forces passing credentials for netlink, as before the regression. Another fix would be to not add SCM_CREDENTIALS in netlink messages if not provided by the sender, but it might break some programs. With help from Florian Weimer & Petr Matousek This issue is designated as CVE-2012-3520 Signed-off-by: Eric Dumazet <[email protected]> Cc: Petr Matousek <[email protected]> Cc: Florian Weimer <[email protected]> Cc: Pablo Neira Ayuso <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-287 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int l_channel_send_eof(lua_State *L) { return channel_send_eof(L, 0, 0); } Commit Message: Avoid a crash (double-free) when SSH connection fails CWE ID: CWE-415 Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: lldp_private_8023_print(netdissect_options *ndo, const u_char *tptr, u_int tlv_len) { int subtype, hexdump = FALSE; if (tlv_len < 4) { return hexdump; } subtype = *(tptr+3); ND_PRINT((ndo, "\n\t %s Subtype (%u)", tok2str(lldp_8023_subtype_values, "unknown", subtype), subtype)); switch (subtype) { case LLDP_PRIVATE_8023_SUBTYPE_MACPHY: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t autonegotiation [%s] (0x%02x)", bittok2str(lldp_8023_autonegotiation_values, "none", *(tptr+4)), *(tptr + 4))); ND_PRINT((ndo, "\n\t PMD autoneg capability [%s] (0x%04x)", bittok2str(lldp_pmd_capability_values,"unknown", EXTRACT_16BITS(tptr+5)), EXTRACT_16BITS(tptr + 5))); ND_PRINT((ndo, "\n\t MAU type %s (0x%04x)", tok2str(lldp_mau_types_values, "unknown", EXTRACT_16BITS(tptr+7)), EXTRACT_16BITS(tptr + 7))); break; case LLDP_PRIVATE_8023_SUBTYPE_MDIPOWER: if (tlv_len < 7) { return hexdump; } ND_PRINT((ndo, "\n\t MDI power support [%s], power pair %s, power class %s", bittok2str(lldp_mdi_values, "none", *(tptr+4)), tok2str(lldp_mdi_power_pairs_values, "unknown", *(tptr+5)), tok2str(lldp_mdi_power_class_values, "unknown", *(tptr + 6)))); break; case LLDP_PRIVATE_8023_SUBTYPE_LINKAGGR: if (tlv_len < 9) { return hexdump; } ND_PRINT((ndo, "\n\t aggregation status [%s], aggregation port ID %u", bittok2str(lldp_aggregation_values, "none", *(tptr+4)), EXTRACT_32BITS(tptr + 5))); break; case LLDP_PRIVATE_8023_SUBTYPE_MTU: ND_PRINT((ndo, "\n\t MTU size %u", EXTRACT_16BITS(tptr + 4))); break; default: hexdump = TRUE; break; } return hexdump; } Commit Message: CVE-2017-13054/LLDP: add a missing length check In lldp_private_8023_print() the case block for subtype 4 (Maximum Frame Size TLV, IEEE 802.3bc-2009 Section 79.3.4) did not include the length check and could over-read the input buffer, put it right. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125 Target: 1 Example 2: Code: ProcScreenSaverSuspend(ClientPtr client) { ScreenSaverSuspensionPtr *prev, this; REQUEST(xScreenSaverSuspendReq); REQUEST_SIZE_MATCH(xScreenSaverSuspendReq); /* Check if this client is suspending the screensaver */ for (prev = &suspendingClients; (this = *prev); prev = &this->next) if (this->pClient == client) break; if (this) { if (stuff->suspend == TRUE) this->count++; else if (--this->count == 0) FreeResource(this->clientResource, RT_NONE); return Success; } /* If we get to this point, this client isn't suspending the screensaver */ if (stuff->suspend == FALSE) return Success; /* * Allocate a suspension record for the client, and stop the screensaver * if it isn't already suspended by another client. We attach a resource ID * to the record, so the screensaver will be reenabled and the record freed * if the client disconnects without reenabling it first. */ this = malloc(sizeof(ScreenSaverSuspensionRec)); if (!this) return BadAlloc; this->next = NULL; this->pClient = client; this->count = 1; this->clientResource = FakeClientID(client->index); if (!AddResource(this->clientResource, SuspendType, (void *) this)) { free(this); return BadAlloc; } *prev = this; if (!screenSaverSuspended) { screenSaverSuspended = TRUE; FreeScreenSaverTimer(); } return Success; } Commit Message: CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int __init sha1_s390_init(void) { if (!crypt_s390_func_available(KIMD_SHA_1, CRYPT_S390_MSA)) return -EOPNOTSUPP; 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 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_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; } Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks. For configuration protocol options, use ND_TCHECK() and ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument. This fixes one case where the ND_TCHECK2() call they replace was not checking enough bytes. 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 Target: 1 Example 2: Code: int sk_wait_data(struct sock *sk, long *timeo) { int rc; DEFINE_WAIT(wait); prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); rc = sk_wait_event(sk, timeo, !skb_queue_empty(&sk->sk_receive_queue)); clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags); finish_wait(sk_sleep(sk), &wait); return rc; } Commit Message: net: sock: validate data_len before allocating skb in sock_alloc_send_pskb() We need to validate the number of pages consumed by data_len, otherwise frags array could be overflowed by userspace. So this patch validate data_len and return -EMSGSIZE when data_len may occupies more frags than MAX_SKB_FRAGS. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int ucma_event_handler(struct rdma_cm_id *cm_id, struct rdma_cm_event *event) { struct ucma_event *uevent; struct ucma_context *ctx = cm_id->context; int ret = 0; uevent = kzalloc(sizeof(*uevent), GFP_KERNEL); if (!uevent) return event->event == RDMA_CM_EVENT_CONNECT_REQUEST; mutex_lock(&ctx->file->mut); uevent->cm_id = cm_id; ucma_set_event_context(ctx, event, uevent); uevent->resp.event = event->event; uevent->resp.status = event->status; if (cm_id->qp_type == IB_QPT_UD) ucma_copy_ud_event(&uevent->resp.param.ud, &event->param.ud); else ucma_copy_conn_event(&uevent->resp.param.conn, &event->param.conn); if (event->event == RDMA_CM_EVENT_CONNECT_REQUEST) { if (!ctx->backlog) { ret = -ENOMEM; kfree(uevent); goto out; } ctx->backlog--; } else if (!ctx->uid || ctx->cm_id != cm_id) { /* * We ignore events for new connections until userspace has set * their context. This can only happen if an error occurs on a * new connection before the user accepts it. This is okay, * since the accept will just fail later. However, we do need * to release the underlying HW resources in case of a device * removal event. */ if (event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) ucma_removal_event_handler(cm_id); kfree(uevent); goto out; } list_add_tail(&uevent->list, &ctx->file->event_list); wake_up_interruptible(&ctx->file->poll_wait); if (event->event == RDMA_CM_EVENT_DEVICE_REMOVAL) ucma_removal_event_handler(cm_id); out: mutex_unlock(&ctx->file->mut); return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[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: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { WORD32 buf_size; pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; /* If dynamic bitstream buffer is not allocated and * header decode is done, then allocate dynamic bitstream buffer */ if((NULL == ps_dec->pu1_bits_buf_dynamic) && (ps_dec->i4_header_decoded & 1)) { WORD32 size; void *pv_buf; void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); RETURN_IF((NULL == pv_buf), IV_FAIL); ps_dec->pu1_bits_buf_dynamic = pv_buf; ps_dec->u4_dynamic_bits_buf_size = size; } if(ps_dec->pu1_bits_buf_dynamic) { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; buf_size = ps_dec->u4_dynamic_bits_buf_size; } else { pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; buf_size = ps_dec->u4_static_bits_buf_size; } u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ buflen = MIN(buflen, buf_size); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); /* Decoder may read extra 8 bytes near end of the frame */ if((buflen + 8) < buf_size) { memset(pu1_bitstrm_buf + buflen, 0, 8); } u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && (ret != IVD_MEM_ALLOC_FAILED) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) { return IV_FAIL; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_MEM_ALLOC_FAILED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Fix slice number increment for error clips Bug: 28673410 CWE ID: CWE-119 Target: 1 Example 2: Code: static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } Commit Message: Don't overflow item refcount on get Counts as a miss if the refcount is too high. ASCII multigets are the only time refcounts can be held for so long. doing a dirty read of refcount. is aligned. trying to avoid adding an extra refcount branch for all calls of item_get due to performance. might be able to move it in there after logging refactoring simplifies some of the branches. CWE ID: CWE-190 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); env->insn_aux_data = new_data; vfree(old_data); return 0; } Commit Message: bpf: fix branch pruning logic when the verifier detects that register contains a runtime constant and it's compared with another constant it will prune exploration of the branch that is guaranteed not to be taken at runtime. This is all correct, but malicious program may be constructed in such a way that it always has a constant comparison and the other branch is never taken under any conditions. In this case such path through the program will not be explored by the verifier. It won't be taken at run-time either, but since all instructions are JITed the malicious program may cause JITs to complain about using reserved fields, etc. To fix the issue we have to track the instructions explored by the verifier and sanitize instructions that are dead at run time with NOPs. We cannot reject such dead code, since llvm generates it for valid C code, since it doesn't do as much data flow analysis as the verifier does. Fixes: 17a5267067f3 ("bpf: verifier (add verifier core)") Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-20 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 flush_tmregs_to_thread(struct task_struct *tsk) { /* * If task is not current, it will have been flushed already to * it's thread_struct during __switch_to(). * * A reclaim flushes ALL the state or if not in TM save TM SPRs * in the appropriate thread structures from live. */ if (tsk != current) return; if (MSR_TM_SUSPENDED(mfmsr())) { tm_reclaim_current(TM_CAUSE_SIGNAL); } else { tm_enable(); tm_save_sprs(&(tsk->thread)); } } Commit Message: powerpc/tm: Flush TM only if CPU has TM feature Commit cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") added code to access TM SPRs in flush_tmregs_to_thread(). However flush_tmregs_to_thread() does not check if TM feature is available on CPU before trying to access TM SPRs in order to copy live state to thread structures. flush_tmregs_to_thread() is indeed guarded by CONFIG_PPC_TRANSACTIONAL_MEM but it might be the case that kernel was compiled with CONFIG_PPC_TRANSACTIONAL_MEM enabled and ran on a CPU without TM feature available, thus rendering the execution of TM instructions that are treated by the CPU as illegal instructions. The fix is just to add proper checking in flush_tmregs_to_thread() if CPU has the TM feature before accessing any TM-specific resource, returning immediately if TM is no available on the CPU. Adding that checking in flush_tmregs_to_thread() instead of in places where it is called, like in vsr_get() and vsr_set(), is better because avoids the same problem cropping up elsewhere. Cc: [email protected] # v4.13+ Fixes: cd63f3c ("powerpc/tm: Fix saving of TM SPRs in core dump") Signed-off-by: Gustavo Romero <[email protected]> Reviewed-by: Cyril Bur <[email protected]> Signed-off-by: Michael Ellerman <[email protected]> CWE ID: CWE-119 Target: 1 Example 2: Code: static enum test_return cache_redzone_test(void) { #ifndef HAVE_UMEM_H cache_t *cache = cache_create("test", sizeof(uint32_t), sizeof(char*), NULL, NULL); /* Ignore SIGABORT */ struct sigaction old_action; struct sigaction action = { .sa_handler = SIG_IGN, .sa_flags = 0}; sigemptyset(&action.sa_mask); sigaction(SIGABRT, &action, &old_action); /* check memory debug.. */ char *p = cache_alloc(cache); char old = *(p - 1); *(p - 1) = 0; cache_free(cache, p); assert(cache_error == -1); *(p - 1) = old; p[sizeof(uint32_t)] = 0; cache_free(cache, p); assert(cache_error == 1); /* restore signal handler */ sigaction(SIGABRT, &old_action, NULL); cache_destroy(cache); return TEST_PASS; #else return TEST_SKIP; #endif } Commit Message: Issue 102: Piping null to the server will crash it 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: const AutocompleteResult& AutocompleteEditModel::result() const { return autocomplete_controller_->result(); } Commit Message: Adds per-provider information to omnibox UMA logs. Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future. BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10380007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: Output:
0
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: base::string16 IDNToUnicodeWithAdjustments( base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) { if (adjustments) adjustments->clear(); base::string16 input16; input16.reserve(host.length()); input16.insert(input16.end(), host.begin(), host.end()); base::string16 out16; for (size_t component_start = 0, component_end; component_start < input16.length(); component_start = component_end + 1) { component_end = input16.find('.', component_start); if (component_end == base::string16::npos) component_end = input16.length(); // For getting the last component. size_t component_length = component_end - component_start; size_t new_component_start = out16.length(); bool converted_idn = false; if (component_end > component_start) { converted_idn = IDNToUnicodeOneComponent(input16.data() + component_start, component_length, &out16); } size_t new_component_length = out16.length() - new_component_start; if (converted_idn && adjustments) { adjustments->push_back(base::OffsetAdjuster::Adjustment( component_start, component_length, new_component_length)); } if (component_end < input16.length()) out16.push_back('.'); } return out16; } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20 Target: 1 Example 2: Code: vop_query_offset(struct vop_vdev *vdev, unsigned long offset, unsigned long *size, unsigned long *pa) { struct vop_device *vpdev = vdev->vpdev; unsigned long start = MIC_DP_SIZE; int i; /* * MMAP interface is as follows: * offset region * 0x0 virtio device_page * 0x1000 first vring * 0x1000 + size of 1st vring second vring * .... */ if (!offset) { *pa = virt_to_phys(vpdev->hw_ops->get_dp(vpdev)); *size = MIC_DP_SIZE; return 0; } for (i = 0; i < vdev->dd->num_vq; i++) { struct vop_vringh *vvr = &vdev->vvr[i]; if (offset == start) { *pa = virt_to_phys(vvr->vring.va); *size = vvr->vring.len; return 0; } start += vvr->vring.len; } return -1; } Commit Message: misc: mic: Fix for double fetch security bug in VOP driver The MIC VOP driver does two successive reads from user space to read a variable length data structure. Kernel memory corruption can result if the data structure changes between the two reads. This patch disallows the chance of this happening. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=116651 Reported by: Pengfei Wang <[email protected]> Reviewed-by: Sudeep Dutt <[email protected]> Signed-off-by: Ashutosh Dixit <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: n_tty_receive_buf_fast(struct tty_struct *tty, const unsigned char *cp, char *fp, int count) { struct n_tty_data *ldata = tty->disc_data; char flag = TTY_NORMAL; while (count--) { if (fp) flag = *fp++; if (likely(flag == TTY_NORMAL)) { unsigned char c = *cp++; if (!test_bit(c, ldata->char_map)) n_tty_receive_char_fast(tty, c); else if (n_tty_receive_char_special(tty, c) && count) { if (fp) flag = *fp++; n_tty_receive_char_lnext(tty, *cp++, flag); count--; } } else n_tty_receive_char_flagged(tty, *cp++, flag); } } Commit Message: n_tty: Fix n_tty_write crash when echoing in raw mode The tty atomic_write_lock does not provide an exclusion guarantee for the tty driver if the termios settings are LECHO & !OPOST. And since it is unexpected and not allowed to call TTY buffer helpers like tty_insert_flip_string concurrently, this may lead to crashes when concurrect writers call pty_write. In that case the following two writers: * the ECHOing from a workqueue and * pty_write from the process race and can overflow the corresponding TTY buffer like follows. If we look into tty_insert_flip_string_fixed_flag, there is: int space = __tty_buffer_request_room(port, goal, flags); struct tty_buffer *tb = port->buf.tail; ... memcpy(char_buf_ptr(tb, tb->used), chars, space); ... tb->used += space; so the race of the two can result in something like this: A B __tty_buffer_request_room __tty_buffer_request_room memcpy(buf(tb->used), ...) tb->used += space; memcpy(buf(tb->used), ...) ->BOOM B's memcpy is past the tty_buffer due to the previous A's tb->used increment. Since the N_TTY line discipline input processing can output concurrently with a tty write, obtain the N_TTY ldisc output_lock to serialize echo output with normal tty writes. This ensures the tty buffer helper tty_insert_flip_string is not called concurrently and everything is fine. Note that this is nicely reproducible by an ordinary user using forkpty and some setup around that (raw termios + ECHO). And it is present in kernels at least after commit d945cb9cce20ac7143c2de8d88b187f62db99bdc (pty: Rework the pty layer to use the normal buffering logic) in 2.6.31-rc3. js: add more info to the commit log js: switch to bool js: lock unconditionally js: lock only the tty->ops->write call References: CVE-2014-0196 Reported-and-tested-by: Jiri Slaby <[email protected]> Signed-off-by: Peter Hurley <[email protected]> Signed-off-by: Jiri Slaby <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: Alan Cox <[email protected]> Cc: <[email protected]> Signed-off-by: Greg Kroah-Hartman <[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: EncodedJSValue JSC_HOST_CALL JSTestInterfaceConstructor::constructJSTestInterface(ExecState* exec) { JSTestInterfaceConstructor* castedThis = jsCast<JSTestInterfaceConstructor*>(exec->callee()); if (exec->argumentCount() < 1) return throwVMError(exec, createTypeError(exec, "Not enough arguments")); ExceptionCode ec = 0; const String& str1(ustringToString(MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 0, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); const String& str2(ustringToString(MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).isEmpty() ? UString() : MAYBE_MISSING_PARAMETER(exec, 1, DefaultIsUndefined).toString(exec)->value(exec))); if (exec->hadException()) return JSValue::encode(jsUndefined()); ScriptExecutionContext* context = castedThis->scriptExecutionContext(); if (!context) return throwVMError(exec, createReferenceError(exec, "TestInterface constructor associated document is unavailable")); RefPtr<TestInterface> object = TestInterface::create(context, str1, str2, ec); if (ec) { setDOMException(exec, ec); return JSValue::encode(JSValue()); } return JSValue::encode(asObject(toJS(exec, castedThis->globalObject(), object.get()))); } Commit Message: [JSC] Implement a helper method createNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=85102 Reviewed by Geoffrey Garen. In bug 84787, kbr@ requested to avoid hard-coding createTypeError(exec, "Not enough arguments") here and there. This patch implements createNotEnoughArgumentsError(exec) and uses it in JSC bindings. c.f. a corresponding bug for V8 bindings is bug 85097. Source/JavaScriptCore: * runtime/Error.cpp: (JSC::createNotEnoughArgumentsError): (JSC): * runtime/Error.h: (JSC): Source/WebCore: Test: bindings/scripts/test/TestObj.idl * bindings/scripts/CodeGeneratorJS.pm: Modified as described above. (GenerateArgumentsCountCheck): * bindings/js/JSDataViewCustom.cpp: Ditto. (WebCore::getDataViewMember): (WebCore::setDataViewMember): * bindings/js/JSDeprecatedPeerConnectionCustom.cpp: (WebCore::JSDeprecatedPeerConnectionConstructor::constructJSDeprecatedPeerConnection): * bindings/js/JSDirectoryEntryCustom.cpp: (WebCore::JSDirectoryEntry::getFile): (WebCore::JSDirectoryEntry::getDirectory): * bindings/js/JSSharedWorkerCustom.cpp: (WebCore::JSSharedWorkerConstructor::constructJSSharedWorker): * bindings/js/JSWebKitMutationObserverCustom.cpp: (WebCore::JSWebKitMutationObserverConstructor::constructJSWebKitMutationObserver): (WebCore::JSWebKitMutationObserver::observe): * bindings/js/JSWorkerCustom.cpp: (WebCore::JSWorkerConstructor::constructJSWorker): * bindings/scripts/test/JS/JSFloat64Array.cpp: Updated run-bindings-tests. (WebCore::jsFloat64ArrayPrototypeFunctionFoo): * bindings/scripts/test/JS/JSTestActiveDOMObject.cpp: (WebCore::jsTestActiveDOMObjectPrototypeFunctionExcitingFunction): (WebCore::jsTestActiveDOMObjectPrototypeFunctionPostMessage): * bindings/scripts/test/JS/JSTestCustomNamedGetter.cpp: (WebCore::jsTestCustomNamedGetterPrototypeFunctionAnotherFunction): * bindings/scripts/test/JS/JSTestEventTarget.cpp: (WebCore::jsTestEventTargetPrototypeFunctionItem): (WebCore::jsTestEventTargetPrototypeFunctionAddEventListener): (WebCore::jsTestEventTargetPrototypeFunctionRemoveEventListener): (WebCore::jsTestEventTargetPrototypeFunctionDispatchEvent): * bindings/scripts/test/JS/JSTestInterface.cpp: (WebCore::JSTestInterfaceConstructor::constructJSTestInterface): (WebCore::jsTestInterfacePrototypeFunctionSupplementalMethod2): * bindings/scripts/test/JS/JSTestMediaQueryListListener.cpp: (WebCore::jsTestMediaQueryListListenerPrototypeFunctionMethod): * bindings/scripts/test/JS/JSTestNamedConstructor.cpp: (WebCore::JSTestNamedConstructorNamedConstructor::constructJSTestNamedConstructor): * bindings/scripts/test/JS/JSTestObj.cpp: (WebCore::JSTestObjConstructor::constructJSTestObj): (WebCore::jsTestObjPrototypeFunctionVoidMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionIntMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionObjMethodWithArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithSequenceArg): (WebCore::jsTestObjPrototypeFunctionMethodReturningSequence): (WebCore::jsTestObjPrototypeFunctionMethodThatRequiresAllArgsAndThrows): (WebCore::jsTestObjPrototypeFunctionSerializedValue): (WebCore::jsTestObjPrototypeFunctionIdbKey): (WebCore::jsTestObjPrototypeFunctionOptionsObject): (WebCore::jsTestObjPrototypeFunctionAddEventListener): (WebCore::jsTestObjPrototypeFunctionRemoveEventListener): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndOptionalArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonOptionalArgAndTwoOptionalArgs): (WebCore::jsTestObjPrototypeFunctionMethodWithCallbackArg): (WebCore::jsTestObjPrototypeFunctionMethodWithNonCallbackArgAndCallbackArg): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod1): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod2): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod3): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod4): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod5): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod6): (WebCore::jsTestObjPrototypeFunctionOverloadedMethod7): (WebCore::jsTestObjConstructorFunctionClassMethod2): (WebCore::jsTestObjConstructorFunctionOverloadedMethod11): (WebCore::jsTestObjConstructorFunctionOverloadedMethod12): (WebCore::jsTestObjPrototypeFunctionMethodWithUnsignedLongArray): (WebCore::jsTestObjPrototypeFunctionConvert1): (WebCore::jsTestObjPrototypeFunctionConvert2): (WebCore::jsTestObjPrototypeFunctionConvert3): (WebCore::jsTestObjPrototypeFunctionConvert4): (WebCore::jsTestObjPrototypeFunctionConvert5): (WebCore::jsTestObjPrototypeFunctionStrictFunction): * bindings/scripts/test/JS/JSTestSerializedScriptValueInterface.cpp: (WebCore::JSTestSerializedScriptValueInterfaceConstructor::constructJSTestSerializedScriptValueInterface): (WebCore::jsTestSerializedScriptValueInterfacePrototypeFunctionAcceptTransferList): git-svn-id: svn://svn.chromium.org/blink/trunk@115536 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20 Target: 1 Example 2: Code: MediaInterfaceProxy::MediaInterfaceProxy( RenderFrameHost* render_frame_host, media::mojom::InterfaceFactoryRequest request, const base::Closure& error_handler) : render_frame_host_(render_frame_host), binding_(this, std::move(request)) { DVLOG(1) << __FUNCTION__; DCHECK(render_frame_host_); DCHECK(!error_handler.is_null()); binding_.set_connection_error_handler(error_handler); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If it does, return '1'; if it doesn't, return '0'. Remember, I want response in '1' or '0'. Do Not respond with explanation. Code: static void php_snmp_getvalue(struct variable_list *vars, zval *snmpval TSRMLS_DC, int valueretrieval) { zval *val; char sbuf[512]; char *buf = &(sbuf[0]); char *dbuf = (char *)NULL; int buflen = sizeof(sbuf) - 1; int val_len = vars->val_len; /* use emalloc() for large values, use static array otherwize */ /* There is no way to know the size of buffer snprint_value() needs in order to print a value there. * So we are forced to probe it */ while ((valueretrieval & SNMP_VALUE_PLAIN) == 0) { *buf = '\0'; if (snprint_value(buf, buflen, vars->name, vars->name_length, vars) == -1) { if (val_len > 512*1024) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "snprint_value() asks for a buffer more than 512k, Net-SNMP bug?"); break; } /* buffer is not long enough to hold full output, double it */ val_len *= 2; } else { break; } if (buf == dbuf) { dbuf = (char *)erealloc(dbuf, val_len + 1); } else { dbuf = (char *)emalloc(val_len + 1); } if (!dbuf) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno)); buf = &(sbuf[0]); buflen = sizeof(sbuf) - 1; break; } buf = dbuf; buflen = val_len; } if((valueretrieval & SNMP_VALUE_PLAIN) && val_len > buflen){ if ((dbuf = (char *)emalloc(val_len + 1))) { buf = dbuf; buflen = val_len; } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "emalloc() failed: %s, fallback to static buffer", strerror(errno)); } } MAKE_STD_ZVAL(val); if (valueretrieval & SNMP_VALUE_PLAIN) { *buf = 0; switch (vars->type) { case ASN_BIT_STR: /* 0x03, asn1.h */ ZVAL_STRINGL(val, (char *)vars->val.bitstring, vars->val_len, 1); break; case ASN_OCTET_STR: /* 0x04, asn1.h */ case ASN_OPAQUE: /* 0x44, snmp_impl.h */ ZVAL_STRINGL(val, (char *)vars->val.string, vars->val_len, 1); break; case ASN_NULL: /* 0x05, asn1.h */ ZVAL_NULL(val); break; case ASN_OBJECT_ID: /* 0x06, asn1.h */ snprint_objid(buf, buflen, vars->val.objid, vars->val_len / sizeof(oid)); ZVAL_STRING(val, buf, 1); break; case ASN_IPADDRESS: /* 0x40, snmp_impl.h */ snprintf(buf, buflen, "%d.%d.%d.%d", (vars->val.string)[0], (vars->val.string)[1], (vars->val.string)[2], (vars->val.string)[3]); buf[buflen]=0; ZVAL_STRING(val, buf, 1); break; case ASN_COUNTER: /* 0x41, snmp_impl.h */ case ASN_GAUGE: /* 0x42, snmp_impl.h */ /* ASN_UNSIGNED is the same as ASN_GAUGE */ case ASN_TIMETICKS: /* 0x43, snmp_impl.h */ case ASN_UINTEGER: /* 0x47, snmp_impl.h */ snprintf(buf, buflen, "%lu", *vars->val.integer); buf[buflen]=0; ZVAL_STRING(val, buf, 1); break; case ASN_INTEGER: /* 0x02, asn1.h */ snprintf(buf, buflen, "%ld", *vars->val.integer); buf[buflen]=0; ZVAL_STRING(val, buf, 1); break; #if defined(NETSNMP_WITH_OPAQUE_SPECIAL_TYPES) || defined(OPAQUE_SPECIAL_TYPES) case ASN_OPAQUE_FLOAT: /* 0x78, asn1.h */ snprintf(buf, buflen, "%f", *vars->val.floatVal); ZVAL_STRING(val, buf, 1); break; case ASN_OPAQUE_DOUBLE: /* 0x79, asn1.h */ snprintf(buf, buflen, "%Lf", *vars->val.doubleVal); ZVAL_STRING(val, buf, 1); break; case ASN_OPAQUE_I64: /* 0x80, asn1.h */ printI64(buf, vars->val.counter64); ZVAL_STRING(val, buf, 1); break; case ASN_OPAQUE_U64: /* 0x81, asn1.h */ #endif case ASN_COUNTER64: /* 0x46, snmp_impl.h */ printU64(buf, vars->val.counter64); ZVAL_STRING(val, buf, 1); break; default: ZVAL_STRING(val, "Unknown value type", 1); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown value type: %u", vars->type); break; } } else /* use Net-SNMP value translation */ { /* we have desired string in buffer, just use it */ ZVAL_STRING(val, buf, 1); } if (valueretrieval & SNMP_VALUE_OBJECT) { object_init(snmpval); add_property_long(snmpval, "type", vars->type); add_property_zval(snmpval, "value", val); } else { *snmpval = *val; zval_copy_ctor(snmpval); } zval_ptr_dtor(&val); if(dbuf){ /* malloc was used to store value */ efree(dbuf); } } Commit Message: CWE ID: CWE-416 Output:
1
Here are some example code snippets. Analyze the following code, commit message, CWE ID and the target value where 1 indicates the code has vulnerability and 0 indicates non-vulnerable code. Example 1: Code: bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } Commit Message: CWE ID: CWE-399 Target: 1 Example 2: Code: static int read_reuc(git_index *index, const char *buffer, size_t size) { const char *endptr; size_t len; int i; /* If called multiple times, the vector might already be initialized */ if (index->reuc._alloc_size == 0 && git_vector_init(&index->reuc, 16, reuc_cmp) < 0) return -1; while (size) { git_index_reuc_entry *lost; len = p_strnlen(buffer, size) + 1; if (size <= len) return index_error_invalid("reading reuc entries"); lost = reuc_entry_alloc(buffer); GITERR_CHECK_ALLOC(lost); size -= len; buffer += len; /* read 3 ASCII octal numbers for stage entries */ for (i = 0; i < 3; i++) { int64_t tmp; if (git__strtol64(&tmp, buffer, &endptr, 8) < 0 || !endptr || endptr == buffer || *endptr || tmp < 0 || tmp > UINT32_MAX) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } lost->mode[i] = (uint32_t)tmp; len = (endptr + 1) - buffer; if (size <= len) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } size -= len; buffer += len; } /* read up to 3 OIDs for stage entries */ for (i = 0; i < 3; i++) { if (!lost->mode[i]) continue; if (size < 20) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry oid"); } git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer); size -= 20; buffer += 20; } /* entry was read successfully - insert into reuc vector */ if (git_vector_insert(&index->reuc, lost) < 0) return -1; } /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->reuc, true); return 0; } Commit Message: index: convert `read_entry` to return entry size via an out-param The function `read_entry` does not conform to our usual coding style of returning stuff via the out parameter and to use the return value for reporting errors. Due to most of our code conforming to that pattern, it has become quite natural for us to actually return `-1` in case there is any error, which has also slipped in with commit 5625d86b9 (index: support index v4, 2016-05-17). As the function returns an `size_t` only, though, the return value is wrapped around, causing the caller of `read_tree` to continue with an invalid index entry. Ultimately, this can lead to a double-free. Improve code and fix the bug by converting the function to return the index entry size via an out parameter and only using the return value to indicate errors. Reported-by: Krishna Ram Prakash R <[email protected]> Reported-by: Vivek Parikh <[email protected]> CWE ID: CWE-415 Target: 0 Now analyze the following code, commit message, and CWE ID. Determine whether it has a vulnerability. If 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 ResetState() { nav_handle1_.reset(); nav_handle2_.reset(); nav_handle3_.reset(); throttle1_.reset(); throttle2_.reset(); throttle3_.reset(); contents1_.reset(); contents2_.reset(); contents3_.reset(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID: Output:
1